@aglyn/tenant-feature-instance 1.20.2 → 1.20.3

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.20.2",
3
+ "version": "1.20.3",
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.20.2",
29
- "@aglyn/shared-data-enums": "1.20.2",
30
- "@aglyn/shared-ui-jsx": "1.20.2",
31
- "@aglyn/shared-util-email": "1.20.2",
32
- "@aglyn/shared-util-http": "1.20.2",
33
- "@aglyn/shared-util-timestamp": "1.20.2",
28
+ "@aglyn/aglyn": "1.20.3",
29
+ "@aglyn/shared-data-enums": "1.20.3",
30
+ "@aglyn/shared-ui-jsx": "1.20.3",
31
+ "@aglyn/shared-util-email": "1.20.3",
32
+ "@aglyn/shared-util-http": "1.20.3",
33
+ "@aglyn/shared-util-timestamp": "1.20.3",
34
34
  "@swc/helpers": "0.5.23",
35
35
  "lodash-es": "^4.18.1",
36
36
  "mobx": "^7.0.5"
@@ -33,6 +33,7 @@ import { createAuthInstance } from "./auth-persistence.js";
33
33
  import { firestoreCacheClassFor, localCacheFor, pruneSharedClientStateFor } from "./firestore-cache.js";
34
34
  import { keepAppCheckRecaptchaContainer } from "./app-check-recaptcha-container.js";
35
35
  import { confirmSharedCacheLock, markMultiTabFirestore, startBootWedgeCheck } from "./firestore-multitab-wedge.js";
36
+ import { startPageWedgeChecks } from "./firestore-page-wedge-check.js";
36
37
  import { firestoreHasServerAnswered } from "./firestore-stall-recovery.js";
37
38
  import { firestorePersistencePrefix } from "./firestore-shared-client-state.js";
38
39
  import { startFirestorePrimaryYield } from "./firestore-primary-yield.js";
@@ -253,6 +254,9 @@ let analyticsConsentGate = null;
253
254
  // A tab still booting finds another tab's lock in seconds, not
254
255
  // the ~37 s the in-use rescue budgets (AGL-4201).
255
256
  void startBootWedgeCheck(getFirestore(app), ()=>firestoreHasServerAnswered(getFirestore(app)));
257
+ // And so does each page opened later in this tab, until it is
258
+ // used (AGL-4204). The tab's lifetime: never stopped.
259
+ startPageWedgeChecks(getFirestore(app));
256
260
  // A visible tab opened while a background tab holds the shared
257
261
  // cache's lease takes the lease at boot instead of routing every
258
262
  // query through the background tab until its lease lapses
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firebase-services.tsx"],"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'use client'\n\nimport {\n type FirebaseApp,\n type FirebaseOptions,\n getApps,\n initializeApp,\n} from 'firebase/app'\nimport {\n type Analytics,\n getAnalytics as getAnalyticsInstance,\n initializeAnalytics as initializeAnalyticsInstance,\n} from 'firebase/analytics'\nimport { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check'\nimport { analyticsMayEmit } from '@aglyn/aglyn/app-utils/analytics-environment'\nimport { pushPlatformConsentDefault } from '@aglyn/aglyn/app-utils/platform-consent-default'\nimport { VISITOR_CONSENT_CHANGED_EVENT } from '@aglyn/aglyn/app-utils/visitor-consent'\nimport {\n type Auth,\n connectAuthEmulator,\n onIdTokenChanged,\n type User,\n} from 'firebase/auth'\nimport {\n type Firestore,\n connectFirestoreEmulator,\n getFirestore,\n initializeFirestore,\n} from 'firebase/firestore'\nimport {\n type RemoteConfig,\n getRemoteConfig as getRemoteConfigInstance,\n} from 'firebase/remote-config'\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react'\nimport {\n FIREBASE_AUTH_EMULATOR_ENABLED,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED,\n} from '@aglyn/shared-data-enums'\nimport {\n APP_CHECK_KEY_MISSING_MESSAGE,\n appCheckSiteKey,\n} from '../../constants/firebase-config'\nimport {\n authEmulatorUrl,\n firestoreEmulatorHost,\n} from '../../constants/firebase-emulator-hosts'\nimport {\n type AuthPersistenceClass,\n createAuthInstance,\n} from './auth-persistence'\nimport {\n firestoreCacheClassFor,\n localCacheFor,\n pruneSharedClientStateFor,\n} from './firestore-cache'\nimport { keepAppCheckRecaptchaContainer } from './app-check-recaptcha-container'\nimport type { ListenHandle } from '../helpers/listen-confirmation'\nimport {\n confirmSharedCacheLock,\n markMultiTabFirestore,\n startBootWedgeCheck,\n} from './firestore-multitab-wedge'\nimport { firestoreHasServerAnswered } from './firestore-stall-recovery'\nimport { firestorePersistencePrefix } from './firestore-shared-client-state'\nimport { startFirestorePrimaryYield } from './firestore-primary-yield'\nimport { startFirestoreTabHandoff } from './firestore-tab-handoff'\n\n/**\n * Drop-in replacement for reactfire's `ObservableStatus<T>` — reactfire is\n * unmaintained against firebase majors past v9, but its shape is preserved\n * here so `helpers/use-doc.ts`'s already-battle-tested onSnapshot+retry\n * implementation (AGL-216/223) didn't need to change.\n */\nexport interface ObservableStatus<T> {\n status: 'loading' | 'error' | 'success'\n hasEmitted: boolean\n isComplete: boolean\n data: T\n error: Error | undefined\n firstValuePromise: Promise<void>\n /**\n * The emitted `data` includes local writes the server has NOT\n * acknowledged (`snapshot.metadata.hasPendingWrites`).\n *\n * Carried rather than dropped because a caller cannot otherwise tell \"the\n * store holds this\" from \"my browser holds this\". `persistentLocalCache`\n * replays a queued write into the very first snapshot after a reload, so a\n * caller that treats every snapshot as authoritative will adopt its own\n * unacknowledged edit as the saved state — which is how the besigner ended\n * up unable to save real changes (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * The emitted `data` came from the local cache and the server has NOT\n * confirmed it (`snapshot.metadata.fromCache`).\n *\n * Carried because it is the only per-listener ground truth about\n * freshness the SDK offers, and the console needs it (AGL-1066). Under\n * `persistentLocalCache` a listener whose server listen is being REFUSED\n * still emits cached snapshots and still reports `status: 'success'` —\n * the retry budget is reset by each cached emission and never spends, so\n * `status` can never reveal the fault (see\n * `use-firestore-collection-cached-retry.spec.ts`).\n *\n * Prefer this over `session-health`'s `staleSession` for anything that\n * asks \"is what I am looking at live?\". `staleSession` is a heuristic\n * needing two denied collections inside a window, and it is unreachable\n * on listener-only pages; this is a fact about THIS listener, costs\n * nothing, and clears itself the instant a server snapshot lands.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget, and\n * no server snapshot has arrived since (AGL-1066).\n *\n * `fromCache` says \"unconfirmed\", which is also true offline and true for\n * the first snapshot of a perfectly healthy load. This says \"refused\" —\n * only `permission-denied` counts it, and it takes a whole budget's worth\n * in a row, so it cannot fire offline and cannot fire on the AGL-216/217\n * post-sign-in token race.\n *\n * It is what `status` would say if the retry budget were spendable. It is\n * carried separately because correcting `status` in place would blank\n * every surface that renders cached data through an `error` branch — see\n * the note on `attempt = 0` in `use-firestore-collection`.\n */\n serverDenied: boolean\n /**\n * This hook's listener, for a guarded save seeded from `data` to wait on\n * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of\n * the hook.\n */\n listen: ListenHandle\n}\n\n/** Replaces reactfire's `ReactFireOptions<T>` — drops the `suspense` field, which was never read. */\nexport interface FirestoreDocOptions<T> {\n idField?: string\n initialData?: T\n}\n\n/**\n * The Firebase products this provider builds, and therefore the ones every\n * page that renders it downloads.\n *\n * ⛔ NO Realtime Database and NO Cloud Storage (AGL-2706). Both were built\n * here and published as `useDatabase()` / `useStorage()`, and neither hook had\n * a single caller anywhere in the repo — so `@firebase/database` (125.9 KB\n * raw) and `@firebase/storage` (13.9 KB) were in the first load of every\n * console route to satisfy a context field nothing read.\n *\n * Realtime Database IS used, by `apps/console/hooks/use-presence.ts` and\n * `use-coediting.ts` — on their own Firebase app, with their own\n * `getDatabase`, behind the editor routes that need presence. That is the\n * shape to copy if a surface needs one of these: reach for the product where\n * the feature is, not in the provider every page mounts. A field here is paid\n * for by every route, used or not.\n */\ninterface FirebaseServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n analytics: Analytics\n remoteConfig: RemoteConfig\n /**\n * The persistence class `auth` was actually created with (AGL-1379).\n *\n * Published so a **second** auth instance derives its class from the\n * primary rather than re-deciding it. `apps/console/hooks/use-presence.ts`\n * builds its own Firebase app and its own `Auth`; before this it took the\n * SDK default unconditionally, so configuring only the provider would have\n * left presence persisting a refresh token on an origin the provider had\n * just been careful not to persist one on.\n */\n authPersistence: AuthPersistenceClass\n}\n\nconst FirebaseServicesContext = createContext<FirebaseServices | undefined>(undefined)\n\n// Module-scope guards so HMR / remounts don't re-run emulator connection\n// (which throws if called twice) or double-initialize Firestore's\n// persistent cache.\n//\n// Firestore's is keyed by app NAME, not a bare boolean (AGL-1456): Firestore\n// initialization is once-per-app, so a module-global flag made the FIRST app\n// to mount decide for every later one — a second app would silently skip\n// `initializeFirestore` and take SDK defaults. That mattered the moment the\n// cache stopped being the same on every host.\nconst firestoreInitialized = new Set<string>()\nlet connectedAuth = false\n\n/**\n * True when THIS Chrome instance is under WebDriver automation control\n * (Puppeteer, Playwright, Selenium, or a raw CDP client) — never true for a\n * person's own browser.\n *\n * The `initializeFirestore` call below already documents the fault this\n * exists for: \"the emulator's WebChannel streaming misbehaves in automated\n * Chrome — listeners serve the initial empty from-cache snapshot and the\n * server sync never arrives\" (AGL-217). That mitigation only reaches\n * `FIREBASE_FIRESTORE_EMULATOR_ENABLED`, so an automated session against a\n * REAL, deployed backend — a browser-automation agent driving a live\n * console, which is exactly what `navigator.webdriver` detects — stayed\n * exposed. `getDocs`/`getDoc` and `onSnapshot` all resolve over the same\n * Watch stream internally, so a one-shot read wedges exactly like a listener\n * does: no error, nothing to catch, `loading` simply never gets its\n * settling event. That is the Media Library grid spinning on \"Loading\n * media…\" indefinitely with a perfectly healthy account and a perfectly\n * healthy network.\n *\n * `undefined` during SSR reads as `false` — `navigator` does not exist in\n * Node, and a server render can only ever produce the auto-detected\n * transport, never the forced one.\n */\nconst isAutomatedChromeSession = (): boolean =>\n typeof navigator !== 'undefined' && navigator.webdriver === true\n\n/**\n * The console tag's gtag config — ONE object, at module scope, deliberately\n * (AGL-1979).\n *\n * `initializeAnalytics(app, options)` throws `already-initialized` unless the\n * options `deepEqual` the ones the instance was first created with, and the\n * provider re-enters this block on every mount, every StrictMode double\n * invoke and every Fast Refresh. A fresh object literal per call survives\n * that only by *value*; a shared constant survives it by *identity*, which is\n * the first branch of the SDK's own comparison and cannot drift when someone\n * edits one call site and not another.\n *\n * ⚠️ The SDK MUTATES this object: `_initializeAnalytics` reads `options.config`\n * and writes `origin`, `update` and the installation id onto it in place.\n * That is precisely why sharing it is safe rather than dangerous — the object\n * the provider holds and the object the SDK stored are the same one, so they\n * cannot disagree.\n */\nconst CONSOLE_ANALYTICS_OPTIONS = {\n config: { send_page_view: false, content_group: 'console' },\n}\n\n/**\n * A surface's answer to \"may an analytics tag exist for this visitor at all?\".\n *\n * Registered from the app, at module scope, in the same shape as\n * `setFirestoreSessionReporters` and `setStaleSessionCheck` — and for a\n * sharper version of the same reason. This is consulted during the provider's\n * FIRST render, before any effect anywhere has run, so a gate installed from\n * an effect would arrive after the decision it exists to make.\n *\n * Answering `false` means the SDK is never asked to initialize: `gtag.js` is\n * never fetched, `window.gtag` never comes into existence, and the shared\n * `deliver()` in `analytics-events.ts` — whose fallback IS `window.gtag` —\n * therefore has nowhere to put a hit. That is the difference between a gate\n * and a suppression, and it is the difference AGL-1608 paid for: a resident\n * tag reports on its own, through enhanced measurement, whatever any flag\n * says afterwards.\n */\nexport type AnalyticsConsentGate = () => boolean\n\nlet analyticsConsentGate: AnalyticsConsentGate | null = null\n\n/**\n * Install the consent gate for this document, or clear it with `null`.\n *\n * UNREGISTERED MEANS ALLOWED, which is deliberate and is the only default that\n * is safe here. The tenant runtime does not use this provider's analytics\n * branch at all (it builds its own tag in `site-analytics.tsx`, behind the\n * AGL-1498 gate), and a self-hosted console points at the operator's own GA\n * property — silencing an operator's analytics because Aglyn's own surface\n * grew a gate is a failure they cannot diagnose. The surface that needs the\n * gate is the one that registers it.\n */\nexport function setAnalyticsConsentGate(\n gate: AnalyticsConsentGate | null,\n): void {\n analyticsConsentGate = gate\n}\n\n/** The gate's verdict, with an unregistered gate reading as \"allowed\". */\nfunction analyticsConsentAllows(): boolean {\n if (analyticsConsentGate === null) return true\n try {\n return analyticsConsentGate() === true\n } catch {\n // A gate that throws cannot be read as consent. Storage can throw in\n // private mode, and \"we could not tell\" is the one state this whole\n // mechanism resolves to \"no\".\n return false\n }\n}\n\n/**\n * The Analytics instance per Firebase app, so a re-boot after a consent change\n * hands back the tag that is already resident rather than asking the SDK for a\n * second one.\n *\n * `initializeAnalytics` is idempotent while the options match, so this is not\n * what makes re-entry safe — `CONSOLE_ANALYTICS_OPTIONS` being a shared\n * constant is. What this avoids is the noisy path: once anything has\n * initialized the provider with different options, every later call throws and\n * is logged, and a withdrawal followed by a re-grant would log it again.\n */\nconst analyticsByApp = new WeakMap<FirebaseApp, Analytics>()\n\n/**\n * Boot the console's Analytics tag, or return the one already booted.\n *\n * Extracted from the provider body so that \"when is the tag created\" and \"may\n * it be created\" are separable: the consent gate can defer this call to a\n * later render without the ordering below moving.\n */\nfunction bootAnalytics(app: FirebaseApp): Analytics | undefined {\n const existing = analyticsByApp.get(app)\n if (existing) return existing\n let analytics: Analytics\n // The region-conditional consent default (AGL-1597), declared BEFORE the\n // SDK boots the tag. Ordering is the whole of it: a `default` read after\n // `config` is not a default, and the SDK issues `config` inside\n // `initializeAnalytics` on the next line. Pushing onto `dataLayer` here\n // works even though gtag.js is not loaded yet — the queue is what makes the\n // ordering expressible.\n //\n // Still declared even though the gate above has already said yes, and the\n // two are not redundant. The gate answers \"may a tag exist\"; the default\n // answers \"what may the tag that does exist do\", per region, from its very\n // first hit. Ad storage stays denied everywhere on this surface.\n pushPlatformConsentDefault(\n typeof window === 'undefined' ? null : (window as never),\n )\n try {\n analytics = initializeAnalyticsInstance(app, CONSOLE_ANALYTICS_OPTIONS)\n } catch (error) {\n console.error(error)\n try {\n // Already initialized by someone else, with someone else's options:\n // take THAT instance rather than leaving consumers with nothing. The\n // tag it is attached to was configured without `send_page_view: false`\n // and without `content_group`, so this session reports a duplicate\n // startup page_view and an unstamped surface — degraded, and loudly so,\n // instead of silently dead.\n analytics = getAnalyticsInstance(app)\n } catch (fallbackError) {\n console.error(fallbackError)\n }\n }\n if (analytics) analyticsByApp.set(app, analytics)\n return analytics\n}\n\n/**\n * The tag this document may have right now: none outside a real production\n * deployment, none while consent is absent, otherwise the booted instance.\n */\nfunction analyticsForConsentState(app: FirebaseApp): Analytics | undefined {\n if (!analyticsMayEmit()) return undefined\n if (!analyticsConsentAllows()) return undefined\n return bootAnalytics(app)\n}\n\nexport interface FirebaseServicesProviderProps {\n firebaseConfig: FirebaseOptions\n appName: string\n /**\n * How much of *anything* this origin may keep on disk. Defaults to\n * `durable`, which is what every host serving this provider today is:\n * `*.aglyn.com` and `*.aglyn.app`, whose DNS we own and whose 14-day\n * session is the product.\n *\n * A **custom console domain** (AGL-1099c) must pass `ephemeral`. That is\n * the whole reason this is a prop rather than a constant: the class differs\n * per origin, not per build, and the decision belongs to whoever knows\n * which origin is being served.\n *\n * **It governs two things, and the name only names one.** It selects the\n * `Auth` persistence class (AGL-1379) *and* the Firestore `localCache`\n * (AGL-1456) — because both answer the same question about the same origin,\n * and splitting them into two props is precisely how the cache came to be\n * unconditional while the credential was hardened. See `firestore-cache.ts`.\n */\n authPersistence?: AuthPersistenceClass\n children?: ReactNode\n}\n\n/** The services every surface boots, before the per-document analytics verdict. */\ninterface FirebaseCoreServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n remoteConfig: RemoteConfig\n}\n\n/**\n * Create (or adopt) the app, Auth, Firestore, App Check and Remote Config for\n * one Firebase app: everything the provider used to build in its first render\n * except Analytics, whose consent verdict belongs to the render that reads it.\n */\nfunction bootFirebaseCore(\n firebaseConfig: FirebaseOptions,\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices {\n const app =\n getApps().find((existing) => existing.name === appName) ??\n initializeApp(firebaseConfig, appName)\n // `durable` resolves to the same `getAuth(app)` this always called.\n const auth = createAuthInstance(app, authPersistence)\n\n // The durable cache's IndexedDB database, `<persistence prefix>main`.\n const persistencePrefix = app.options?.projectId\n ? firestorePersistencePrefix(app.name, app.options.projectId)\n : undefined\n const databaseName = persistencePrefix && `${persistencePrefix}main`\n // The origin's class, unless this tab fell back to the memory cache\n // because another tab locked the shared one (AGL-3428), or a tab has just\n // seen that lock (AGL-4090). Firestore only: `auth` above keeps the\n // origin's class.\n const firestoreCacheClass = firestoreCacheClassFor(authPersistence, databaseName)\n if (!firestoreInitialized.has(appName)) {\n try {\n // Under the emulator (dev/e2e only): force long-polling and skip\n // the persistent multi-tab cache. The emulator's WebChannel\n // streaming misbehaves in automated Chrome — listeners serve the\n // initial empty from-cache snapshot and the server sync never\n // arrives, which looks like \"empty pages with zero errors\"\n // (the AGL-217 mystery). Real traffic keeps the default transport\n // and persistent cache — except a WebDriver-controlled Chrome\n // against a real backend, which forces long-polling for the same\n // reason without giving up the cache (see `isAutomatedChromeSession`\n // below).\n //\n // ⚠️ CONSEQUENCE, and it will cost you hours if you do not know it\n // (AGL-1066): every stale-session/stale-cache fault is UNREPRODUCIBLE\n // locally through the app, because the cache that causes them is off\n // in exactly the configuration you would reach for to reproduce one.\n // A listener that keeps serving arbitrarily-old data while the server\n // refuses it, a `noDocument` tombstone that 404s a live host, the\n // retry budget that never spends because a cached emission resets it\n // — none of them can happen here. Test that behaviour with the unit\n // seams instead (`use-firestore-collection-cached-retry.spec.ts`\n // drives cached emissions and denials directly), or against a\n // deployed environment. Do NOT \"fix\" it by turning the cache on for\n // the emulator: the AGL-217 empty-pages-with-zero-errors mystery is\n // what that produces.\n initializeFirestore(\n app,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ? { experimentalForceLongPolling: true }\n : {\n // NOT unconditional (AGL-1456). `persistentLocalCache` writes\n // document bodies to this origin's IndexedDB, so on a custom\n // console domain it is the same exposure D6 removed from the\n // refresh token — see `firestore-cache.ts` for why one\n // declaration governs both.\n localCache: localCacheFor(firestoreCacheClass),\n // The real-backend half of the AGL-217 mitigation above: force\n // long-polling for a WebDriver-controlled Chrome even when it\n // is NOT talking to the emulator, because the WebChannel wedge\n // is a property of automated Chrome, not of which backend it\n // is automating against. Never true for a real visitor, so\n // production traffic keeps the SDK's own auto-detected\n // transport untouched.\n ...(isAutomatedChromeSession()\n ? { experimentalForceLongPolling: true }\n : {}),\n },\n )\n if (FIREBASE_FIRESTORE_EMULATOR_ENABLED) {\n // Where the server was told the emulator is, rather than a default\n // port another session's stack may hold (AGL-2834).\n const emulator = firestoreEmulatorHost()\n connectFirestoreEmulator(\n getFirestore(app),\n emulator.host,\n emulator.port,\n )\n } else {\n // The SDK never sweeps the multi-tab records the durable cache\n // strands in localStorage, and a full localStorage fails the whole\n // Firestore client — see `firestore-shared-client-state.ts`.\n void pruneSharedClientStateFor(firestoreCacheClass, app)\n // Only the durable multi-tab cache can be locked by another tab,\n // so only it gets the lease check after a stalled recovery.\n if (firestoreCacheClass === 'durable' && persistencePrefix && databaseName) {\n markMultiTabFirestore(getFirestore(app), databaseName)\n // A tab still booting finds another tab's lock in seconds, not\n // the ~37 s the in-use rescue budgets (AGL-4201).\n void startBootWedgeCheck(getFirestore(app), () =>\n firestoreHasServerAnswered(getFirestore(app)),\n )\n // A visible tab opened while a background tab holds the shared\n // cache's lease takes the lease at boot instead of routing every\n // query through the background tab until its lease lapses\n // (AGL-3660). In initializeFirestore's task: its first step\n // snapshots the other tabs before this tab's client can start.\n void startFirestoreTabHandoff(getFirestore(app), persistencePrefix)\n // A background tab that keeps its lease live never hands it over\n // on its own, and every tab's cache work waits on its throttled\n // renderer. The visible tab asks; the holder lets go through the\n // SDK's own election (AGL-4204). Same task, same snapshot rule.\n void startFirestorePrimaryYield(getFirestore(app), persistencePrefix)\n } else if (authPersistence === 'durable' && databaseName) {\n // A durable origin's tab on the memory cache. If that is because a\n // tab saw the shared cache locked, read the lease once, read-only,\n // so the record lasts only as long as the lock (AGL-4090).\n void confirmSharedCacheLock(databaseName)\n }\n }\n } catch {\n // already initialized (e.g. HMR reset the module flag) — getFirestore() returns the existing instance\n } finally {\n firestoreInitialized.add(appName)\n }\n }\n const firestore = getFirestore(app)\n\n if (!connectedAuth) {\n try {\n if (FIREBASE_AUTH_EMULATOR_ENABLED) {\n // The emulator the server was started with (AGL-2834).\n connectAuthEmulator(auth, authEmulatorUrl())\n }\n connectedAuth = true\n } catch (error) {\n console.error(error)\n }\n }\n // App Check must be skipped under the emulators: there is no App\n // Check emulator, so ReCaptcha would hit the real backend and its\n // 403s break emulator auth (the AGL-216 emulator sessions hit this).\n if (\n !FIREBASE_AUTH_EMULATOR_ENABLED &&\n !FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ) {\n // No site key means no provider (AGL-2049). Registering one built on\n // `undefined` does not throw — it fails asynchronously inside the SDK,\n // where the catch below cannot see it — so this has to be a pre-check.\n const siteKey = appCheckSiteKey()\n if (!siteKey) {\n console.warn(APP_CHECK_KEY_MISSING_MESSAGE)\n } else {\n try {\n initializeAppCheck(app, {\n provider: new ReCaptchaV3Provider(siteKey),\n isTokenAutoRefreshEnabled: true,\n })\n // The widget renders into the SDK's <body> div only once Google's\n // script loads; a body cleared before then (hydration fallback,\n // global-error) made that render throw unhandled.\n keepAppCheckRecaptchaContainer(app.name)\n } catch (error) {\n console.error(error)\n }\n }\n }\n // Remote Config (AGL-228): release-flag delivery. Browser-only like\n // analytics; consumers set defaultConfig before their first getValue so\n // gating never blocks on the network.\n let remoteConfig: RemoteConfig\n try {\n remoteConfig = getRemoteConfigInstance(app)\n remoteConfig.settings.minimumFetchIntervalMillis =\n process.env.NODE_ENV === 'production' ? 3_600_000 : 60_000\n } catch (error) {\n console.error(error)\n }\n\n return { app, firestore, auth, remoteConfig }\n}\n\n/**\n * Services booted before React rendered anything, waiting for the provider to\n * adopt them (AGL-3660).\n *\n * The provider builds its services in its first render, and on the console\n * that render comes late: after every chunk of the route has executed, after\n * hydration, and after the `NoSsr` boundary above it has committed its\n * fallback and rendered again. Auth's persistence read and `accounts:lookup`,\n * and App Check's reCAPTCHA chain (script, script, iframe, token exchange),\n * which Auth AND Firestore requests both wait on whenever the cached App Check\n * token has expired, only started then. None of it depends on React, so a\n * surface that knows its config at module scope can start it there.\n *\n * Taken once, by the first provider that renders with the same app name and\n * persistence class; any later mount boots exactly as it always did. A\n * mismatched key is never adopted, so a preboot cannot hand a provider a\n * different persistence class than the one it was given.\n */\nconst prebooted = new Map<string, FirebaseCoreServices>()\nconst prebootKey = (appName: string, authPersistence: AuthPersistenceClass) =>\n `${appName}|${authPersistence}`\n\n/**\n * Start Firebase for this document now rather than at the provider's first\n * render. Browser only, once per app name and persistence class, and it never\n * throws: a failure here leaves the provider to boot as it always did.\n *\n * The Analytics consent gate is NOT read here (the provider reads it), so the\n * gate's module-scope registration does not have to precede this call.\n */\nexport function prebootFirebaseServices(options: {\n firebaseConfig: FirebaseOptions\n appName: string\n authPersistence?: AuthPersistenceClass\n}): void {\n if (typeof window === 'undefined') return\n const { firebaseConfig, appName, authPersistence = 'durable' } = options\n const key = prebootKey(appName, authPersistence)\n if (prebooted.has(key)) return\n try {\n prebooted.set(key, bootFirebaseCore(firebaseConfig, appName, authPersistence))\n } catch (error) {\n console.error(error)\n }\n}\n\nfunction takePrebootedFirebaseCore(\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices | undefined {\n const key = prebootKey(appName, authPersistence)\n const core = prebooted.get(key)\n if (core) prebooted.delete(key)\n return core\n}\n\nexport function FirebaseServicesProvider(props: FirebaseServicesProviderProps) {\n const { firebaseConfig, appName, authPersistence = 'durable', children } = props\n const servicesRef = useRef<FirebaseServices | undefined>(undefined)\n\n if (!servicesRef.current) {\n const core =\n takePrebootedFirebaseCore(appName, authPersistence) ??\n bootFirebaseCore(firebaseConfig, appName, authPersistence)\n // `initializeAnalytics`, not `getAnalytics`, for exactly one reason: it is\n // the only form that can pass `config`, and `send_page_view: false` is the\n // only way to stop the SDK's own startup `page_view` (AGL-1643).\n //\n // Booting Analytics issues `gtag('config', <id>, configProperties)`, and\n // the vendored SDK's own comment on that line reads \"This will trigger a\n // page_view event unless 'send_page_view' is set to false in\n // configProperties\". `getAnalytics(app)` passes no config at all, so the\n // key was never there and the hit always fired — on top of the manual\n // `page_view` the console's layout sends on mount. Two hits, one page.\n //\n // The SDK's is the one suppressed rather than the layout's, and the\n // direction is the whole decision: the SDK fires ONCE per document load,\n // while the layout fires on mount AND on every `usePathname` change. In a\n // client-routed app the layout's is a superset — killing it instead would\n // have left every in-app navigation unreported, halving console pageviews\n // rather than correcting them, and the reports would have looked fine.\n //\n // Nothing else about attribution moves: the surviving hit is sent from the\n // same document at mount, so `document.referrer` — which gtag resolves for\n // `page_referrer` itself, and which is what carries marketing traffic\n // source into the session — is still the external referrer at that moment.\n //\n // Re-entry is safe *only* while the options match. `initializeAnalytics`\n // returns the existing instance when they deep-equal the first call's and\n // throws `already-initialized` otherwise — and the options can be made to\n // differ by things no call site here controls (AGL-1979):\n //\n // * anything that touches the analytics provider WITHOUT options first\n // initializes it with `{}`. `getAnalytics()` is the obvious one, but\n // `@firebase/remote-config` reaches the same code path on its own —\n // `addExperimentToAnalytics` calls `analyticsProvider.getImmediate({\n // optional: true })`, and `optional` only suppresses the throw, it\n // does not stop the initialization.\n // * in dev, a module instance carrying a PREVIOUS version of these\n // options (this config changed under AGL-1857) surviving a Fast\n // Refresh alongside the new one.\n //\n // Once that happens the conflict is permanent for the document: every\n // later call throws, so without the fallback below `analytics` stayed\n // undefined forever and the next consumer — `logEvent(analytics, …)` —\n // read `.app` off it and threw a TypeError two frames away, which is how\n // this surfaced (top Cloud Error Reporting group, and reproduced live on\n // app.aglyn.com).\n //\n // `getAnalytics(app)` is the remedy the SDK's own error message names. It\n // cannot cost us the config on a healthy document: it only runs after\n // `initializeAnalytics` threw, and on a first init that throw can only be\n // `no-app-id` / `no-api-key` / `already-exists`, none of which\n // `getAnalytics` can rescue either — it re-throws and we fall through to\n // an undefined instance, which every consumer must now tolerate.\n // `content_group: 'console'` (AGL-1857) rides the same config: it is the\n // first-class GA4 axis that separates console traffic from `marketing`\n // (stamped by the tenant runtime on aglyn.com's own tag) and `docs`\n // (stamped by the Docusaurus head snippet) in standard reports, without\n // reaching for the Hostname dimension. The console is this provider's\n // only consumer, verified by grep — the tenant runtime builds its tag in\n // `site-analytics.tsx` and never passes through here.\n //\n // AND NOT AT ALL outside a real production deployment (AGL-2067). This\n // provider used to boot Analytics unconditionally, while\n // `apps/console/.env.development.local` points at the PRODUCTION\n // measurement id — so every `next dev` session and every Vercel preview\n // build produced genuine `session_start` / `first_visit` / `page_view`\n // hits in the live property. Not a theory: the archived Marketing\n // property's entire year-to-date history is 30 views / 6 users, ~24 of\n // them `/signin` on preview urls (docs/ANALYTICS.md).\n //\n // Not initialized rather than initialized-and-suppressed, because a\n // resident tag reports on its own — AGL-1608 is the same lesson from the\n // consent side. `useAnalytics()` returning undefined is already a\n // supported state everywhere (AGL-1979), which is what makes this a\n // two-line gate instead of an audit.\n //\n // `analyticsMayEmit` leans LOUD on an unknown deployment: a self-hosted\n // build points at the operator's own Firebase project and their own GA\n // property, and silencing a customer's analytics to protect ours is the\n // worse failure. See the module for the escape hatch.\n //\n // AND NOT while a registered consent gate says no (AGL-1498 posture,\n // applied to Aglyn's own console). `analyticsForConsentState` is where\n // both conditions and the boot itself now live, because the boot has to\n // be repeatable: a visitor whose region has not resolved yet is undecided\n // at this instant and may be granted a moment later, and a visitor who\n // withdraws mid-session has to lose the instance without the page\n // reloading. See the effect below.\n //\n // SCOPE. This is the console's tag and only the console's:\n // `CONSOLE_ANALYTICS_OPTIONS`, `content_group: 'console'`, and this\n // provider's analytics branch has no other consumer (the tenant runtime\n // builds its tag in `site-analytics.tsx` and never passes through here).\n // Customer sites keep the AGL-1498 gate and the host's own\n // `consent.mode`; nothing here reaches them.\n const initialAnalytics = analyticsForConsentState(core.app)\n\n servicesRef.current = {\n ...core,\n analytics: initialAnalytics,\n authPersistence,\n }\n }\n\n const services = servicesRef.current\n\n // The consent gate's other half: the verdict can CHANGE within one document,\n // in both directions, and everything else in this provider is built exactly\n // once by design.\n //\n // Deferred grant. A visitor with no stored record is undecided at the\n // instant this provider first renders, because resolving them needs the\n // region endpoint and that is a network call. Outside the prior-consent\n // regions the answer is implied consent, and it lands a few hundred\n // milliseconds later — same document, so `document.referrer` is still the\n // external referrer and the pageview's attribution is unaffected. Without\n // this, \"the gate is synchronous\" would have quietly meant \"the rest of the\n // world is never measured on a first visit\".\n //\n // Withdrawal. Dropping the instance unmounts every binding hung off it,\n // which is what unregisters the analytics transport — after that\n // `deliver()` falls through to `window.gtag`, and the shared consent writer\n // has already set `ga-disable-<id>` and sent a denied `consent update` on\n // that exact tag (AGL-1608). The resident tag cannot be unloaded; it can be\n // made to send nothing, and both halves are needed because either alone\n // leaks — enhanced measurement fires with no call site at all.\n const [analytics, setAnalytics] = useState<Analytics | undefined>(\n () => services.analytics,\n )\n useEffect(() => {\n const sync = () => setAnalytics(analyticsForConsentState(services.app))\n // Once on mount as well as on the event: the priming pass can resolve a\n // visitor between this provider's render and this effect, and the event it\n // dispatched then had no listener yet.\n sync()\n window.addEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n return () =>\n window.removeEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n }, [services])\n\n // Identity changes only when the tag comes or goes, so a consent-stable\n // document re-renders nothing.\n const value = useMemo(\n () =>\n services.analytics === analytics ? services : { ...services, analytics },\n [services, analytics],\n )\n\n return (\n <FirebaseServicesContext.Provider value={value}>\n {children}\n </FirebaseServicesContext.Provider>\n )\n}\nFirebaseServicesProvider.displayName = 'FirebaseServicesProvider'\n\nfunction useFirebaseServices(): FirebaseServices {\n const services = useContext(FirebaseServicesContext)\n if (!services) {\n throw new Error(\n 'Firebase hooks must be used within a <FirebaseServicesProvider>',\n )\n }\n return services\n}\n\nexport function useFirebaseApp(): FirebaseApp {\n return useFirebaseServices().app\n}\nexport function useFirestore(): Firestore {\n return useFirebaseServices().firestore\n}\nexport function useAuth(): Auth {\n return useFirebaseServices().auth\n}\n/**\n * The persistence class the provider's `Auth` was created with (AGL-1379).\n *\n * Read it — never re-derive it — when building a **second** Firebase app on\n * the same origin, so the second instance cannot end up more persistent than\n * the first. `apps/console/hooks/use-presence.ts` is the existing case.\n */\nexport function useAuthPersistence(): AuthPersistenceClass {\n return useFirebaseServices().authPersistence\n}\nexport function useAnalytics(): Analytics {\n return useFirebaseServices().analytics\n}\nexport function useRemoteConfig(): RemoteConfig {\n return useFirebaseServices().remoteConfig\n}\n\n/**\n * Replaces reactfire's `useUser()`. Reactfire subscribes via\n * `onIdTokenChanged` rather than `onAuthStateChanged` so fields like\n * `emailVerified` stay live across token refresh (e.g. after\n * `user.reload()` post-email-verification), not just sign-in/out — matched\n * here for behavioral parity.\n *\n * THREE states, not two (AGL-1261): `undefined` = auth has not resolved yet,\n * `null` = resolved, signed OUT, a `User` = resolved, signed in. This used to\n * collapse the emitted `null` into `undefined`, which made \"signed out\" and\n * \"still loading\" the same value — a state that, for a signed-out visitor,\n * never left \"loading\". `useSessionCookie` gates its whole body on\n * `user === undefined`, so its silent restore from the shared `__session`\n * cookie could never run: the cookie exchange returned a valid custom token\n * and nothing ever asked for it.\n */\nexport function useUser(): { data: User | null | undefined } {\n const auth = useAuth()\n const [user, setUser] = useState<User | null | undefined>(\n auth.currentUser ?? undefined,\n )\n\n useEffect(() => {\n return onIdTokenChanged(auth, (nextUser) => {\n // `?? null`, never `?? undefined` — see the note above.\n setUser(nextUser ?? null)\n })\n }, [auth])\n\n return { data: user }\n}\n\nexport interface SigninCheckResult {\n signedIn: boolean\n user: User | null\n}\n\n/** Replaces reactfire's `useSigninCheck()` — same `onIdTokenChanged` basis as `useUser()`. */\nexport function useSigninCheck(): {\n status: 'loading' | 'success' | 'error'\n data: SigninCheckResult | undefined\n error: Error | undefined\n} {\n const auth = useAuth()\n const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')\n const [data, setData] = useState<SigninCheckResult | undefined>(undefined)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n useEffect(() => {\n return onIdTokenChanged(\n auth,\n (user) => {\n setStatus('success')\n setError(undefined)\n setData({ signedIn: !!user, user: user ?? null })\n },\n (err) => {\n setStatus('error')\n setError(err)\n },\n )\n }, [auth])\n\n return { status, data, error }\n}\n"],"names":["getApps","initializeApp","getAnalytics","getAnalyticsInstance","initializeAnalytics","initializeAnalyticsInstance","initializeAppCheck","ReCaptchaV3Provider","analyticsMayEmit","pushPlatformConsentDefault","VISITOR_CONSENT_CHANGED_EVENT","connectAuthEmulator","onIdTokenChanged","connectFirestoreEmulator","getFirestore","initializeFirestore","getRemoteConfig","getRemoteConfigInstance","createContext","useContext","useEffect","useMemo","useRef","useState","FIREBASE_AUTH_EMULATOR_ENABLED","FIREBASE_FIRESTORE_EMULATOR_ENABLED","APP_CHECK_KEY_MISSING_MESSAGE","appCheckSiteKey","authEmulatorUrl","firestoreEmulatorHost","createAuthInstance","firestoreCacheClassFor","localCacheFor","pruneSharedClientStateFor","keepAppCheckRecaptchaContainer","confirmSharedCacheLock","markMultiTabFirestore","startBootWedgeCheck","firestoreHasServerAnswered","firestorePersistencePrefix","startFirestorePrimaryYield","startFirestoreTabHandoff","FirebaseServicesContext","undefined","firestoreInitialized","Set","connectedAuth","isAutomatedChromeSession","navigator","webdriver","CONSOLE_ANALYTICS_OPTIONS","config","send_page_view","content_group","analyticsConsentGate","setAnalyticsConsentGate","gate","analyticsConsentAllows","analyticsByApp","WeakMap","bootAnalytics","app","existing","get","analytics","window","error","console","fallbackError","set","analyticsForConsentState","bootFirebaseCore","firebaseConfig","appName","authPersistence","find","name","auth","persistencePrefix","options","projectId","databaseName","firestoreCacheClass","has","experimentalForceLongPolling","localCache","emulator","host","port","add","firestore","siteKey","warn","provider","isTokenAutoRefreshEnabled","remoteConfig","settings","minimumFetchIntervalMillis","process","env","NODE_ENV","prebooted","Map","prebootKey","prebootFirebaseServices","key","takePrebootedFirebaseCore","core","delete","FirebaseServicesProvider","props","children","servicesRef","current","initialAnalytics","services","setAnalytics","sync","addEventListener","removeEventListener","value","Provider","displayName","useFirebaseServices","Error","useFirebaseApp","useFirestore","useAuth","useAuthPersistence","useAnalytics","useRemoteConfig","useUser","user","setUser","currentUser","nextUser","data","useSigninCheck","status","setStatus","setData","setError","signedIn","err"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAGEA,OAAO,EACPC,aAAa,QACR,eAAc;AACrB,SAEEC,gBAAgBC,oBAAoB,EACpCC,uBAAuBC,2BAA2B,QAC7C,qBAAoB;AAC3B,SAASC,kBAAkB,EAAEC,mBAAmB,QAAQ,qBAAoB;AAC5E,SAASC,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,6BAA6B,QAAQ,yCAAwC;AACtF,SAEEC,mBAAmB,EACnBC,gBAAgB,QAEX,gBAAe;AACtB,SAEEC,wBAAwB,EACxBC,YAAY,EACZC,mBAAmB,QACd,qBAAoB;AAC3B,SAEEC,mBAAmBC,uBAAuB,QACrC,yBAAwB;AAC/B,SACEC,aAAa,EACbC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SACEC,8BAA8B,EAC9BC,mCAAmC,QAC9B,2BAA0B;AACjC,SACEC,6BAA6B,EAC7BC,eAAe,QACV,qC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qC;IACd,OAAOJ,sBAAsB9C,IAAI;AACnC;AACA;;;;;;CAMC,GACD,OAAO,SAASmD;IACd,OAAOL,sBAAsBjD,eAAe;AAC9C;AACA,OAAO,SAASuD;IACd,OAAON,sBAAsB3D,SAAS;AACxC;AACA,OAAO,SAASkE;IACd,OAAOP,sBAAsB5B,YAAY;AAC3C;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASoC;QAGZtD;IAFF,MAAMA,OAAOkD;IACb,MAAM,CAACK,MAAMC,QAAQ,GAAG9G,UACtBsD,oBAAAA,KAAKyD,WAAW,YAAhBzD,oBAAoBlC;IAGtBvB,UAAU;QACR,OAAOR,iBAAiBiE,MAAM,CAAC0D;YAC7B,wDAAwD;YACxDF,QAAQE,mBAAAA,WAAY;QACtB;IACF,GAAG;QAAC1D;KAAK;IAET,OAAO;QAAE2D,MAAMJ;IAAK;AACtB;AAOA,4FAA4F,GAC5F,OAAO,SAASK;IAKd,MAAM5D,OAAOkD;IACb,MAAM,CAACW,QAAQC,UAAU,GAAGpH,SAA0C;IACtE,MAAM,CAACiH,MAAMI,QAAQ,GAAGrH,SAAwCoB;IAChE,MAAM,CAACuB,OAAO2E,SAAS,GAAGtH,SAA4BoB;IAEtDvB,UAAU;QACR,OAAOR,iBACLiE,MACA,CAACuD;YACCO,UAAU;YACVE,SAASlG;YACTiG,QAAQ;gBAAEE,UAAU,CAAC,CAACV;gBAAMA,IAAI,EAAEA,eAAAA,OAAQ;YAAK;QACjD,GACA,CAACW;YACCJ,UAAU;YACVE,SAASE;QACX;IAEJ,GAAG;QAAClE;KAAK;IAET,OAAO;QAAE6D;QAAQF;QAAMtE;IAAM;AAC/B"}
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firebase-services.tsx"],"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'use client'\n\nimport {\n type FirebaseApp,\n type FirebaseOptions,\n getApps,\n initializeApp,\n} from 'firebase/app'\nimport {\n type Analytics,\n getAnalytics as getAnalyticsInstance,\n initializeAnalytics as initializeAnalyticsInstance,\n} from 'firebase/analytics'\nimport { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check'\nimport { analyticsMayEmit } from '@aglyn/aglyn/app-utils/analytics-environment'\nimport { pushPlatformConsentDefault } from '@aglyn/aglyn/app-utils/platform-consent-default'\nimport { VISITOR_CONSENT_CHANGED_EVENT } from '@aglyn/aglyn/app-utils/visitor-consent'\nimport {\n type Auth,\n connectAuthEmulator,\n onIdTokenChanged,\n type User,\n} from 'firebase/auth'\nimport {\n type Firestore,\n connectFirestoreEmulator,\n getFirestore,\n initializeFirestore,\n} from 'firebase/firestore'\nimport {\n type RemoteConfig,\n getRemoteConfig as getRemoteConfigInstance,\n} from 'firebase/remote-config'\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react'\nimport {\n FIREBASE_AUTH_EMULATOR_ENABLED,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED,\n} from '@aglyn/shared-data-enums'\nimport {\n APP_CHECK_KEY_MISSING_MESSAGE,\n appCheckSiteKey,\n} from '../../constants/firebase-config'\nimport {\n authEmulatorUrl,\n firestoreEmulatorHost,\n} from '../../constants/firebase-emulator-hosts'\nimport {\n type AuthPersistenceClass,\n createAuthInstance,\n} from './auth-persistence'\nimport {\n firestoreCacheClassFor,\n localCacheFor,\n pruneSharedClientStateFor,\n} from './firestore-cache'\nimport { keepAppCheckRecaptchaContainer } from './app-check-recaptcha-container'\nimport type { ListenHandle } from '../helpers/listen-confirmation'\nimport {\n confirmSharedCacheLock,\n markMultiTabFirestore,\n startBootWedgeCheck,\n} from './firestore-multitab-wedge'\nimport { startPageWedgeChecks } from './firestore-page-wedge-check'\nimport { firestoreHasServerAnswered } from './firestore-stall-recovery'\nimport { firestorePersistencePrefix } from './firestore-shared-client-state'\nimport { startFirestorePrimaryYield } from './firestore-primary-yield'\nimport { startFirestoreTabHandoff } from './firestore-tab-handoff'\n\n/**\n * Drop-in replacement for reactfire's `ObservableStatus<T>` — reactfire is\n * unmaintained against firebase majors past v9, but its shape is preserved\n * here so `helpers/use-doc.ts`'s already-battle-tested onSnapshot+retry\n * implementation (AGL-216/223) didn't need to change.\n */\nexport interface ObservableStatus<T> {\n status: 'loading' | 'error' | 'success'\n hasEmitted: boolean\n isComplete: boolean\n data: T\n error: Error | undefined\n firstValuePromise: Promise<void>\n /**\n * The emitted `data` includes local writes the server has NOT\n * acknowledged (`snapshot.metadata.hasPendingWrites`).\n *\n * Carried rather than dropped because a caller cannot otherwise tell \"the\n * store holds this\" from \"my browser holds this\". `persistentLocalCache`\n * replays a queued write into the very first snapshot after a reload, so a\n * caller that treats every snapshot as authoritative will adopt its own\n * unacknowledged edit as the saved state — which is how the besigner ended\n * up unable to save real changes (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * The emitted `data` came from the local cache and the server has NOT\n * confirmed it (`snapshot.metadata.fromCache`).\n *\n * Carried because it is the only per-listener ground truth about\n * freshness the SDK offers, and the console needs it (AGL-1066). Under\n * `persistentLocalCache` a listener whose server listen is being REFUSED\n * still emits cached snapshots and still reports `status: 'success'` —\n * the retry budget is reset by each cached emission and never spends, so\n * `status` can never reveal the fault (see\n * `use-firestore-collection-cached-retry.spec.ts`).\n *\n * Prefer this over `session-health`'s `staleSession` for anything that\n * asks \"is what I am looking at live?\". `staleSession` is a heuristic\n * needing two denied collections inside a window, and it is unreachable\n * on listener-only pages; this is a fact about THIS listener, costs\n * nothing, and clears itself the instant a server snapshot lands.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget, and\n * no server snapshot has arrived since (AGL-1066).\n *\n * `fromCache` says \"unconfirmed\", which is also true offline and true for\n * the first snapshot of a perfectly healthy load. This says \"refused\" —\n * only `permission-denied` counts it, and it takes a whole budget's worth\n * in a row, so it cannot fire offline and cannot fire on the AGL-216/217\n * post-sign-in token race.\n *\n * It is what `status` would say if the retry budget were spendable. It is\n * carried separately because correcting `status` in place would blank\n * every surface that renders cached data through an `error` branch — see\n * the note on `attempt = 0` in `use-firestore-collection`.\n */\n serverDenied: boolean\n /**\n * This hook's listener, for a guarded save seeded from `data` to wait on\n * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of\n * the hook.\n */\n listen: ListenHandle\n}\n\n/** Replaces reactfire's `ReactFireOptions<T>` — drops the `suspense` field, which was never read. */\nexport interface FirestoreDocOptions<T> {\n idField?: string\n initialData?: T\n}\n\n/**\n * The Firebase products this provider builds, and therefore the ones every\n * page that renders it downloads.\n *\n * ⛔ NO Realtime Database and NO Cloud Storage (AGL-2706). Both were built\n * here and published as `useDatabase()` / `useStorage()`, and neither hook had\n * a single caller anywhere in the repo — so `@firebase/database` (125.9 KB\n * raw) and `@firebase/storage` (13.9 KB) were in the first load of every\n * console route to satisfy a context field nothing read.\n *\n * Realtime Database IS used, by `apps/console/hooks/use-presence.ts` and\n * `use-coediting.ts` — on their own Firebase app, with their own\n * `getDatabase`, behind the editor routes that need presence. That is the\n * shape to copy if a surface needs one of these: reach for the product where\n * the feature is, not in the provider every page mounts. A field here is paid\n * for by every route, used or not.\n */\ninterface FirebaseServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n analytics: Analytics\n remoteConfig: RemoteConfig\n /**\n * The persistence class `auth` was actually created with (AGL-1379).\n *\n * Published so a **second** auth instance derives its class from the\n * primary rather than re-deciding it. `apps/console/hooks/use-presence.ts`\n * builds its own Firebase app and its own `Auth`; before this it took the\n * SDK default unconditionally, so configuring only the provider would have\n * left presence persisting a refresh token on an origin the provider had\n * just been careful not to persist one on.\n */\n authPersistence: AuthPersistenceClass\n}\n\nconst FirebaseServicesContext = createContext<FirebaseServices | undefined>(undefined)\n\n// Module-scope guards so HMR / remounts don't re-run emulator connection\n// (which throws if called twice) or double-initialize Firestore's\n// persistent cache.\n//\n// Firestore's is keyed by app NAME, not a bare boolean (AGL-1456): Firestore\n// initialization is once-per-app, so a module-global flag made the FIRST app\n// to mount decide for every later one — a second app would silently skip\n// `initializeFirestore` and take SDK defaults. That mattered the moment the\n// cache stopped being the same on every host.\nconst firestoreInitialized = new Set<string>()\nlet connectedAuth = false\n\n/**\n * True when THIS Chrome instance is under WebDriver automation control\n * (Puppeteer, Playwright, Selenium, or a raw CDP client) — never true for a\n * person's own browser.\n *\n * The `initializeFirestore` call below already documents the fault this\n * exists for: \"the emulator's WebChannel streaming misbehaves in automated\n * Chrome — listeners serve the initial empty from-cache snapshot and the\n * server sync never arrives\" (AGL-217). That mitigation only reaches\n * `FIREBASE_FIRESTORE_EMULATOR_ENABLED`, so an automated session against a\n * REAL, deployed backend — a browser-automation agent driving a live\n * console, which is exactly what `navigator.webdriver` detects — stayed\n * exposed. `getDocs`/`getDoc` and `onSnapshot` all resolve over the same\n * Watch stream internally, so a one-shot read wedges exactly like a listener\n * does: no error, nothing to catch, `loading` simply never gets its\n * settling event. That is the Media Library grid spinning on \"Loading\n * media…\" indefinitely with a perfectly healthy account and a perfectly\n * healthy network.\n *\n * `undefined` during SSR reads as `false` — `navigator` does not exist in\n * Node, and a server render can only ever produce the auto-detected\n * transport, never the forced one.\n */\nconst isAutomatedChromeSession = (): boolean =>\n typeof navigator !== 'undefined' && navigator.webdriver === true\n\n/**\n * The console tag's gtag config — ONE object, at module scope, deliberately\n * (AGL-1979).\n *\n * `initializeAnalytics(app, options)` throws `already-initialized` unless the\n * options `deepEqual` the ones the instance was first created with, and the\n * provider re-enters this block on every mount, every StrictMode double\n * invoke and every Fast Refresh. A fresh object literal per call survives\n * that only by *value*; a shared constant survives it by *identity*, which is\n * the first branch of the SDK's own comparison and cannot drift when someone\n * edits one call site and not another.\n *\n * ⚠️ The SDK MUTATES this object: `_initializeAnalytics` reads `options.config`\n * and writes `origin`, `update` and the installation id onto it in place.\n * That is precisely why sharing it is safe rather than dangerous — the object\n * the provider holds and the object the SDK stored are the same one, so they\n * cannot disagree.\n */\nconst CONSOLE_ANALYTICS_OPTIONS = {\n config: { send_page_view: false, content_group: 'console' },\n}\n\n/**\n * A surface's answer to \"may an analytics tag exist for this visitor at all?\".\n *\n * Registered from the app, at module scope, in the same shape as\n * `setFirestoreSessionReporters` and `setStaleSessionCheck` — and for a\n * sharper version of the same reason. This is consulted during the provider's\n * FIRST render, before any effect anywhere has run, so a gate installed from\n * an effect would arrive after the decision it exists to make.\n *\n * Answering `false` means the SDK is never asked to initialize: `gtag.js` is\n * never fetched, `window.gtag` never comes into existence, and the shared\n * `deliver()` in `analytics-events.ts` — whose fallback IS `window.gtag` —\n * therefore has nowhere to put a hit. That is the difference between a gate\n * and a suppression, and it is the difference AGL-1608 paid for: a resident\n * tag reports on its own, through enhanced measurement, whatever any flag\n * says afterwards.\n */\nexport type AnalyticsConsentGate = () => boolean\n\nlet analyticsConsentGate: AnalyticsConsentGate | null = null\n\n/**\n * Install the consent gate for this document, or clear it with `null`.\n *\n * UNREGISTERED MEANS ALLOWED, which is deliberate and is the only default that\n * is safe here. The tenant runtime does not use this provider's analytics\n * branch at all (it builds its own tag in `site-analytics.tsx`, behind the\n * AGL-1498 gate), and a self-hosted console points at the operator's own GA\n * property — silencing an operator's analytics because Aglyn's own surface\n * grew a gate is a failure they cannot diagnose. The surface that needs the\n * gate is the one that registers it.\n */\nexport function setAnalyticsConsentGate(\n gate: AnalyticsConsentGate | null,\n): void {\n analyticsConsentGate = gate\n}\n\n/** The gate's verdict, with an unregistered gate reading as \"allowed\". */\nfunction analyticsConsentAllows(): boolean {\n if (analyticsConsentGate === null) return true\n try {\n return analyticsConsentGate() === true\n } catch {\n // A gate that throws cannot be read as consent. Storage can throw in\n // private mode, and \"we could not tell\" is the one state this whole\n // mechanism resolves to \"no\".\n return false\n }\n}\n\n/**\n * The Analytics instance per Firebase app, so a re-boot after a consent change\n * hands back the tag that is already resident rather than asking the SDK for a\n * second one.\n *\n * `initializeAnalytics` is idempotent while the options match, so this is not\n * what makes re-entry safe — `CONSOLE_ANALYTICS_OPTIONS` being a shared\n * constant is. What this avoids is the noisy path: once anything has\n * initialized the provider with different options, every later call throws and\n * is logged, and a withdrawal followed by a re-grant would log it again.\n */\nconst analyticsByApp = new WeakMap<FirebaseApp, Analytics>()\n\n/**\n * Boot the console's Analytics tag, or return the one already booted.\n *\n * Extracted from the provider body so that \"when is the tag created\" and \"may\n * it be created\" are separable: the consent gate can defer this call to a\n * later render without the ordering below moving.\n */\nfunction bootAnalytics(app: FirebaseApp): Analytics | undefined {\n const existing = analyticsByApp.get(app)\n if (existing) return existing\n let analytics: Analytics\n // The region-conditional consent default (AGL-1597), declared BEFORE the\n // SDK boots the tag. Ordering is the whole of it: a `default` read after\n // `config` is not a default, and the SDK issues `config` inside\n // `initializeAnalytics` on the next line. Pushing onto `dataLayer` here\n // works even though gtag.js is not loaded yet — the queue is what makes the\n // ordering expressible.\n //\n // Still declared even though the gate above has already said yes, and the\n // two are not redundant. The gate answers \"may a tag exist\"; the default\n // answers \"what may the tag that does exist do\", per region, from its very\n // first hit. Ad storage stays denied everywhere on this surface.\n pushPlatformConsentDefault(\n typeof window === 'undefined' ? null : (window as never),\n )\n try {\n analytics = initializeAnalyticsInstance(app, CONSOLE_ANALYTICS_OPTIONS)\n } catch (error) {\n console.error(error)\n try {\n // Already initialized by someone else, with someone else's options:\n // take THAT instance rather than leaving consumers with nothing. The\n // tag it is attached to was configured without `send_page_view: false`\n // and without `content_group`, so this session reports a duplicate\n // startup page_view and an unstamped surface — degraded, and loudly so,\n // instead of silently dead.\n analytics = getAnalyticsInstance(app)\n } catch (fallbackError) {\n console.error(fallbackError)\n }\n }\n if (analytics) analyticsByApp.set(app, analytics)\n return analytics\n}\n\n/**\n * The tag this document may have right now: none outside a real production\n * deployment, none while consent is absent, otherwise the booted instance.\n */\nfunction analyticsForConsentState(app: FirebaseApp): Analytics | undefined {\n if (!analyticsMayEmit()) return undefined\n if (!analyticsConsentAllows()) return undefined\n return bootAnalytics(app)\n}\n\nexport interface FirebaseServicesProviderProps {\n firebaseConfig: FirebaseOptions\n appName: string\n /**\n * How much of *anything* this origin may keep on disk. Defaults to\n * `durable`, which is what every host serving this provider today is:\n * `*.aglyn.com` and `*.aglyn.app`, whose DNS we own and whose 14-day\n * session is the product.\n *\n * A **custom console domain** (AGL-1099c) must pass `ephemeral`. That is\n * the whole reason this is a prop rather than a constant: the class differs\n * per origin, not per build, and the decision belongs to whoever knows\n * which origin is being served.\n *\n * **It governs two things, and the name only names one.** It selects the\n * `Auth` persistence class (AGL-1379) *and* the Firestore `localCache`\n * (AGL-1456) — because both answer the same question about the same origin,\n * and splitting them into two props is precisely how the cache came to be\n * unconditional while the credential was hardened. See `firestore-cache.ts`.\n */\n authPersistence?: AuthPersistenceClass\n children?: ReactNode\n}\n\n/** The services every surface boots, before the per-document analytics verdict. */\ninterface FirebaseCoreServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n remoteConfig: RemoteConfig\n}\n\n/**\n * Create (or adopt) the app, Auth, Firestore, App Check and Remote Config for\n * one Firebase app: everything the provider used to build in its first render\n * except Analytics, whose consent verdict belongs to the render that reads it.\n */\nfunction bootFirebaseCore(\n firebaseConfig: FirebaseOptions,\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices {\n const app =\n getApps().find((existing) => existing.name === appName) ??\n initializeApp(firebaseConfig, appName)\n // `durable` resolves to the same `getAuth(app)` this always called.\n const auth = createAuthInstance(app, authPersistence)\n\n // The durable cache's IndexedDB database, `<persistence prefix>main`.\n const persistencePrefix = app.options?.projectId\n ? firestorePersistencePrefix(app.name, app.options.projectId)\n : undefined\n const databaseName = persistencePrefix && `${persistencePrefix}main`\n // The origin's class, unless this tab fell back to the memory cache\n // because another tab locked the shared one (AGL-3428), or a tab has just\n // seen that lock (AGL-4090). Firestore only: `auth` above keeps the\n // origin's class.\n const firestoreCacheClass = firestoreCacheClassFor(authPersistence, databaseName)\n if (!firestoreInitialized.has(appName)) {\n try {\n // Under the emulator (dev/e2e only): force long-polling and skip\n // the persistent multi-tab cache. The emulator's WebChannel\n // streaming misbehaves in automated Chrome — listeners serve the\n // initial empty from-cache snapshot and the server sync never\n // arrives, which looks like \"empty pages with zero errors\"\n // (the AGL-217 mystery). Real traffic keeps the default transport\n // and persistent cache — except a WebDriver-controlled Chrome\n // against a real backend, which forces long-polling for the same\n // reason without giving up the cache (see `isAutomatedChromeSession`\n // below).\n //\n // ⚠️ CONSEQUENCE, and it will cost you hours if you do not know it\n // (AGL-1066): every stale-session/stale-cache fault is UNREPRODUCIBLE\n // locally through the app, because the cache that causes them is off\n // in exactly the configuration you would reach for to reproduce one.\n // A listener that keeps serving arbitrarily-old data while the server\n // refuses it, a `noDocument` tombstone that 404s a live host, the\n // retry budget that never spends because a cached emission resets it\n // — none of them can happen here. Test that behaviour with the unit\n // seams instead (`use-firestore-collection-cached-retry.spec.ts`\n // drives cached emissions and denials directly), or against a\n // deployed environment. Do NOT \"fix\" it by turning the cache on for\n // the emulator: the AGL-217 empty-pages-with-zero-errors mystery is\n // what that produces.\n initializeFirestore(\n app,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ? { experimentalForceLongPolling: true }\n : {\n // NOT unconditional (AGL-1456). `persistentLocalCache` writes\n // document bodies to this origin's IndexedDB, so on a custom\n // console domain it is the same exposure D6 removed from the\n // refresh token — see `firestore-cache.ts` for why one\n // declaration governs both.\n localCache: localCacheFor(firestoreCacheClass),\n // The real-backend half of the AGL-217 mitigation above: force\n // long-polling for a WebDriver-controlled Chrome even when it\n // is NOT talking to the emulator, because the WebChannel wedge\n // is a property of automated Chrome, not of which backend it\n // is automating against. Never true for a real visitor, so\n // production traffic keeps the SDK's own auto-detected\n // transport untouched.\n ...(isAutomatedChromeSession()\n ? { experimentalForceLongPolling: true }\n : {}),\n },\n )\n if (FIREBASE_FIRESTORE_EMULATOR_ENABLED) {\n // Where the server was told the emulator is, rather than a default\n // port another session's stack may hold (AGL-2834).\n const emulator = firestoreEmulatorHost()\n connectFirestoreEmulator(\n getFirestore(app),\n emulator.host,\n emulator.port,\n )\n } else {\n // The SDK never sweeps the multi-tab records the durable cache\n // strands in localStorage, and a full localStorage fails the whole\n // Firestore client — see `firestore-shared-client-state.ts`.\n void pruneSharedClientStateFor(firestoreCacheClass, app)\n // Only the durable multi-tab cache can be locked by another tab,\n // so only it gets the lease check after a stalled recovery.\n if (firestoreCacheClass === 'durable' && persistencePrefix && databaseName) {\n markMultiTabFirestore(getFirestore(app), databaseName)\n // A tab still booting finds another tab's lock in seconds, not\n // the ~37 s the in-use rescue budgets (AGL-4201).\n void startBootWedgeCheck(getFirestore(app), () =>\n firestoreHasServerAnswered(getFirestore(app)),\n )\n // And so does each page opened later in this tab, until it is\n // used (AGL-4204). The tab's lifetime: never stopped.\n startPageWedgeChecks(getFirestore(app))\n // A visible tab opened while a background tab holds the shared\n // cache's lease takes the lease at boot instead of routing every\n // query through the background tab until its lease lapses\n // (AGL-3660). In initializeFirestore's task: its first step\n // snapshots the other tabs before this tab's client can start.\n void startFirestoreTabHandoff(getFirestore(app), persistencePrefix)\n // A background tab that keeps its lease live never hands it over\n // on its own, and every tab's cache work waits on its throttled\n // renderer. The visible tab asks; the holder lets go through the\n // SDK's own election (AGL-4204). Same task, same snapshot rule.\n void startFirestorePrimaryYield(getFirestore(app), persistencePrefix)\n } else if (authPersistence === 'durable' && databaseName) {\n // A durable origin's tab on the memory cache. If that is because a\n // tab saw the shared cache locked, read the lease once, read-only,\n // so the record lasts only as long as the lock (AGL-4090).\n void confirmSharedCacheLock(databaseName)\n }\n }\n } catch {\n // already initialized (e.g. HMR reset the module flag) — getFirestore() returns the existing instance\n } finally {\n firestoreInitialized.add(appName)\n }\n }\n const firestore = getFirestore(app)\n\n if (!connectedAuth) {\n try {\n if (FIREBASE_AUTH_EMULATOR_ENABLED) {\n // The emulator the server was started with (AGL-2834).\n connectAuthEmulator(auth, authEmulatorUrl())\n }\n connectedAuth = true\n } catch (error) {\n console.error(error)\n }\n }\n // App Check must be skipped under the emulators: there is no App\n // Check emulator, so ReCaptcha would hit the real backend and its\n // 403s break emulator auth (the AGL-216 emulator sessions hit this).\n if (\n !FIREBASE_AUTH_EMULATOR_ENABLED &&\n !FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ) {\n // No site key means no provider (AGL-2049). Registering one built on\n // `undefined` does not throw — it fails asynchronously inside the SDK,\n // where the catch below cannot see it — so this has to be a pre-check.\n const siteKey = appCheckSiteKey()\n if (!siteKey) {\n console.warn(APP_CHECK_KEY_MISSING_MESSAGE)\n } else {\n try {\n initializeAppCheck(app, {\n provider: new ReCaptchaV3Provider(siteKey),\n isTokenAutoRefreshEnabled: true,\n })\n // The widget renders into the SDK's <body> div only once Google's\n // script loads; a body cleared before then (hydration fallback,\n // global-error) made that render throw unhandled.\n keepAppCheckRecaptchaContainer(app.name)\n } catch (error) {\n console.error(error)\n }\n }\n }\n // Remote Config (AGL-228): release-flag delivery. Browser-only like\n // analytics; consumers set defaultConfig before their first getValue so\n // gating never blocks on the network.\n let remoteConfig: RemoteConfig\n try {\n remoteConfig = getRemoteConfigInstance(app)\n remoteConfig.settings.minimumFetchIntervalMillis =\n process.env.NODE_ENV === 'production' ? 3_600_000 : 60_000\n } catch (error) {\n console.error(error)\n }\n\n return { app, firestore, auth, remoteConfig }\n}\n\n/**\n * Services booted before React rendered anything, waiting for the provider to\n * adopt them (AGL-3660).\n *\n * The provider builds its services in its first render, and on the console\n * that render comes late: after every chunk of the route has executed, after\n * hydration, and after the `NoSsr` boundary above it has committed its\n * fallback and rendered again. Auth's persistence read and `accounts:lookup`,\n * and App Check's reCAPTCHA chain (script, script, iframe, token exchange),\n * which Auth AND Firestore requests both wait on whenever the cached App Check\n * token has expired, only started then. None of it depends on React, so a\n * surface that knows its config at module scope can start it there.\n *\n * Taken once, by the first provider that renders with the same app name and\n * persistence class; any later mount boots exactly as it always did. A\n * mismatched key is never adopted, so a preboot cannot hand a provider a\n * different persistence class than the one it was given.\n */\nconst prebooted = new Map<string, FirebaseCoreServices>()\nconst prebootKey = (appName: string, authPersistence: AuthPersistenceClass) =>\n `${appName}|${authPersistence}`\n\n/**\n * Start Firebase for this document now rather than at the provider's first\n * render. Browser only, once per app name and persistence class, and it never\n * throws: a failure here leaves the provider to boot as it always did.\n *\n * The Analytics consent gate is NOT read here (the provider reads it), so the\n * gate's module-scope registration does not have to precede this call.\n */\nexport function prebootFirebaseServices(options: {\n firebaseConfig: FirebaseOptions\n appName: string\n authPersistence?: AuthPersistenceClass\n}): void {\n if (typeof window === 'undefined') return\n const { firebaseConfig, appName, authPersistence = 'durable' } = options\n const key = prebootKey(appName, authPersistence)\n if (prebooted.has(key)) return\n try {\n prebooted.set(key, bootFirebaseCore(firebaseConfig, appName, authPersistence))\n } catch (error) {\n console.error(error)\n }\n}\n\nfunction takePrebootedFirebaseCore(\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices | undefined {\n const key = prebootKey(appName, authPersistence)\n const core = prebooted.get(key)\n if (core) prebooted.delete(key)\n return core\n}\n\nexport function FirebaseServicesProvider(props: FirebaseServicesProviderProps) {\n const { firebaseConfig, appName, authPersistence = 'durable', children } = props\n const servicesRef = useRef<FirebaseServices | undefined>(undefined)\n\n if (!servicesRef.current) {\n const core =\n takePrebootedFirebaseCore(appName, authPersistence) ??\n bootFirebaseCore(firebaseConfig, appName, authPersistence)\n // `initializeAnalytics`, not `getAnalytics`, for exactly one reason: it is\n // the only form that can pass `config`, and `send_page_view: false` is the\n // only way to stop the SDK's own startup `page_view` (AGL-1643).\n //\n // Booting Analytics issues `gtag('config', <id>, configProperties)`, and\n // the vendored SDK's own comment on that line reads \"This will trigger a\n // page_view event unless 'send_page_view' is set to false in\n // configProperties\". `getAnalytics(app)` passes no config at all, so the\n // key was never there and the hit always fired — on top of the manual\n // `page_view` the console's layout sends on mount. Two hits, one page.\n //\n // The SDK's is the one suppressed rather than the layout's, and the\n // direction is the whole decision: the SDK fires ONCE per document load,\n // while the layout fires on mount AND on every `usePathname` change. In a\n // client-routed app the layout's is a superset — killing it instead would\n // have left every in-app navigation unreported, halving console pageviews\n // rather than correcting them, and the reports would have looked fine.\n //\n // Nothing else about attribution moves: the surviving hit is sent from the\n // same document at mount, so `document.referrer` — which gtag resolves for\n // `page_referrer` itself, and which is what carries marketing traffic\n // source into the session — is still the external referrer at that moment.\n //\n // Re-entry is safe *only* while the options match. `initializeAnalytics`\n // returns the existing instance when they deep-equal the first call's and\n // throws `already-initialized` otherwise — and the options can be made to\n // differ by things no call site here controls (AGL-1979):\n //\n // * anything that touches the analytics provider WITHOUT options first\n // initializes it with `{}`. `getAnalytics()` is the obvious one, but\n // `@firebase/remote-config` reaches the same code path on its own —\n // `addExperimentToAnalytics` calls `analyticsProvider.getImmediate({\n // optional: true })`, and `optional` only suppresses the throw, it\n // does not stop the initialization.\n // * in dev, a module instance carrying a PREVIOUS version of these\n // options (this config changed under AGL-1857) surviving a Fast\n // Refresh alongside the new one.\n //\n // Once that happens the conflict is permanent for the document: every\n // later call throws, so without the fallback below `analytics` stayed\n // undefined forever and the next consumer — `logEvent(analytics, …)` —\n // read `.app` off it and threw a TypeError two frames away, which is how\n // this surfaced (top Cloud Error Reporting group, and reproduced live on\n // app.aglyn.com).\n //\n // `getAnalytics(app)` is the remedy the SDK's own error message names. It\n // cannot cost us the config on a healthy document: it only runs after\n // `initializeAnalytics` threw, and on a first init that throw can only be\n // `no-app-id` / `no-api-key` / `already-exists`, none of which\n // `getAnalytics` can rescue either — it re-throws and we fall through to\n // an undefined instance, which every consumer must now tolerate.\n // `content_group: 'console'` (AGL-1857) rides the same config: it is the\n // first-class GA4 axis that separates console traffic from `marketing`\n // (stamped by the tenant runtime on aglyn.com's own tag) and `docs`\n // (stamped by the Docusaurus head snippet) in standard reports, without\n // reaching for the Hostname dimension. The console is this provider's\n // only consumer, verified by grep — the tenant runtime builds its tag in\n // `site-analytics.tsx` and never passes through here.\n //\n // AND NOT AT ALL outside a real production deployment (AGL-2067). This\n // provider used to boot Analytics unconditionally, while\n // `apps/console/.env.development.local` points at the PRODUCTION\n // measurement id — so every `next dev` session and every Vercel preview\n // build produced genuine `session_start` / `first_visit` / `page_view`\n // hits in the live property. Not a theory: the archived Marketing\n // property's entire year-to-date history is 30 views / 6 users, ~24 of\n // them `/signin` on preview urls (docs/ANALYTICS.md).\n //\n // Not initialized rather than initialized-and-suppressed, because a\n // resident tag reports on its own — AGL-1608 is the same lesson from the\n // consent side. `useAnalytics()` returning undefined is already a\n // supported state everywhere (AGL-1979), which is what makes this a\n // two-line gate instead of an audit.\n //\n // `analyticsMayEmit` leans LOUD on an unknown deployment: a self-hosted\n // build points at the operator's own Firebase project and their own GA\n // property, and silencing a customer's analytics to protect ours is the\n // worse failure. See the module for the escape hatch.\n //\n // AND NOT while a registered consent gate says no (AGL-1498 posture,\n // applied to Aglyn's own console). `analyticsForConsentState` is where\n // both conditions and the boot itself now live, because the boot has to\n // be repeatable: a visitor whose region has not resolved yet is undecided\n // at this instant and may be granted a moment later, and a visitor who\n // withdraws mid-session has to lose the instance without the page\n // reloading. See the effect below.\n //\n // SCOPE. This is the console's tag and only the console's:\n // `CONSOLE_ANALYTICS_OPTIONS`, `content_group: 'console'`, and this\n // provider's analytics branch has no other consumer (the tenant runtime\n // builds its tag in `site-analytics.tsx` and never passes through here).\n // Customer sites keep the AGL-1498 gate and the host's own\n // `consent.mode`; nothing here reaches them.\n const initialAnalytics = analyticsForConsentState(core.app)\n\n servicesRef.current = {\n ...core,\n analytics: initialAnalytics,\n authPersistence,\n }\n }\n\n const services = servicesRef.current\n\n // The consent gate's other half: the verdict can CHANGE within one document,\n // in both directions, and everything else in this provider is built exactly\n // once by design.\n //\n // Deferred grant. A visitor with no stored record is undecided at the\n // instant this provider first renders, because resolving them needs the\n // region endpoint and that is a network call. Outside the prior-consent\n // regions the answer is implied consent, and it lands a few hundred\n // milliseconds later — same document, so `document.referrer` is still the\n // external referrer and the pageview's attribution is unaffected. Without\n // this, \"the gate is synchronous\" would have quietly meant \"the rest of the\n // world is never measured on a first visit\".\n //\n // Withdrawal. Dropping the instance unmounts every binding hung off it,\n // which is what unregisters the analytics transport — after that\n // `deliver()` falls through to `window.gtag`, and the shared consent writer\n // has already set `ga-disable-<id>` and sent a denied `consent update` on\n // that exact tag (AGL-1608). The resident tag cannot be unloaded; it can be\n // made to send nothing, and both halves are needed because either alone\n // leaks — enhanced measurement fires with no call site at all.\n const [analytics, setAnalytics] = useState<Analytics | undefined>(\n () => services.analytics,\n )\n useEffect(() => {\n const sync = () => setAnalytics(analyticsForConsentState(services.app))\n // Once on mount as well as on the event: the priming pass can resolve a\n // visitor between this provider's render and this effect, and the event it\n // dispatched then had no listener yet.\n sync()\n window.addEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n return () =>\n window.removeEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n }, [services])\n\n // Identity changes only when the tag comes or goes, so a consent-stable\n // document re-renders nothing.\n const value = useMemo(\n () =>\n services.analytics === analytics ? services : { ...services, analytics },\n [services, analytics],\n )\n\n return (\n <FirebaseServicesContext.Provider value={value}>\n {children}\n </FirebaseServicesContext.Provider>\n )\n}\nFirebaseServicesProvider.displayName = 'FirebaseServicesProvider'\n\nfunction useFirebaseServices(): FirebaseServices {\n const services = useContext(FirebaseServicesContext)\n if (!services) {\n throw new Error(\n 'Firebase hooks must be used within a <FirebaseServicesProvider>',\n )\n }\n return services\n}\n\nexport function useFirebaseApp(): FirebaseApp {\n return useFirebaseServices().app\n}\nexport function useFirestore(): Firestore {\n return useFirebaseServices().firestore\n}\nexport function useAuth(): Auth {\n return useFirebaseServices().auth\n}\n/**\n * The persistence class the provider's `Auth` was created with (AGL-1379).\n *\n * Read it — never re-derive it — when building a **second** Firebase app on\n * the same origin, so the second instance cannot end up more persistent than\n * the first. `apps/console/hooks/use-presence.ts` is the existing case.\n */\nexport function useAuthPersistence(): AuthPersistenceClass {\n return useFirebaseServices().authPersistence\n}\nexport function useAnalytics(): Analytics {\n return useFirebaseServices().analytics\n}\nexport function useRemoteConfig(): RemoteConfig {\n return useFirebaseServices().remoteConfig\n}\n\n/**\n * Replaces reactfire's `useUser()`. Reactfire subscribes via\n * `onIdTokenChanged` rather than `onAuthStateChanged` so fields like\n * `emailVerified` stay live across token refresh (e.g. after\n * `user.reload()` post-email-verification), not just sign-in/out — matched\n * here for behavioral parity.\n *\n * THREE states, not two (AGL-1261): `undefined` = auth has not resolved yet,\n * `null` = resolved, signed OUT, a `User` = resolved, signed in. This used to\n * collapse the emitted `null` into `undefined`, which made \"signed out\" and\n * \"still loading\" the same value — a state that, for a signed-out visitor,\n * never left \"loading\". `useSessionCookie` gates its whole body on\n * `user === undefined`, so its silent restore from the shared `__session`\n * cookie could never run: the cookie exchange returned a valid custom token\n * and nothing ever asked for it.\n */\nexport function useUser(): { data: User | null | undefined } {\n const auth = useAuth()\n const [user, setUser] = useState<User | null | undefined>(\n auth.currentUser ?? undefined,\n )\n\n useEffect(() => {\n return onIdTokenChanged(auth, (nextUser) => {\n // `?? null`, never `?? undefined` — see the note above.\n setUser(nextUser ?? null)\n })\n }, [auth])\n\n return { data: user }\n}\n\nexport interface SigninCheckResult {\n signedIn: boolean\n user: User | null\n}\n\n/** Replaces reactfire's `useSigninCheck()` — same `onIdTokenChanged` basis as `useUser()`. */\nexport function useSigninCheck(): {\n status: 'loading' | 'success' | 'error'\n data: SigninCheckResult | undefined\n error: Error | undefined\n} {\n const auth = useAuth()\n const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')\n const [data, setData] = useState<SigninCheckResult | undefined>(undefined)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n useEffect(() => {\n return onIdTokenChanged(\n auth,\n (user) => {\n setStatus('success')\n setError(undefined)\n setData({ signedIn: !!user, user: user ?? null })\n },\n (err) => {\n setStatus('error')\n setError(err)\n },\n )\n }, [auth])\n\n return { status, data, error }\n}\n"],"names":["getApps","initializeApp","getAnalytics","getAnalyticsInstance","initializeAnalytics","initializeAnalyticsInstance","initializeAppCheck","ReCaptchaV3Provider","analyticsMayEmit","pushPlatformConsentDefault","VISITOR_CONSENT_CHANGED_EVENT","connectAuthEmulator","onIdTokenChanged","connectFirestoreEmulator","getFirestore","initializeFirestore","getRemoteConfig","getRemoteConfigInstance","createContext","useContext","useEffect","useMemo","useRef","useState","FIREBASE_AUTH_EMULATOR_ENABLED","FIREBASE_FIRESTORE_EMULATOR_ENABLED","APP_CHECK_KEY_MISSING_MESSAGE","appCheckSiteKey","authEmulatorUrl","firestoreEmulatorHost","createAuthInstance","firestoreCacheClassFor","localCacheFor","pruneSharedClientStateFor","keepAppCheckRecaptchaContainer","confirmSharedCacheLock","markMultiTabFirestore","startBootWedgeCheck","startPageWedgeChecks","firestoreHasServerAnswered","firestorePersistencePrefix","startFirestorePrimaryYield","startFirestoreTabHandoff","FirebaseServicesContext","undefined","firestoreInitialized","Set","connectedAuth","isAutomatedChromeSession","navigator","webdriver","CONSOLE_ANALYTICS_OPTIONS","config","send_page_view","content_group","analyticsConsentGate","setAnalyticsConsentGate","gate","analyticsConsentAllows","analyticsByApp","WeakMap","bootAnalytics","app","existing","get","analytics","window","error","console","fallbackError","set","analyticsForConsentState","bootFirebaseCore","firebaseConfig","appName","authPersistence","find","name","auth","persistencePrefix","options","projectId","databaseName","firestoreCacheClass","has","experimentalForceLongPolling","localCache","emulator","host","port","add","firestore","siteKey","warn","provider","isTokenAutoRefreshEnabled","remoteConfig","settings","minimumFetchIntervalMillis","process","env","NODE_ENV","prebooted","Map","prebootKey","prebootFirebaseServices","key","takePrebootedFirebaseCore","core","delete","FirebaseServicesProvider","props","children","servicesRef","current","initialAnalytics","services","setAnalytics","sync","addEventListener","removeEventListener","value","Provider","displayName","useFirebaseServices","Error","useFirebaseApp","useFirestore","useAuth","useAuthPersistence","useAnalytics","useRemoteConfig","useUser","user","setUser","currentUser","nextUser","data","useSigninCheck","status","setStatus","setData","setError","signedIn","err"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAGEA,OAAO,EACPC,aAAa,QACR,eAAc;AACrB,SAEEC,gBAAgBC,oBAAoB,EACpCC,uBAAuBC,2BAA2B,QAC7C,qBAAoB;AAC3B,SAASC,kBAAkB,EAAEC,mBAAmB,QAAQ,qBAAoB;AAC5E,SAASC,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,6BAA6B,QAAQ,yCAAwC;AACtF,SAEEC,mBAAmB,EACnBC,gBAAgB,QAEX,gBAAe;AACtB,SAEEC,wBAAwB,EACxBC,YAAY,EACZC,mBAAmB,QACd,qBAAoB;AAC3B,SAEEC,mBAAmBC,uBAAuB,QACrC,yBAAwB;AAC/B,SACEC,aAAa,EACbC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SACEC,8BAA8B,EAC9BC,mCAAmC,QAC9B,2BAA0B;AACjC,SACEC,6BAA6B,EAC7BC,eAAe,QACV,qCAAiC;AACxC,SACEC,eAAe,EACfC,qBAAqB,QAChB,6CAAyC;AAChD,SAEEC,kBAAkB,QACb,wBAAoB;AAC3B,SACEC,sBAAsB,EACtBC,aAAa,EACbC,yBAAyB,QACpB,uBAAmB;AAC1B,SAASC,8BAA8B,QAAQ,qCAAiC;AAEhF,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,mBAAmB,QACd,gCAA4B;AACnC,SAASC,oBAAoB,QAAQ,kCAA8B;AACnE,SAASC,0BAA0B,QAAQ,gCAA4B;AACvE,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,0BAA0B,QAAQ,+BAA2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K,MAAMC,QAAQ,GAAG/G,UACtBuD,oBAAAA,KAAKyD,WAAW,YAAhBzD,oBAAoBlC;IAGtBxB,UAAU;QACR,OAAOR,iBAAiBkE,MAAM,CAAC0D;YAC7B,wDAAwD;YACxDF,QAAQE,mBAAAA,WAAY;QACtB;IACF,GAAG;QAAC1D;KAAK;IAET,OAAO;QAAE2D,MAAMJ;IAAK;AACtB;AAOA,4FAA4F,GAC5F,OAAO,SAASK;IAKd,MAAM5D,OAAOkD;IACb,MAAM,CAACW,QAAQC,UAAU,GAAGrH,SAA0C;IACtE,MAAM,CAACkH,MAAMI,QAAQ,GAAGtH,SAAwCqB;IAChE,MAAM,CAACuB,OAAO2E,SAAS,GAAGvH,SAA4BqB;IAEtDxB,UAAU;QACR,OAAOR,iBACLkE,MACA,CAACuD;YACCO,UAAU;YACVE,SAASlG;YACTiG,QAAQ;gBAAEE,UAAU,CAAC,CAACV;gBAAMA,IAAI,EAAEA,eAAAA,OAAQ;YAAK;QACjD,GACA,CAACW;YACCJ,UAAU;YACVE,SAASE;QACX;IAEJ,GAAG;QAAClE;KAAK;IAET,OAAO;QAAE6D;QAAQF;QAAMtE;IAAM;AAC/B"}
@@ -424,7 +424,12 @@ export type BootWedgeOutcome =
424
424
  /** The client does not run the durable multi-tab cache. */
425
425
  | 'not-multi-tab'
426
426
  /** Something unexpected; the stall watch stays in charge. */
427
- | 'error';
427
+ | 'error'
428
+ /**
429
+ * Someone has started using the page, or has left it (AGL-4204). A page in
430
+ * use has the stall watch's budget, which protects what was typed into it.
431
+ */
432
+ | 'in-use';
428
433
  export interface BootWedgeCheckDeps {
429
434
  /** Reads the lease, bounded by {@link BOOT_WEDGE_LOCK_MS}. */
430
435
  probe: () => Promise<PrimaryLeaseProbe>;
@@ -432,6 +437,12 @@ export interface BootWedgeCheckDeps {
432
437
  fallBack: (evidence: WedgeEvidence) => void;
433
438
  /** Whether the server has confirmed anything for this client yet. */
434
439
  hasServerAnswered: () => boolean;
440
+ /**
441
+ * Whether the page has been used since the check began, or replaced. Checked
442
+ * wherever `hasServerAnswered` is. The boot check has none: a page with no
443
+ * server answer has nothing on it to lose.
444
+ */
445
+ isInUse?: () => boolean;
435
446
  isFallbackActive?: () => boolean;
436
447
  isOnline?: () => boolean;
437
448
  /** Resolves once the document is visible, at once when it already is. */
@@ -491,6 +502,13 @@ export declare function browserWedgeEscalationFor(firestore: Firestore): (() =>
491
502
  * client with a cache of its own has no other tab to wait on. Never rejects.
492
503
  */
493
504
  export declare function browserLeaseCheckFor(firestore: Firestore): (() => Promise<LeaseCheck>) | undefined;
505
+ /**
506
+ * Reads the lease of the database `firestore` was registered under with the
507
+ * boot check's budget ({@link BOOT_WEDGE_LOCK_MS}), and the fallback for it, or
508
+ * `undefined` when it does not run the durable multi-tab cache. For the page
509
+ * check (`firestore-page-wedge-check.ts`, AGL-4204).
510
+ */
511
+ export declare function bootWedgeCheckPartsFor(firestore: Firestore): Pick<BootWedgeCheckDeps, 'probe' | 'fallBack'> | undefined;
494
512
  /**
495
513
  * Runs the boot check (AGL-4201) for `firestore`, which
496
514
  * {@link markMultiTabFirestore} has registered. Call it right after
@@ -544,7 +544,7 @@ const whenDocumentVisible = ()=>new Promise((resolve)=>{
544
544
  document.addEventListener('visibilitychange', onChange);
545
545
  });
546
546
  /** The boot check, with its browser parts injected. Never rejects. */ export async function runBootWedgeCheck(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;
547
+ const { probe, fallBack, hasServerAnswered, isInUse = ()=>false, 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;
548
548
  try {
549
549
  if (isFallbackActive()) return 'fallback-active';
550
550
  await wait(delayMs);
@@ -552,12 +552,14 @@ const whenDocumentVisible = ()=>new Promise((resolve)=>{
552
552
  const until = now() + windowMs;
553
553
  for(;;){
554
554
  if (hasServerAnswered()) return 'answered';
555
+ if (isInUse()) return 'in-use';
555
556
  if (!isOnline()) return 'offline';
556
557
  if (isFallbackActive()) return 'fallback-active';
557
558
  const read = await probe();
558
559
  if (read.state === 'locked') {
559
560
  // The read took up to its whole budget; the client may have come through.
560
561
  if (hasServerAnswered()) return 'answered';
562
+ if (isInUse()) return 'in-use';
561
563
  if (!isOnline()) return 'offline';
562
564
  if (isFallbackActive()) return 'fallback-active';
563
565
  fallBack({
@@ -724,23 +726,34 @@ const whenDocumentVisible = ()=>new Promise((resolve)=>{
724
726
  };
725
727
  }
726
728
  /**
727
- * Runs the boot check (AGL-4201) for `firestore`, which
728
- * {@link markMultiTabFirestore} has registered. Call it right after
729
- * registering. `hasServerAnswered` is the stall watch's record of server
730
- * answers (`firestoreHasServerAnswered`), passed in so this module does not
731
- * import the one that imports it. Fire and forget: it never rejects.
732
- */ export function startBootWedgeCheck(firestore, hasServerAnswered) {
729
+ * Reads the lease of the database `firestore` was registered under with the
730
+ * boot check's budget ({@link BOOT_WEDGE_LOCK_MS}), and the fallback for it, or
731
+ * `undefined` when it does not run the durable multi-tab cache. For the page
732
+ * check (`firestore-page-wedge-check.ts`, AGL-4204).
733
+ */ export function bootWedgeCheckPartsFor(firestore) {
733
734
  const databaseName = multiTabDatabases.get(firestore);
734
- if (databaseName === undefined) return Promise.resolve('not-multi-tab');
735
- return runBootWedgeCheck({
735
+ if (databaseName === undefined) return undefined;
736
+ return {
736
737
  probe: ()=>probePrimaryLease(browserIndexedDb(), databaseName, {
737
738
  timeoutMs: BOOT_WEDGE_LOCK_MS
738
739
  }),
739
740
  fallBack: (evidence)=>fallBackToMemoryCache(evidence, {
740
741
  databaseName
741
- }),
742
+ })
743
+ };
744
+ }
745
+ /**
746
+ * Runs the boot check (AGL-4201) for `firestore`, which
747
+ * {@link markMultiTabFirestore} has registered. Call it right after
748
+ * registering. `hasServerAnswered` is the stall watch's record of server
749
+ * answers (`firestoreHasServerAnswered`), passed in so this module does not
750
+ * import the one that imports it. Fire and forget: it never rejects.
751
+ */ export function startBootWedgeCheck(firestore, hasServerAnswered) {
752
+ const parts = bootWedgeCheckPartsFor(firestore);
753
+ if (parts === undefined) return Promise.resolve('not-multi-tab');
754
+ return runBootWedgeCheck(_extends({}, parts, {
742
755
  hasServerAnswered
743
- });
756
+ }));
744
757
  }
745
758
 
746
759
  //# sourceMappingURL=firestore-multitab-wedge.js.map
@@ -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 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+FC,GAED,8DAA8D,GAC9D,OAAO,MAAMC,4BAA4B,wCAAuC;AAEhF;;;;;CAKC,GACD,OAAO,MAAMC,+BAA+B,KAAK,KAAK,KAAI;AAE1D,sFAAsF,GACtF,OAAO,MAAMC,wBAAwB,sCAAqC;AAE1E;;;;;CAKC,GACD,OAAO,MAAMC,2BAA2B,IAAI,KAAK,KAAI;AAErD;;;;;;CAMC,GACD,OAAO,MAAMC,yBAAyB,MAAM;AAE5C;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,yBAAyB,KAAK;AAE3C;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,gBAAgB,MAAM;AAEnC;;;CAGC,GACD,OAAO,MAAMC,sBAAsB,IAAG;AAEtC;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,KAAK;AAEpC,mGAAmG,GACnG,MAAMC,cAAc;AACpB,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BG,GAAG,CAACjG,YAAY;YACrCoF,2BAA2B,CAAC5B,WAC1BgB,sBAAsBhB,UAAU;oBAAEtG;gBAAa;QAEnD;QACA4I,kBAAkBI,GAAG,CAAClG,WAAW9C;IACnC;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASiJ,0BACdnG,SAAoB;IAEpB,MAAM9C,eAAe4I,kBAAkBxG,GAAG,CAACU;IAC3C,IAAI9C,iBAAiB4C,WAAW,OAAOA;IACvC,OAAOgD,sBAAsB;QAC3B/E,OAAO,IACLf,kBAAkB6E,oBAAoB3E,cAAc;gBAClDC,WAAWR;YACb;QACFqG,UAAU,CAACQ,WAAagB,sBAAsBhB,UAAU;gBAAEtG;YAAa;IACzE;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASkJ,qBACdpG,SAAoB;IAEpB,MAAM9C,eAAe4I,kBAAkBxG,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,SAAS8I,oBACdrG,SAAoB,EACpBkE,iBAAgC;IAEhC,MAAMhH,eAAe4I,kBAAkBxG,GAAG,CAACU;IAC3C,IAAI9C,iBAAiB4C,WAAW,OAAOnC,QAAQC,OAAO,CAAC;IACvD,OAAOqG,kBAAkB;QACvBlG,OAAO,IACLf,kBAAkB6E,oBAAoB3E,cAAc;gBAClDC,WAAWuG;YACb;QACFV,UAAU,CAACQ,WAAagB,sBAAsBhB,UAAU;gBAAEtG;YAAa;QACvEgH;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 /**\n * Someone has started using the page, or has left it (AGL-4204). A page in\n * use has the stall watch's budget, which protects what was typed into it.\n */\n | 'in-use'\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 /**\n * Whether the page has been used since the check began, or replaced. Checked\n * wherever `hasServerAnswered` is. The boot check has none: a page with no\n * server answer has nothing on it to lose.\n */\n isInUse?: () => 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 isInUse = () => false,\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 (isInUse()) return 'in-use'\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 (isInUse()) return 'in-use'\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 * Reads the lease of the database `firestore` was registered under with the\n * boot check's budget ({@link BOOT_WEDGE_LOCK_MS}), and the fallback for it, or\n * `undefined` when it does not run the durable multi-tab cache. For the page\n * check (`firestore-page-wedge-check.ts`, AGL-4204).\n */\nexport function bootWedgeCheckPartsFor(\n firestore: Firestore,\n):\n | Pick<BootWedgeCheckDeps, 'probe' | 'fallBack'>\n | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return {\n probe: () =>\n probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: BOOT_WEDGE_LOCK_MS,\n }),\n fallBack: (evidence) => fallBackToMemoryCache(evidence, { databaseName }),\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 parts = bootWedgeCheckPartsFor(firestore)\n if (parts === undefined) return Promise.resolve('not-multi-tab')\n return runBootWedgeCheck({ ...parts, hasServerAnswered })\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","isInUse","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","bootWedgeCheckPartsFor","startBootWedgeCheck","parts"],"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,wBAAwB,sCAAqC;AAE1E;;;;;CAKC,GACD,OAAO,MAAMC,2BAA2B,IAAI,KAAK,KAAI;AAErD;;;;;;CAMC,GACD,OAAO,MAAMC,yBAAyB,MAAM;AAE5C;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,yBAAyB,KAAK;AAE3C;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,gBAAgB,MAAM;AAEnC;;;CAGC,GACD,OAAO,MAAMC,sBAAsB,IAAG;AAEtC;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,KAAK;AAEpC,mGAAmG,GACnG,MAAMC,cAAc;AACpB,MAAMC,YAAY;AA2ClB;;;;;;;;;CASC,GACD,OAAO,eAAe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1G,WAAW,OAAOnC,QAAQC,OAAO,CAAC;IAChD,OAAOqG,kBAAkB,aAAKuC;QAAOtC;;AACvC"}
@@ -0,0 +1,94 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { Firestore } from 'firebase/firestore';
18
+ import { type BootWedgeOutcome } from './firestore-multitab-wedge';
19
+ /**
20
+ * A PAGE OPENED IN A TAB THAT IS ALREADY RUNNING FINDS ANOTHER TAB'S LOCK IN
21
+ * SECONDS TOO (AGL-4204).
22
+ *
23
+ * The boot check (`runBootWedgeCheck`, AGL-4201) rescues a tab that is still
24
+ * loading its first page: when another tab's transaction holds the shared
25
+ * cache, it reloads onto the memory cache in about 5 s. A tab that is already
26
+ * running and moves to another page never had that. Its new page's readers
27
+ * wait on the same lock, and only the stall watch rescues them: 8 s stall, 1 s
28
+ * prompt read, 3 s settle, a 20 s lock read and the reload. About half a
29
+ * minute on a spinner. Measured in production on 2026-11-11 (v1.20.2): a
30
+ * background console tab on a heavily loaded machine held the store for 40 s,
31
+ * then for about 2.5 min, and a page opened in a running tab sat on its
32
+ * spinner while a fresh tab drew the same page in 4.8 s.
33
+ *
34
+ * The stall watch's long budget is there to protect what was typed into a page
35
+ * (AGL-4135): a reload loses it. A page nobody has touched since it opened has
36
+ * nothing typed into it, which is the boot check's own premise. So when the
37
+ * path changes, the page gets the boot check, with two more ways to stand
38
+ * down:
39
+ *
40
+ * - **The server answers this client after the page opened.** The store is not
41
+ * locked for it: nothing reaches a tab's views while another tab's
42
+ * transaction holds every store.
43
+ * - **The page is used** (a pointer press, a key, typing, a paste or a drop on
44
+ * it), **or replaced** by the next page, whose own check takes over. From
45
+ * then on the page has the stall watch's budget, as every page had before.
46
+ *
47
+ * Only the path counts as a page. A query string change (a tab, a filter) is
48
+ * the same page, possibly with something typed into it.
49
+ *
50
+ * A press or key on the old page that leads to the new one (a link, a menu
51
+ * item) is the old page's: interactions are stamped with the path they
52
+ * happened on, and only those on the new path after it was first seen count.
53
+ *
54
+ * The path is read on a short timer ({@link PAGE_POLL_MS}) rather than from
55
+ * the router, so this lib does not depend on one: reading `location.pathname`
56
+ * costs nothing, and the check's own two-second delay dwarfs the lag.
57
+ */
58
+ /** How often the path is read for a page change. */
59
+ export declare const PAGE_POLL_MS = 500;
60
+ /** The events that mean someone is using the page. */
61
+ export declare const PAGE_INTERACTION_EVENTS: readonly ["pointerdown", "keydown", "input", "paste", "drop"];
62
+ /** The two ways a page's check asks about the page it was started for. */
63
+ export interface PageCheckScope {
64
+ /** Whether the server has answered this client since the page opened. */
65
+ isAnswered: () => boolean;
66
+ /** Whether the page has been used since it opened, or replaced. */
67
+ isInUse: () => boolean;
68
+ }
69
+ export interface PageWedgeWatchDeps {
70
+ /** The current page's path. */
71
+ readPath: () => string;
72
+ /** When the server last answered this client, if ever. */
73
+ lastServerAnswerAt: () => number | undefined;
74
+ /** Runs the boot check for one page. */
75
+ runCheck: (page: PageCheckScope) => Promise<BootWedgeOutcome>;
76
+ now?: () => number;
77
+ }
78
+ export interface PageWedgeWatch {
79
+ /** Records that the page on the current path was used, now. */
80
+ noteInteraction: () => void;
81
+ /**
82
+ * Reads the path. On a change, starts the new page's check and returns its
83
+ * outcome; otherwise returns `undefined`.
84
+ */
85
+ poll: () => Promise<BootWedgeOutcome> | undefined;
86
+ }
87
+ /** The page watch, with its browser parts injected. Pure over `deps`. */
88
+ export declare function createPageWedgeWatch(deps: PageWedgeWatchDeps): PageWedgeWatch;
89
+ /**
90
+ * Starts the page check for `firestore`, which `markMultiTabFirestore` has
91
+ * registered. Returns `stop`. Does nothing outside a browser or for a client
92
+ * that does not run the durable multi-tab cache. Never throws.
93
+ */
94
+ export declare function startPageWedgeChecks(firestore: Firestore): () => void;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ import { bootWedgeCheckPartsFor, runBootWedgeCheck } from "./firestore-multitab-wedge.js";
18
+ import { firestoreLastServerAnswerAt } from "./firestore-stall-recovery.js";
19
+ /**
20
+ * A PAGE OPENED IN A TAB THAT IS ALREADY RUNNING FINDS ANOTHER TAB'S LOCK IN
21
+ * SECONDS TOO (AGL-4204).
22
+ *
23
+ * The boot check (`runBootWedgeCheck`, AGL-4201) rescues a tab that is still
24
+ * loading its first page: when another tab's transaction holds the shared
25
+ * cache, it reloads onto the memory cache in about 5 s. A tab that is already
26
+ * running and moves to another page never had that. Its new page's readers
27
+ * wait on the same lock, and only the stall watch rescues them: 8 s stall, 1 s
28
+ * prompt read, 3 s settle, a 20 s lock read and the reload. About half a
29
+ * minute on a spinner. Measured in production on 2026-11-11 (v1.20.2): a
30
+ * background console tab on a heavily loaded machine held the store for 40 s,
31
+ * then for about 2.5 min, and a page opened in a running tab sat on its
32
+ * spinner while a fresh tab drew the same page in 4.8 s.
33
+ *
34
+ * The stall watch's long budget is there to protect what was typed into a page
35
+ * (AGL-4135): a reload loses it. A page nobody has touched since it opened has
36
+ * nothing typed into it, which is the boot check's own premise. So when the
37
+ * path changes, the page gets the boot check, with two more ways to stand
38
+ * down:
39
+ *
40
+ * - **The server answers this client after the page opened.** The store is not
41
+ * locked for it: nothing reaches a tab's views while another tab's
42
+ * transaction holds every store.
43
+ * - **The page is used** (a pointer press, a key, typing, a paste or a drop on
44
+ * it), **or replaced** by the next page, whose own check takes over. From
45
+ * then on the page has the stall watch's budget, as every page had before.
46
+ *
47
+ * Only the path counts as a page. A query string change (a tab, a filter) is
48
+ * the same page, possibly with something typed into it.
49
+ *
50
+ * A press or key on the old page that leads to the new one (a link, a menu
51
+ * item) is the old page's: interactions are stamped with the path they
52
+ * happened on, and only those on the new path after it was first seen count.
53
+ *
54
+ * The path is read on a short timer ({@link PAGE_POLL_MS}) rather than from
55
+ * the router, so this lib does not depend on one: reading `location.pathname`
56
+ * costs nothing, and the check's own two-second delay dwarfs the lag.
57
+ */ /** How often the path is read for a page change. */ export const PAGE_POLL_MS = 500;
58
+ /** The events that mean someone is using the page. */ export const PAGE_INTERACTION_EVENTS = [
59
+ 'pointerdown',
60
+ 'keydown',
61
+ 'input',
62
+ 'paste',
63
+ 'drop'
64
+ ];
65
+ /** The page watch, with its browser parts injected. Pure over `deps`. */ export function createPageWedgeWatch(deps) {
66
+ const { readPath, lastServerAnswerAt, runCheck, now = Date.now } = deps;
67
+ let path = readPath();
68
+ /** When `path` was last read unchanged: the new page opened after it. */ let lastSeenAt = now();
69
+ let page = 0;
70
+ let interaction;
71
+ return {
72
+ noteInteraction: ()=>{
73
+ interaction = {
74
+ path: readPath(),
75
+ at: now()
76
+ };
77
+ },
78
+ poll: ()=>{
79
+ const at = now();
80
+ const next = readPath();
81
+ if (next === path) {
82
+ lastSeenAt = at;
83
+ return undefined;
84
+ }
85
+ const openedAfter = lastSeenAt;
86
+ path = next;
87
+ lastSeenAt = at;
88
+ const mine = ++page;
89
+ return runCheck({
90
+ isAnswered: ()=>{
91
+ const answeredAt = lastServerAnswerAt();
92
+ return answeredAt !== undefined && answeredAt > openedAfter;
93
+ },
94
+ isInUse: ()=>page !== mine || interaction !== undefined && interaction.path === next && interaction.at > openedAfter
95
+ });
96
+ }
97
+ };
98
+ }
99
+ /**
100
+ * Starts the page check for `firestore`, which `markMultiTabFirestore` has
101
+ * registered. Returns `stop`. Does nothing outside a browser or for a client
102
+ * that does not run the durable multi-tab cache. Never throws.
103
+ */ export function startPageWedgeChecks(firestore) {
104
+ const parts = bootWedgeCheckPartsFor(firestore);
105
+ if (parts === undefined || typeof window === 'undefined') return ()=>undefined;
106
+ try {
107
+ const watch = createPageWedgeWatch({
108
+ readPath: ()=>window.location.pathname,
109
+ lastServerAnswerAt: ()=>firestoreLastServerAnswerAt(firestore),
110
+ runCheck: (page)=>runBootWedgeCheck(_extends({}, parts, {
111
+ hasServerAnswered: page.isAnswered,
112
+ isInUse: page.isInUse
113
+ }))
114
+ });
115
+ const onInteraction = ()=>watch.noteInteraction();
116
+ for (const type of PAGE_INTERACTION_EVENTS){
117
+ window.addEventListener(type, onInteraction, {
118
+ capture: true,
119
+ passive: true
120
+ });
121
+ }
122
+ const timer = setInterval(()=>void watch.poll(), PAGE_POLL_MS);
123
+ return ()=>{
124
+ clearInterval(timer);
125
+ for (const type of PAGE_INTERACTION_EVENTS){
126
+ window.removeEventListener(type, onInteraction, {
127
+ capture: true
128
+ });
129
+ }
130
+ };
131
+ } catch (unused) {
132
+ return ()=>undefined;
133
+ }
134
+ }
135
+
136
+ //# sourceMappingURL=firestore-page-wedge-check.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-page-wedge-check.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 {\n bootWedgeCheckPartsFor,\n runBootWedgeCheck,\n type BootWedgeOutcome,\n} from './firestore-multitab-wedge'\nimport { firestoreLastServerAnswerAt } from './firestore-stall-recovery'\n\n/**\n * A PAGE OPENED IN A TAB THAT IS ALREADY RUNNING FINDS ANOTHER TAB'S LOCK IN\n * SECONDS TOO (AGL-4204).\n *\n * The boot check (`runBootWedgeCheck`, AGL-4201) rescues a tab that is still\n * loading its first page: when another tab's transaction holds the shared\n * cache, it reloads onto the memory cache in about 5 s. A tab that is already\n * running and moves to another page never had that. Its new page's readers\n * wait on the same lock, and only the stall watch rescues them: 8 s stall, 1 s\n * prompt read, 3 s settle, a 20 s lock read and the reload. About half a\n * minute on a spinner. Measured in production on 2026-11-11 (v1.20.2): a\n * background console tab on a heavily loaded machine held the store for 40 s,\n * then for about 2.5 min, and a page opened in a running tab sat on its\n * spinner while a fresh tab drew the same page in 4.8 s.\n *\n * The stall watch's long budget is there to protect what was typed into a page\n * (AGL-4135): a reload loses it. A page nobody has touched since it opened has\n * nothing typed into it, which is the boot check's own premise. So when the\n * path changes, the page gets the boot check, with two more ways to stand\n * down:\n *\n * - **The server answers this client after the page opened.** The store is not\n * locked for it: nothing reaches a tab's views while another tab's\n * transaction holds every store.\n * - **The page is used** (a pointer press, a key, typing, a paste or a drop on\n * it), **or replaced** by the next page, whose own check takes over. From\n * then on the page has the stall watch's budget, as every page had before.\n *\n * Only the path counts as a page. A query string change (a tab, a filter) is\n * the same page, possibly with something typed into it.\n *\n * A press or key on the old page that leads to the new one (a link, a menu\n * item) is the old page's: interactions are stamped with the path they\n * happened on, and only those on the new path after it was first seen count.\n *\n * The path is read on a short timer ({@link PAGE_POLL_MS}) rather than from\n * the router, so this lib does not depend on one: reading `location.pathname`\n * costs nothing, and the check's own two-second delay dwarfs the lag.\n */\n\n/** How often the path is read for a page change. */\nexport const PAGE_POLL_MS = 500\n\n/** The events that mean someone is using the page. */\nexport const PAGE_INTERACTION_EVENTS = [\n 'pointerdown',\n 'keydown',\n 'input',\n 'paste',\n 'drop',\n] as const\n\n/** The two ways a page's check asks about the page it was started for. */\nexport interface PageCheckScope {\n /** Whether the server has answered this client since the page opened. */\n isAnswered: () => boolean\n /** Whether the page has been used since it opened, or replaced. */\n isInUse: () => boolean\n}\n\nexport interface PageWedgeWatchDeps {\n /** The current page's path. */\n readPath: () => string\n /** When the server last answered this client, if ever. */\n lastServerAnswerAt: () => number | undefined\n /** Runs the boot check for one page. */\n runCheck: (page: PageCheckScope) => Promise<BootWedgeOutcome>\n now?: () => number\n}\n\nexport interface PageWedgeWatch {\n /** Records that the page on the current path was used, now. */\n noteInteraction: () => void\n /**\n * Reads the path. On a change, starts the new page's check and returns its\n * outcome; otherwise returns `undefined`.\n */\n poll: () => Promise<BootWedgeOutcome> | undefined\n}\n\n/** The page watch, with its browser parts injected. Pure over `deps`. */\nexport function createPageWedgeWatch(deps: PageWedgeWatchDeps): PageWedgeWatch {\n const { readPath, lastServerAnswerAt, runCheck, now = Date.now } = deps\n let path = readPath()\n /** When `path` was last read unchanged: the new page opened after it. */\n let lastSeenAt = now()\n let page = 0\n let interaction: { path: string; at: number } | undefined\n\n return {\n noteInteraction: () => {\n interaction = { path: readPath(), at: now() }\n },\n poll: () => {\n const at = now()\n const next = readPath()\n if (next === path) {\n lastSeenAt = at\n return undefined\n }\n const openedAfter = lastSeenAt\n path = next\n lastSeenAt = at\n const mine = ++page\n return runCheck({\n isAnswered: () => {\n const answeredAt = lastServerAnswerAt()\n return answeredAt !== undefined && answeredAt > openedAfter\n },\n isInUse: () =>\n page !== mine ||\n (interaction !== undefined &&\n interaction.path === next &&\n interaction.at > openedAfter),\n })\n },\n }\n}\n\n/**\n * Starts the page check for `firestore`, which `markMultiTabFirestore` has\n * registered. Returns `stop`. Does nothing outside a browser or for a client\n * that does not run the durable multi-tab cache. Never throws.\n */\nexport function startPageWedgeChecks(firestore: Firestore): () => void {\n const parts = bootWedgeCheckPartsFor(firestore)\n if (parts === undefined || typeof window === 'undefined') return () => undefined\n try {\n const watch = createPageWedgeWatch({\n readPath: () => window.location.pathname,\n lastServerAnswerAt: () => firestoreLastServerAnswerAt(firestore),\n runCheck: (page) =>\n runBootWedgeCheck({\n ...parts,\n hasServerAnswered: page.isAnswered,\n isInUse: page.isInUse,\n }),\n })\n const onInteraction = () => watch.noteInteraction()\n for (const type of PAGE_INTERACTION_EVENTS) {\n window.addEventListener(type, onInteraction, { capture: true, passive: true })\n }\n const timer = setInterval(() => void watch.poll(), PAGE_POLL_MS)\n return () => {\n clearInterval(timer)\n for (const type of PAGE_INTERACTION_EVENTS) {\n window.removeEventListener(type, onInteraction, { capture: true })\n }\n }\n } catch {\n return () => undefined\n }\n}\n"],"names":["bootWedgeCheckPartsFor","runBootWedgeCheck","firestoreLastServerAnswerAt","PAGE_POLL_MS","PAGE_INTERACTION_EVENTS","createPageWedgeWatch","deps","readPath","lastServerAnswerAt","runCheck","now","Date","path","lastSeenAt","page","interaction","noteInteraction","at","poll","next","undefined","openedAfter","mine","isAnswered","answeredAt","isInUse","startPageWedgeChecks","firestore","parts","window","watch","location","pathname","hasServerAnswered","onInteraction","type","addEventListener","capture","passive","timer","setInterval","clearInterval","removeEventListener"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,SACEA,sBAAsB,EACtBC,iBAAiB,QAEZ,gCAA4B;AACnC,SAASC,2BAA2B,QAAQ,gCAA4B;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCC,GAED,kDAAkD,GAClD,OAAO,MAAMC,eAAe,IAAG;AAE/B,oDAAoD,GACpD,OAAO,MAAMC,0BAA0B;IACrC;IACA;IACA;IACA;IACA;CACD,CAAS;AA8BV,uEAAuE,GACvE,OAAO,SAASC,qBAAqBC,IAAwB;IAC3D,MAAM,EAAEC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MZ,IAAI,IAAIf;QACnD,OAAO;YACLsC,cAAcF;YACd,KAAK,MAAMJ,QAAQ/B,wBAAyB;gBAC1CyB,OAAOa,mBAAmB,CAACP,MAAMD,eAAe;oBAAEG,SAAS;gBAAK;YAClE;QACF;IACF,EAAE,eAAM;QACN,OAAO,IAAMjB;IACf;AACF"}
@@ -244,6 +244,12 @@ export declare function noteFirestoreServerAnswer(firestore: Firestore | null |
244
244
  * boot check's line between a tab still booting and one in use (AGL-4201).
245
245
  */
246
246
  export declare function firestoreHasServerAnswered(firestore: Firestore | null | undefined): boolean;
247
+ /**
248
+ * When the server last confirmed anything for `firestore` in this tab, or
249
+ * `undefined` if it has not: the page check's line between a page still
250
+ * loading and one the server has reached (AGL-4204).
251
+ */
252
+ export declare function firestoreLastServerAnswerAt(firestore: Firestore | null | undefined): number | undefined;
247
253
  /**
248
254
  * Recovers `firestore` if it has stalled. Safe to call from every reader
249
255
  * that notices: the guards above collapse the calls into at most one network
@@ -276,6 +276,13 @@ const recoveries = new WeakMap();
276
276
  */ export function firestoreHasServerAnswered(firestore) {
277
277
  return Boolean(firestore && typeof firestore === 'object' && serverAnswers.has(firestore));
278
278
  }
279
+ /**
280
+ * When the server last confirmed anything for `firestore` in this tab, or
281
+ * `undefined` if it has not: the page check's line between a page still
282
+ * loading and one the server has reached (AGL-4204).
283
+ */ export function firestoreLastServerAnswerAt(firestore) {
284
+ return firestore && typeof firestore === 'object' ? serverAnswers.get(firestore) : undefined;
285
+ }
279
286
  /**
280
287
  * Recovers `firestore` if it has stalled. Safe to call from every reader
281
288
  * that notices: the guards above collapse the calls into at most one network
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-stall-recovery.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 {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\nimport {\n browserLeaseCheckFor,\n browserWedgeEscalationFor,\n type LeaseCheck,\n} from './firestore-multitab-wedge'\n\n/**\n * RECOVERING A FIRESTORE CLIENT THAT HAS STOPPED SYNCING (AGL-3373).\n *\n * ## The wedge\n *\n * The console runs the persistent cache with `persistentMultipleTabManager`\n * (`firestore-cache.ts`). Only the PRIMARY tab talks to the backend; every\n * other tab reads the shared IndexedDB cache and takes its online state from\n * a `localStorage` record the primary writes. A secondary that believes the\n * client is online answers a `getDocs` only once the primary has synced the\n * query, and raises no first snapshot for a listener whose cache is empty.\n *\n * When the primary dies without handing over — a crashed, discarded or\n * frozen tab — its \"Online\" record outlives it, and until some tab runs the\n * lease election and wins, nothing syncs. The election runs on a 4-second\n * timer inside each tab, which the browser throttles to about once a minute\n * in a hidden tab. On 2026-09-28 no live tab synced for about ten minutes:\n * the notifications page never left its loading state and a staff page sat\n * on its splash until a fresh tab (which wins the election on start) was\n * opened.\n *\n * ## The recovery, and why it is this one\n *\n * `disableNetwork` then `enableNetwork`, from the tab that noticed. Both are\n * public API, and in the multi-tab client each one calls\n * `setNetworkEnabled`, which schedules the lease election for IMMEDIATE\n * execution instead of the next (possibly throttled) timer tick. A visible\n * tab that finds the lease lapsed takes it, starts its own streams and\n * writes its own online state, which replaces the dead tab's. A tab that was\n * already primary with a silently dead stream gets fresh streams.\n *\n * Nothing is lost. Writes made meanwhile sit in the mutation queue (in\n * IndexedDB, under the persistent cache) and are sent when the network comes\n * back; the SDK's own contract for `disableNetwork` is that writes queue.\n *\n * The rejected alternatives:\n *\n * - **Clearing the persistence cache** (`terminate` + `clearIndexedDbPersistence`).\n * It deletes the mutation queue, so pending writes are lost, and\n * `waitForPendingWrites` cannot drain them first because draining is the\n * very thing that is stuck. It also refuses to run while any other tab\n * holds the database, which in a multi-tab wedge is always. And\n * `terminate` invalidates the one `Firestore` instance every hook in the\n * console holds.\n * - **Pruning the dead tab's online-state record at startup**, beside the\n * AGL-2845 prune. The SDK already ignores an online-state record at\n * startup unless its writer is an active, non-zombie client\n * (`WebStorageSharedClientState.handleOnlineStateEvent`), and a freshly\n * started tab wins the election anyway — which is why a fresh tab fixed\n * the incident. The tabs that stayed stuck were the ones ALREADY running,\n * which a startup prune never reaches.\n * - **`persistentSingleTabManager`.** It removes cross-tab dependency, but\n * every tab after the first falls back to a memory cache, so writes made\n * offline in those tabs are lost when they close. And a tab still on the\n * multi-tab build that meets a single-tab lease holder fails its queue\n * with `failed-precondition` until reloaded, so the rollout itself would\n * wedge the tabs left open across it.\n *\n * ## Guards\n *\n * - **Online only.** A browser that reports no network is correctly offline,\n * and the cache answering is the cache doing its job.\n * - **Visible only.** A hidden tab's timers are throttled and its reader is\n * not waiting; if it is stalled, it recovers the moment it is looked at.\n * - **Once per {@link STALL_RECOVERY_COOLDOWN_MS} per client.** Every list on\n * a page stalls together, and one cycle serves them all. A concurrent\n * request shares the cycle already running.\n * - **A client the server is answering is not stalled (AGL-4120).** See below.\n * - **Nor is one waiting on the shared cache, or served by a live lease\n * holder (AGL-4135).** See below.\n * - **The network is always re-enabled**, including when disabling fails.\n * - **Each step is bounded by {@link NETWORK_STEP_TIMEOUT_MS}.** Both calls are\n * queued on the client's AsyncQueue, and when another tab has locked the\n * shared IndexedDB they queue behind an operation that never finishes\n * (AGL-3428). Unbounded, the first such cycle never settled, and every\n * later recovery request shared it forever.\n *\n * ## The cycle is not free, so it needs a silent client (AGL-4120)\n *\n * A stall watch knows one thing: ITS listener has not been confirmed. That used\n * to be enough to cycle, so one slow listener among thirty-five took the whole\n * client off the network, and the cycle did real damage to one that was working.\n * `disableNetwork` makes a primary ineligible for its own lease\n * (`canActAsPrimary`), so it hands the lease over, to a hidden tab if one is\n * waiting: captured in production as `NET-OFF, LEASE-RELEASE, NET-ON`. And while\n * the network is off, every view in a primary goes Offline, so every listener the\n * server had already confirmed reads `fromCache` again until it is confirmed a\n * second time. A contact page read server-confirmed at 9 s and unconfirmed from\n * 14 s to past a minute, on a page nobody touched, refusing every save on it. A\n * slow page was turned into a broken one by the code meant to rescue it.\n *\n * So every server-confirmed snapshot stamps the client\n * ({@link noteFirestoreServerAnswer}), and a recovery within\n * {@link FIRESTORE_STALL_MS} of one answers `'answering'` and does nothing. A\n * client that is working through a page is left to finish. One that has really\n * gone silent stops stamping, and the next watch to fire gets its cycle.\n *\n * ## A client that is waiting is not silent either (AGL-4135)\n *\n * A client can go 8 s without an answer while nothing is wrong with it. Every\n * console tab shares one IndexedDB cache, and every SDK transaction locks every\n * store. A tab that is starved (busy, slow, throttled in the background) keeps\n * each transaction open until its event loop comes back between requests, for\n * seconds at a time. A healthy tab's client waits behind that lock and cannot\n * apply what the server sends, so it raises no confirmed snapshot. Measured in\n * production (v1.5.0, two tabs): the tab holding the lease was blocked for\n * about 12 s, and when its queue drained the cycle it had asked for ran, broadcast\n * `Offline` and put every confirmed view in both tabs back on the cache, the\n * record being saved included. The cycle cannot shorten another tab's\n * transaction, because both of its calls queue behind it.\n *\n * And a client in a tab that does not hold the lease is served by the tab that\n * does. Cycling it cannot reach the holder's stream. It only marks this tab\n * `networkEnabled: false` and reruns an election the live holder wins\n * (`networkEnabled: false` at 5.7 s in the AGL-4132 run).\n *\n * So before a cycle, the client reads the lease ({@link StallRecoveryDeps.checkLease}):\n *\n * - **the read waits** (`waiting`): a transaction holds the store. No cycle.\n * The wedge check below runs in its place, since a store that stays locked is\n * the AGL-3428 wedge whether or not a cycle ran first.\n * - **another tab holds a live lease** (`served`): no cycle. The holder is\n * slow, and nothing this tab does makes it faster.\n * - **anything else** (`silent`): this tab holds the lease and its stream has\n * gone quiet, or the lease has lapsed or is vacant and an election is due.\n * That is what the cycle is for, and it runs.\n *\n * The read takes up to a second (`LEASE_PROMPT_READ_MS`), so the client is\n * asked again afterwards whether the server has answered meanwhile.\n *\n * ## When the cycle is not enough (AGL-3428)\n *\n * A tab frozen partway through an IndexedDB transaction holds every store the\n * SDK uses, and the election the cycle forces cannot run. For a client on the\n * durable multi-tab cache the cycle is followed by the lease check in\n * `firestore-multitab-wedge.ts`, which moves the tab to a memory cache when\n * the lease shows the wedge. A client found `waiting` gets that check without\n * the cycle.\n */\n\n/**\n * How long a server read or a listener's first server-confirmed snapshot may\n * take before the client is treated as stalled. A healthy console answers\n * in well under two seconds; this leaves room for a slow network without\n * leaving a reader on a spinner for long.\n */\nexport const FIRESTORE_STALL_MS = 8_000\n\n/** The least time between two recoveries of the same client. */\nexport const STALL_RECOVERY_COOLDOWN_MS = 30_000\n\n/**\n * The longest the wait between two cycles grows to, on a client that cycling is\n * not bringing back. Doubling, so that a connection too slow to answer inside\n * one cooldown is not restarted before it can.\n */\nexport const STALL_RECOVERY_MAX_COOLDOWN_MS = 5 * 60_000\n\n/**\n * The longest `disableNetwork` or `enableNetwork` may take. Both finish in\n * milliseconds on a client whose queue is moving.\n */\nexport const NETWORK_STEP_TIMEOUT_MS = 5_000\n\n/** What a recovery request did. */\nexport type StallRecoveryOutcome =\n /** The browser reports no network: the cache is the right answer. */\n | 'offline'\n /** The tab is hidden: nobody is waiting on it. */\n | 'hidden'\n /** A recovery ran moments ago; this request rode on it. */\n | 'cooling'\n /** The server answered this client moments ago: it is busy, not stalled. */\n | 'answering'\n /** A transaction holds the shared cache, and this client is queued behind it (AGL-4135). */\n | 'waiting'\n /** Another tab holds a live lease and serves this client (AGL-4135). */\n | 'served'\n /** The network was cycled. */\n | 'recovered'\n /** The cycle threw or timed out; the network was still re-enabled if at all possible. */\n | 'failed'\n /** The multi-tab cache was wedged and this tab is moving to the memory cache. */\n | 'fell-back'\n\nexport interface StallRecoveryDeps {\n /** Take the client off the network. */\n disable: () => Promise<void>\n /** Put it back. */\n enable: () => Promise<void>\n /** `navigator.onLine`, or `true` where there is no navigator. */\n isOnline?: () => boolean\n /** Whether the document is visible, or `true` where there is none. */\n isVisible?: () => boolean\n now?: () => number\n /**\n * When the server last confirmed anything for this client, or `undefined`\n * if it has not. Without one, every stall is taken at its word.\n */\n lastServerAnswerAt?: () => number | undefined\n /** How recent an answer proves the client is alive. */\n answeringWindowMs?: number\n cooldownMs?: number\n /** The bound on each of `disable` and `enable`. */\n stepTimeoutMs?: number\n /**\n * Reads the shared cache's lease before a cycle (AGL-4135). Only a multi-tab\n * client has one; without it, every stall that passes the other guards is\n * cycled.\n */\n checkLease?: () => Promise<LeaseCheck>\n /**\n * The wedge check. Runs after every cycle, and in place of one for a client\n * found `waiting`. Resolves `true` when it has moved the tab off the shared\n * cache. Only a multi-tab client has one.\n */\n escalate?: () => Promise<boolean>\n}\n\nexport interface StallRecovery {\n recover: () => Promise<StallRecoveryOutcome>\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/** The recovery for one client, with its guards. Pure over `deps`. */\nexport function createStallRecovery(deps: StallRecoveryDeps): StallRecovery {\n const {\n disable,\n enable,\n isOnline = browserOnline,\n isVisible = documentVisible,\n now = Date.now,\n lastServerAnswerAt,\n answeringWindowMs = FIRESTORE_STALL_MS,\n cooldownMs = STALL_RECOVERY_COOLDOWN_MS,\n stepTimeoutMs = NETWORK_STEP_TIMEOUT_MS,\n checkLease,\n escalate,\n } = deps\n let lastStartedAt: number | undefined\n /** Cycles in a row that the server has not answered since. */\n let quietCycles = 0\n /** When a client found waiting last had the wedge check (AGL-4135). */\n let lastWaitCheckedAt: number | undefined\n let running: Promise<StallRecoveryOutcome> | undefined\n\n /** Whether `step` settled successfully within `stepTimeoutMs`. */\n const bounded = (step: () => Promise<void>): Promise<boolean> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), stepTimeoutMs)\n const done = (ok: boolean) => {\n clearTimeout(timer)\n resolve(ok)\n }\n try {\n step().then(\n () => done(true),\n () => done(false),\n )\n } catch {\n done(false)\n }\n })\n\n /** Whether the escalation moved the tab off the shared cache. Best effort. */\n const escalated = async (): Promise<boolean> => {\n if (!escalate) return false\n try {\n return await escalate()\n } catch {\n return false\n }\n }\n\n const cycle = async (): Promise<StallRecoveryOutcome> => {\n let outcome: StallRecoveryOutcome = 'recovered'\n if (!(await bounded(disable))) outcome = 'failed'\n if (!(await bounded(enable))) outcome = 'failed'\n // The escalation is best effort; the cycle's own outcome stands.\n return (await escalated()) ? 'fell-back' : outcome\n }\n\n const answeredWithin = (at: number): boolean => {\n const answeredAt = lastServerAnswerAt?.()\n return answeredAt !== undefined && at - answeredAt < answeringWindowMs\n }\n\n /** Past the guards: reads the lease, then cycles only a client nothing explains. */\n const attempt = async (): Promise<StallRecoveryOutcome> => {\n let lease: LeaseCheck = { state: 'silent' }\n if (checkLease) {\n try {\n lease = await checkLease()\n } catch {\n // Unread, the stall is taken at its word, as it always was.\n }\n }\n if (lease.state === 'served') return 'served'\n if (lease.state === 'waiting') {\n // As often as a cycle would have run it, and no more: every check is\n // one more chance for a long wait to read as a wedge.\n const checkedAt = now()\n if (\n lastWaitCheckedAt !== undefined &&\n checkedAt - lastWaitCheckedAt < cooldownMs\n ) {\n return 'waiting'\n }\n lastWaitCheckedAt = checkedAt\n return (await escalated()) ? 'fell-back' : 'waiting'\n }\n // The read took time, and a client that was waiting may have answered.\n const at = now()\n if (answeredWithin(at)) return 'answering'\n if (lastStartedAt !== undefined) {\n const answeredAt = lastServerAnswerAt?.()\n const answeredSince =\n answeredAt !== undefined && answeredAt >= lastStartedAt\n quietCycles = answeredSince ? 0 : quietCycles + 1\n }\n lastStartedAt = at\n return cycle()\n }\n\n return {\n recover: () => {\n if (running) return running\n if (!isOnline()) return Promise.resolve('offline')\n if (!isVisible()) return Promise.resolve('hidden')\n const at = now()\n if (answeredWithin(at)) return Promise.resolve('answering')\n if (lastStartedAt !== undefined) {\n const cooldown = Math.min(\n cooldownMs * 2 ** quietCycles,\n STALL_RECOVERY_MAX_COOLDOWN_MS,\n )\n if (at - lastStartedAt < cooldown) return Promise.resolve('cooling')\n }\n running = attempt().finally(() => {\n running = undefined\n })\n return running\n },\n }\n}\n\nconst recoveries = new WeakMap<Firestore, StallRecovery>()\n\n/** When the server last confirmed a snapshot for each client. */\nconst serverAnswers = new WeakMap<Firestore, number>()\n\n/**\n * Records that the server just confirmed something for `firestore`: the\n * evidence a stall watch does not have that this client is alive. Every listener\n * that arms a watch calls this on a server-confirmed snapshot.\n */\nexport function noteFirestoreServerAnswer(\n firestore: Firestore | null | undefined,\n): void {\n if (firestore && typeof firestore === 'object') {\n serverAnswers.set(firestore, Date.now())\n }\n}\n\n/**\n * Whether the server has confirmed anything for `firestore` in this tab: the\n * boot check's line between a tab still booting and one in use (AGL-4201).\n */\nexport function firestoreHasServerAnswered(\n firestore: Firestore | null | undefined,\n): boolean {\n return Boolean(\n firestore && typeof firestore === 'object' && serverAnswers.has(firestore),\n )\n}\n\n/**\n * Recovers `firestore` if it has stalled. Safe to call from every reader\n * that notices: the guards above collapse the calls into at most one network\n * cycle per cooldown. Never rejects.\n */\nexport function recoverStalledFirestore(\n firestore: Firestore | null | undefined,\n): Promise<StallRecoveryOutcome> {\n if (!firestore || typeof firestore !== 'object') {\n return Promise.resolve('failed')\n }\n let recovery = recoveries.get(firestore)\n if (!recovery) {\n recovery = createStallRecovery({\n disable: () => disableNetwork(firestore),\n enable: () => enableNetwork(firestore),\n lastServerAnswerAt: () => serverAnswers.get(firestore),\n checkLease: browserLeaseCheckFor(firestore),\n escalate: browserWedgeEscalationFor(firestore),\n })\n recoveries.set(firestore, recovery)\n }\n return recovery.recover().catch(() => 'failed' as const)\n}\n\n/**\n * Arms a stall timer for one read or listen. Until `disarm` is called, `onStall`\n * runs (by default, {@link recoverStalledFirestore}) every `stallMs`. A tab that\n * is hidden when the timer fires waits until it is shown, since that is when a\n * reader is waiting again.\n *\n * It keeps firing because one call can do nothing: the request may land inside\n * a cooldown, or on a client that is still answering. A watch that spent itself\n * there left its listener unconfirmed for life (AGL-4120), which is how a tab's\n * first page worked and a later page's saves were refused. The calls cost nothing\n * until one of them finds a client that really needs a cycle.\n *\n * Returns `disarm`, which is idempotent.\n */\nexport function armFirestoreStallWatch(\n firestore: Firestore | null | undefined,\n options: { stallMs?: number; onStall?: () => void } = {},\n): () => void {\n const { stallMs = FIRESTORE_STALL_MS } = options\n const onStall =\n options.onStall ?? (() => void recoverStalledFirestore(firestore))\n let done = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let onVisible: (() => void) | undefined\n const fire = () => {\n if (done) return\n if (!documentVisible() && typeof document !== 'undefined') {\n onVisible = () => {\n if (!documentVisible()) return\n document.removeEventListener('visibilitychange', onVisible!)\n onVisible = undefined\n fire()\n }\n document.addEventListener('visibilitychange', onVisible)\n return\n }\n onStall()\n timer = setTimeout(fire, stallMs)\n }\n timer = setTimeout(fire, stallMs)\n return () => {\n if (done) return\n done = true\n clearTimeout(timer)\n if (onVisible && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisible)\n }\n }\n}\n"],"names":["disableNetwork","enableNetwork","browserLeaseCheckFor","browserWedgeEscalationFor","FIRESTORE_STALL_MS","STALL_RECOVERY_COOLDOWN_MS","STALL_RECOVERY_MAX_COOLDOWN_MS","NETWORK_STEP_TIMEOUT_MS","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createStallRecovery","deps","disable","enable","isOnline","isVisible","now","Date","lastServerAnswerAt","answeringWindowMs","cooldownMs","stepTimeoutMs","checkLease","escalate","lastStartedAt","quietCycles","lastWaitCheckedAt","running","bounded","step","Promise","resolve","timer","setTimeout","done","ok","clearTimeout","then","escalated","cycle","outcome","answeredWithin","at","answeredAt","undefined","attempt","lease","state","checkedAt","answeredSince","recover","cooldown","Math","min","finally","recoveries","WeakMap","serverAnswers","noteFirestoreServerAnswer","firestore","set","firestoreHasServerAnswered","Boolean","has","recoverStalledFirestore","recovery","get","catch","armFirestoreStallWatch","options","stallMs","onStall","onVisible","fire","removeEventListener","addEventListener"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAE3B,SACEC,oBAAoB,EACpBC,yBAAyB,QAEpB,gCAA4B;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0IC,GAED;;;;;CAKC,GACD,OAAO,MAAMC,qBAAqB,KAAK;AAEvC,8DAA8D,GAC9D,OAAO,MAAMC,6BAA6B,MAAM;AAEhD;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,IAAI,MAAM;AAExD;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,KAAK;AA6D5C,MAAMC,gBAAgB,IACpB,OAAOC,cAAc,eAAeA,UAAUC,MAAM,KAAK;AAE3D,MAAMC,kBAAkB,IACtB,OAAOC,aAAa,eAAeA,SAASC,eAAe,KAAK;AAElE,oEAAoE,GACpE,OAAO,SAASC,oBAAoBC,IAAuB;IACzD,MAAM,EACJC,OAAO,EACPC,MAAM,EACNC,WAAWV,aAAa,EACxBW,YAAYR,eAAe,EAC3BS,MAAMC,KAAKD,GAAG,EACdE,kBAAkB,EAClBC,oBAAoBnB,kBAAkB,EACtCoB,aAAanB,0BAA0B,EACvCoB,gBAAgBlB,uBAAuB,EACvCmB,UAAU,EACVC,QAAQ,EACT,GAAGZ;IACJ,IAAIa;IACJ,4DAA4D,GAC5D,IAAIC,cAAc;IAClB,qEAAqE,GACrE,IAAIC;IACJ,IAAIC;IAEJ,gEAAgE,GAChE,MAAMC,UAAU,CAACC,OACf,IAAIC,QAAQ,CAACC;YACX,MAAMC,QAAQC,WAAW,IAAMF,QAAQ,QAAQV;YAC/C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AC5CrC,YAAYxB,qBAAqB6D;YACjCpC,UAAUxB,0BAA0B4D;QACtC;QACAJ,WAAWK,GAAG,CAACD,WAAWM;IAC5B;IACA,OAAOA,SAASf,OAAO,GAAGiB,KAAK,CAAC,IAAM;AACxC;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,uBACdT,SAAuC,EACvCU,UAAsD,CAAC,CAAC;QAItDA;IAFF,MAAM,EAAEC,UAAUtE,kBAAkB,EAAE,GAAGqE;IACzC,MAAME,WACJF,mBAAAA,QAAQE,OAAO,YAAfF,mBAAoB,IAAM,KAAKL,wBAAwBL;IACzD,IAAIzB,OAAO;IACX,IAAIF;IACJ,IAAIwC;IACJ,MAAMC,OAAO;QACX,IAAIvC,MAAM;QACV,IAAI,CAAC3B,qBAAqB,OAAOC,aAAa,aAAa;YACzDgE,YAAY;gBACV,IAAI,CAACjE,mBAAmB;gBACxBC,SAASkE,mBAAmB,CAAC,oBAAoBF;gBACjDA,YAAY5B;gBACZ6B;YACF;YACAjE,SAASmE,gBAAgB,CAAC,oBAAoBH;YAC9C;QACF;QACAD;QACAvC,QAAQC,WAAWwC,MAAMH;IAC3B;IACAtC,QAAQC,WAAWwC,MAAMH;IACzB,OAAO;QACL,IAAIpC,MAAM;QACVA,OAAO;QACPE,aAAaJ;QACb,IAAIwC,aAAa,OAAOhE,aAAa,aAAa;YAChDA,SAASkE,mBAAmB,CAAC,oBAAoBF;QACnD;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-stall-recovery.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 {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\nimport {\n browserLeaseCheckFor,\n browserWedgeEscalationFor,\n type LeaseCheck,\n} from './firestore-multitab-wedge'\n\n/**\n * RECOVERING A FIRESTORE CLIENT THAT HAS STOPPED SYNCING (AGL-3373).\n *\n * ## The wedge\n *\n * The console runs the persistent cache with `persistentMultipleTabManager`\n * (`firestore-cache.ts`). Only the PRIMARY tab talks to the backend; every\n * other tab reads the shared IndexedDB cache and takes its online state from\n * a `localStorage` record the primary writes. A secondary that believes the\n * client is online answers a `getDocs` only once the primary has synced the\n * query, and raises no first snapshot for a listener whose cache is empty.\n *\n * When the primary dies without handing over — a crashed, discarded or\n * frozen tab — its \"Online\" record outlives it, and until some tab runs the\n * lease election and wins, nothing syncs. The election runs on a 4-second\n * timer inside each tab, which the browser throttles to about once a minute\n * in a hidden tab. On 2026-09-28 no live tab synced for about ten minutes:\n * the notifications page never left its loading state and a staff page sat\n * on its splash until a fresh tab (which wins the election on start) was\n * opened.\n *\n * ## The recovery, and why it is this one\n *\n * `disableNetwork` then `enableNetwork`, from the tab that noticed. Both are\n * public API, and in the multi-tab client each one calls\n * `setNetworkEnabled`, which schedules the lease election for IMMEDIATE\n * execution instead of the next (possibly throttled) timer tick. A visible\n * tab that finds the lease lapsed takes it, starts its own streams and\n * writes its own online state, which replaces the dead tab's. A tab that was\n * already primary with a silently dead stream gets fresh streams.\n *\n * Nothing is lost. Writes made meanwhile sit in the mutation queue (in\n * IndexedDB, under the persistent cache) and are sent when the network comes\n * back; the SDK's own contract for `disableNetwork` is that writes queue.\n *\n * The rejected alternatives:\n *\n * - **Clearing the persistence cache** (`terminate` + `clearIndexedDbPersistence`).\n * It deletes the mutation queue, so pending writes are lost, and\n * `waitForPendingWrites` cannot drain them first because draining is the\n * very thing that is stuck. It also refuses to run while any other tab\n * holds the database, which in a multi-tab wedge is always. And\n * `terminate` invalidates the one `Firestore` instance every hook in the\n * console holds.\n * - **Pruning the dead tab's online-state record at startup**, beside the\n * AGL-2845 prune. The SDK already ignores an online-state record at\n * startup unless its writer is an active, non-zombie client\n * (`WebStorageSharedClientState.handleOnlineStateEvent`), and a freshly\n * started tab wins the election anyway — which is why a fresh tab fixed\n * the incident. The tabs that stayed stuck were the ones ALREADY running,\n * which a startup prune never reaches.\n * - **`persistentSingleTabManager`.** It removes cross-tab dependency, but\n * every tab after the first falls back to a memory cache, so writes made\n * offline in those tabs are lost when they close. And a tab still on the\n * multi-tab build that meets a single-tab lease holder fails its queue\n * with `failed-precondition` until reloaded, so the rollout itself would\n * wedge the tabs left open across it.\n *\n * ## Guards\n *\n * - **Online only.** A browser that reports no network is correctly offline,\n * and the cache answering is the cache doing its job.\n * - **Visible only.** A hidden tab's timers are throttled and its reader is\n * not waiting; if it is stalled, it recovers the moment it is looked at.\n * - **Once per {@link STALL_RECOVERY_COOLDOWN_MS} per client.** Every list on\n * a page stalls together, and one cycle serves them all. A concurrent\n * request shares the cycle already running.\n * - **A client the server is answering is not stalled (AGL-4120).** See below.\n * - **Nor is one waiting on the shared cache, or served by a live lease\n * holder (AGL-4135).** See below.\n * - **The network is always re-enabled**, including when disabling fails.\n * - **Each step is bounded by {@link NETWORK_STEP_TIMEOUT_MS}.** Both calls are\n * queued on the client's AsyncQueue, and when another tab has locked the\n * shared IndexedDB they queue behind an operation that never finishes\n * (AGL-3428). Unbounded, the first such cycle never settled, and every\n * later recovery request shared it forever.\n *\n * ## The cycle is not free, so it needs a silent client (AGL-4120)\n *\n * A stall watch knows one thing: ITS listener has not been confirmed. That used\n * to be enough to cycle, so one slow listener among thirty-five took the whole\n * client off the network, and the cycle did real damage to one that was working.\n * `disableNetwork` makes a primary ineligible for its own lease\n * (`canActAsPrimary`), so it hands the lease over, to a hidden tab if one is\n * waiting: captured in production as `NET-OFF, LEASE-RELEASE, NET-ON`. And while\n * the network is off, every view in a primary goes Offline, so every listener the\n * server had already confirmed reads `fromCache` again until it is confirmed a\n * second time. A contact page read server-confirmed at 9 s and unconfirmed from\n * 14 s to past a minute, on a page nobody touched, refusing every save on it. A\n * slow page was turned into a broken one by the code meant to rescue it.\n *\n * So every server-confirmed snapshot stamps the client\n * ({@link noteFirestoreServerAnswer}), and a recovery within\n * {@link FIRESTORE_STALL_MS} of one answers `'answering'` and does nothing. A\n * client that is working through a page is left to finish. One that has really\n * gone silent stops stamping, and the next watch to fire gets its cycle.\n *\n * ## A client that is waiting is not silent either (AGL-4135)\n *\n * A client can go 8 s without an answer while nothing is wrong with it. Every\n * console tab shares one IndexedDB cache, and every SDK transaction locks every\n * store. A tab that is starved (busy, slow, throttled in the background) keeps\n * each transaction open until its event loop comes back between requests, for\n * seconds at a time. A healthy tab's client waits behind that lock and cannot\n * apply what the server sends, so it raises no confirmed snapshot. Measured in\n * production (v1.5.0, two tabs): the tab holding the lease was blocked for\n * about 12 s, and when its queue drained the cycle it had asked for ran, broadcast\n * `Offline` and put every confirmed view in both tabs back on the cache, the\n * record being saved included. The cycle cannot shorten another tab's\n * transaction, because both of its calls queue behind it.\n *\n * And a client in a tab that does not hold the lease is served by the tab that\n * does. Cycling it cannot reach the holder's stream. It only marks this tab\n * `networkEnabled: false` and reruns an election the live holder wins\n * (`networkEnabled: false` at 5.7 s in the AGL-4132 run).\n *\n * So before a cycle, the client reads the lease ({@link StallRecoveryDeps.checkLease}):\n *\n * - **the read waits** (`waiting`): a transaction holds the store. No cycle.\n * The wedge check below runs in its place, since a store that stays locked is\n * the AGL-3428 wedge whether or not a cycle ran first.\n * - **another tab holds a live lease** (`served`): no cycle. The holder is\n * slow, and nothing this tab does makes it faster.\n * - **anything else** (`silent`): this tab holds the lease and its stream has\n * gone quiet, or the lease has lapsed or is vacant and an election is due.\n * That is what the cycle is for, and it runs.\n *\n * The read takes up to a second (`LEASE_PROMPT_READ_MS`), so the client is\n * asked again afterwards whether the server has answered meanwhile.\n *\n * ## When the cycle is not enough (AGL-3428)\n *\n * A tab frozen partway through an IndexedDB transaction holds every store the\n * SDK uses, and the election the cycle forces cannot run. For a client on the\n * durable multi-tab cache the cycle is followed by the lease check in\n * `firestore-multitab-wedge.ts`, which moves the tab to a memory cache when\n * the lease shows the wedge. A client found `waiting` gets that check without\n * the cycle.\n */\n\n/**\n * How long a server read or a listener's first server-confirmed snapshot may\n * take before the client is treated as stalled. A healthy console answers\n * in well under two seconds; this leaves room for a slow network without\n * leaving a reader on a spinner for long.\n */\nexport const FIRESTORE_STALL_MS = 8_000\n\n/** The least time between two recoveries of the same client. */\nexport const STALL_RECOVERY_COOLDOWN_MS = 30_000\n\n/**\n * The longest the wait between two cycles grows to, on a client that cycling is\n * not bringing back. Doubling, so that a connection too slow to answer inside\n * one cooldown is not restarted before it can.\n */\nexport const STALL_RECOVERY_MAX_COOLDOWN_MS = 5 * 60_000\n\n/**\n * The longest `disableNetwork` or `enableNetwork` may take. Both finish in\n * milliseconds on a client whose queue is moving.\n */\nexport const NETWORK_STEP_TIMEOUT_MS = 5_000\n\n/** What a recovery request did. */\nexport type StallRecoveryOutcome =\n /** The browser reports no network: the cache is the right answer. */\n | 'offline'\n /** The tab is hidden: nobody is waiting on it. */\n | 'hidden'\n /** A recovery ran moments ago; this request rode on it. */\n | 'cooling'\n /** The server answered this client moments ago: it is busy, not stalled. */\n | 'answering'\n /** A transaction holds the shared cache, and this client is queued behind it (AGL-4135). */\n | 'waiting'\n /** Another tab holds a live lease and serves this client (AGL-4135). */\n | 'served'\n /** The network was cycled. */\n | 'recovered'\n /** The cycle threw or timed out; the network was still re-enabled if at all possible. */\n | 'failed'\n /** The multi-tab cache was wedged and this tab is moving to the memory cache. */\n | 'fell-back'\n\nexport interface StallRecoveryDeps {\n /** Take the client off the network. */\n disable: () => Promise<void>\n /** Put it back. */\n enable: () => Promise<void>\n /** `navigator.onLine`, or `true` where there is no navigator. */\n isOnline?: () => boolean\n /** Whether the document is visible, or `true` where there is none. */\n isVisible?: () => boolean\n now?: () => number\n /**\n * When the server last confirmed anything for this client, or `undefined`\n * if it has not. Without one, every stall is taken at its word.\n */\n lastServerAnswerAt?: () => number | undefined\n /** How recent an answer proves the client is alive. */\n answeringWindowMs?: number\n cooldownMs?: number\n /** The bound on each of `disable` and `enable`. */\n stepTimeoutMs?: number\n /**\n * Reads the shared cache's lease before a cycle (AGL-4135). Only a multi-tab\n * client has one; without it, every stall that passes the other guards is\n * cycled.\n */\n checkLease?: () => Promise<LeaseCheck>\n /**\n * The wedge check. Runs after every cycle, and in place of one for a client\n * found `waiting`. Resolves `true` when it has moved the tab off the shared\n * cache. Only a multi-tab client has one.\n */\n escalate?: () => Promise<boolean>\n}\n\nexport interface StallRecovery {\n recover: () => Promise<StallRecoveryOutcome>\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/** The recovery for one client, with its guards. Pure over `deps`. */\nexport function createStallRecovery(deps: StallRecoveryDeps): StallRecovery {\n const {\n disable,\n enable,\n isOnline = browserOnline,\n isVisible = documentVisible,\n now = Date.now,\n lastServerAnswerAt,\n answeringWindowMs = FIRESTORE_STALL_MS,\n cooldownMs = STALL_RECOVERY_COOLDOWN_MS,\n stepTimeoutMs = NETWORK_STEP_TIMEOUT_MS,\n checkLease,\n escalate,\n } = deps\n let lastStartedAt: number | undefined\n /** Cycles in a row that the server has not answered since. */\n let quietCycles = 0\n /** When a client found waiting last had the wedge check (AGL-4135). */\n let lastWaitCheckedAt: number | undefined\n let running: Promise<StallRecoveryOutcome> | undefined\n\n /** Whether `step` settled successfully within `stepTimeoutMs`. */\n const bounded = (step: () => Promise<void>): Promise<boolean> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), stepTimeoutMs)\n const done = (ok: boolean) => {\n clearTimeout(timer)\n resolve(ok)\n }\n try {\n step().then(\n () => done(true),\n () => done(false),\n )\n } catch {\n done(false)\n }\n })\n\n /** Whether the escalation moved the tab off the shared cache. Best effort. */\n const escalated = async (): Promise<boolean> => {\n if (!escalate) return false\n try {\n return await escalate()\n } catch {\n return false\n }\n }\n\n const cycle = async (): Promise<StallRecoveryOutcome> => {\n let outcome: StallRecoveryOutcome = 'recovered'\n if (!(await bounded(disable))) outcome = 'failed'\n if (!(await bounded(enable))) outcome = 'failed'\n // The escalation is best effort; the cycle's own outcome stands.\n return (await escalated()) ? 'fell-back' : outcome\n }\n\n const answeredWithin = (at: number): boolean => {\n const answeredAt = lastServerAnswerAt?.()\n return answeredAt !== undefined && at - answeredAt < answeringWindowMs\n }\n\n /** Past the guards: reads the lease, then cycles only a client nothing explains. */\n const attempt = async (): Promise<StallRecoveryOutcome> => {\n let lease: LeaseCheck = { state: 'silent' }\n if (checkLease) {\n try {\n lease = await checkLease()\n } catch {\n // Unread, the stall is taken at its word, as it always was.\n }\n }\n if (lease.state === 'served') return 'served'\n if (lease.state === 'waiting') {\n // As often as a cycle would have run it, and no more: every check is\n // one more chance for a long wait to read as a wedge.\n const checkedAt = now()\n if (\n lastWaitCheckedAt !== undefined &&\n checkedAt - lastWaitCheckedAt < cooldownMs\n ) {\n return 'waiting'\n }\n lastWaitCheckedAt = checkedAt\n return (await escalated()) ? 'fell-back' : 'waiting'\n }\n // The read took time, and a client that was waiting may have answered.\n const at = now()\n if (answeredWithin(at)) return 'answering'\n if (lastStartedAt !== undefined) {\n const answeredAt = lastServerAnswerAt?.()\n const answeredSince =\n answeredAt !== undefined && answeredAt >= lastStartedAt\n quietCycles = answeredSince ? 0 : quietCycles + 1\n }\n lastStartedAt = at\n return cycle()\n }\n\n return {\n recover: () => {\n if (running) return running\n if (!isOnline()) return Promise.resolve('offline')\n if (!isVisible()) return Promise.resolve('hidden')\n const at = now()\n if (answeredWithin(at)) return Promise.resolve('answering')\n if (lastStartedAt !== undefined) {\n const cooldown = Math.min(\n cooldownMs * 2 ** quietCycles,\n STALL_RECOVERY_MAX_COOLDOWN_MS,\n )\n if (at - lastStartedAt < cooldown) return Promise.resolve('cooling')\n }\n running = attempt().finally(() => {\n running = undefined\n })\n return running\n },\n }\n}\n\nconst recoveries = new WeakMap<Firestore, StallRecovery>()\n\n/** When the server last confirmed a snapshot for each client. */\nconst serverAnswers = new WeakMap<Firestore, number>()\n\n/**\n * Records that the server just confirmed something for `firestore`: the\n * evidence a stall watch does not have that this client is alive. Every listener\n * that arms a watch calls this on a server-confirmed snapshot.\n */\nexport function noteFirestoreServerAnswer(\n firestore: Firestore | null | undefined,\n): void {\n if (firestore && typeof firestore === 'object') {\n serverAnswers.set(firestore, Date.now())\n }\n}\n\n/**\n * Whether the server has confirmed anything for `firestore` in this tab: the\n * boot check's line between a tab still booting and one in use (AGL-4201).\n */\nexport function firestoreHasServerAnswered(\n firestore: Firestore | null | undefined,\n): boolean {\n return Boolean(\n firestore && typeof firestore === 'object' && serverAnswers.has(firestore),\n )\n}\n\n/**\n * When the server last confirmed anything for `firestore` in this tab, or\n * `undefined` if it has not: the page check's line between a page still\n * loading and one the server has reached (AGL-4204).\n */\nexport function firestoreLastServerAnswerAt(\n firestore: Firestore | null | undefined,\n): number | undefined {\n return firestore && typeof firestore === 'object'\n ? serverAnswers.get(firestore)\n : undefined\n}\n\n/**\n * Recovers `firestore` if it has stalled. Safe to call from every reader\n * that notices: the guards above collapse the calls into at most one network\n * cycle per cooldown. Never rejects.\n */\nexport function recoverStalledFirestore(\n firestore: Firestore | null | undefined,\n): Promise<StallRecoveryOutcome> {\n if (!firestore || typeof firestore !== 'object') {\n return Promise.resolve('failed')\n }\n let recovery = recoveries.get(firestore)\n if (!recovery) {\n recovery = createStallRecovery({\n disable: () => disableNetwork(firestore),\n enable: () => enableNetwork(firestore),\n lastServerAnswerAt: () => serverAnswers.get(firestore),\n checkLease: browserLeaseCheckFor(firestore),\n escalate: browserWedgeEscalationFor(firestore),\n })\n recoveries.set(firestore, recovery)\n }\n return recovery.recover().catch(() => 'failed' as const)\n}\n\n/**\n * Arms a stall timer for one read or listen. Until `disarm` is called, `onStall`\n * runs (by default, {@link recoverStalledFirestore}) every `stallMs`. A tab that\n * is hidden when the timer fires waits until it is shown, since that is when a\n * reader is waiting again.\n *\n * It keeps firing because one call can do nothing: the request may land inside\n * a cooldown, or on a client that is still answering. A watch that spent itself\n * there left its listener unconfirmed for life (AGL-4120), which is how a tab's\n * first page worked and a later page's saves were refused. The calls cost nothing\n * until one of them finds a client that really needs a cycle.\n *\n * Returns `disarm`, which is idempotent.\n */\nexport function armFirestoreStallWatch(\n firestore: Firestore | null | undefined,\n options: { stallMs?: number; onStall?: () => void } = {},\n): () => void {\n const { stallMs = FIRESTORE_STALL_MS } = options\n const onStall =\n options.onStall ?? (() => void recoverStalledFirestore(firestore))\n let done = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let onVisible: (() => void) | undefined\n const fire = () => {\n if (done) return\n if (!documentVisible() && typeof document !== 'undefined') {\n onVisible = () => {\n if (!documentVisible()) return\n document.removeEventListener('visibilitychange', onVisible!)\n onVisible = undefined\n fire()\n }\n document.addEventListener('visibilitychange', onVisible)\n return\n }\n onStall()\n timer = setTimeout(fire, stallMs)\n }\n timer = setTimeout(fire, stallMs)\n return () => {\n if (done) return\n done = true\n clearTimeout(timer)\n if (onVisible && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisible)\n }\n }\n}\n"],"names":["disableNetwork","enableNetwork","browserLeaseCheckFor","browserWedgeEscalationFor","FIRESTORE_STALL_MS","STALL_RECOVERY_COOLDOWN_MS","STALL_RECOVERY_MAX_COOLDOWN_MS","NETWORK_STEP_TIMEOUT_MS","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createStallRecovery","deps","disable","enable","isOnline","isVisible","now","Date","lastServerAnswerAt","answeringWindowMs","cooldownMs","stepTimeoutMs","checkLease","escalate","lastStartedAt","quietCycles","lastWaitCheckedAt","running","bounded","step","Promise","resolve","timer","setTimeout","done","ok","clearTimeout","then","escalated","cycle","outcome","answeredWithin","at","answeredAt","undefined","attempt","lease","state","checkedAt","answeredSince","recover","cooldown","Math","min","finally","recoveries","WeakMap","serverAnswers","noteFirestoreServerAnswer","firestore","set","firestoreHasServerAnswered","Boolean","has","firestoreLastServerAnswerAt","get","recoverStalledFirestore","recovery","catch","armFirestoreStallWatch","options","stallMs","onStall","onVisible","fire","removeEventListener","addEventListener"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAE3B,SACEC,oBAAoB,EACpBC,yBAAyB,QAEpB,gCAA4B;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0IC,GAED;;;;;CAKC,GACD,OAAO,MAAMC,qBAAqB,KAAK;AAEvC,8DAA8D,GAC9D,OAAO,MAAMC,6BAA6B,MAAM;AAEhD;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,IAAI,MAAM;AAExD;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,KAAK;AA6D5C,MAAMC,gBAAgB,IACpB,OAAOC,cAAc,eAAeA,UAAUC,MAAM,KAAK;AAE3D,MAAMC,kBAAkB,IACtB,OAAOC,aAAa,eAAeA,SAASC,eAAe,KAAK;AAElE,oEAAoE,GACpE,OAAO,SAASC,oBAAoBC,IAAuB;IACzD,MAAM,EACJC,OAAO,EACPC,MAAM,EACNC,WAAWV,aAAa,EACxBW,YAAYR,eAAe,EAC3BS,MAAMC,KAAKD,GAAG,EACdE,kBAAkB,EAClBC,oBAAoBnB,kBAAkB,EACtCoB,aAAanB,0BAA0B,EACvCoB,gBAAgBlB,uBAAuB,EACvCmB,UAAU,EACVC,QAAQ,EACT,GAAGZ;IACJ,IAAIa;IACJ,4DAA4D,GAC5D,IAAIC,cAAc;IAClB,qEAAqE,GACrE,IAAIC;IACJ,IAAIC;IAEJ,gEA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