@aglyn/tenant-feature-instance 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/hooks/firebase/firebase-services.d.ts +7 -0
- package/src/lib/hooks/firebase/firebase-services.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.d.ts +67 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js +81 -2
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-stall-recovery.d.ts +52 -4
- package/src/lib/hooks/firebase/firestore-stall-recovery.js +87 -16
- package/src/lib/hooks/firebase/firestore-stall-recovery.js.map +1 -1
- package/src/lib/hooks/helpers/guarded-seed-write.d.ts +71 -1
- package/src/lib/hooks/helpers/guarded-seed-write.js +4 -3
- package/src/lib/hooks/helpers/guarded-seed-write.js.map +1 -1
- package/src/lib/hooks/helpers/listen-confirmation.d.ts +54 -7
- package/src/lib/hooks/helpers/listen-confirmation.js +89 -12
- package/src/lib/hooks/helpers/listen-confirmation.js.map +1 -1
- package/src/lib/hooks/helpers/use-doc.js +6 -4
- package/src/lib/hooks/helpers/use-doc.js.map +1 -1
- package/src/lib/hooks/use-firestore-collection.d.ts +7 -0
- package/src/lib/hooks/use-firestore-collection.js +6 -4
- package/src/lib/hooks/use-firestore-collection.js.map +1 -1
- package/src/lib/hooks/use-firestore-doc.d.ts +7 -0
- package/src/lib/hooks/use-firestore-doc.js +6 -4
- package/src/lib/hooks/use-firestore-doc.js.map +1 -1
- package/src/lib/hooks/use-paged-collection.d.ts +7 -1
- package/src/lib/hooks/use-paged-collection.js.map +1 -1
- package/src/lib/hooks/use-sorted-paged-collection.js +3 -1
- package/src/lib/hooks/use-sorted-paged-collection.js.map +1 -1
- package/src/lib/testing/list-query-double.js +1 -0
- package/src/lib/testing/list-query-double.js.map +1 -1
|
@@ -20,7 +20,7 @@ import { useEffect, useRef, useState } from "react";
|
|
|
20
20
|
import { CONFIRMABLE_LISTEN_OPTIONS } from "./helpers/listen-options.js";
|
|
21
21
|
import { DENIAL_STREAK_TO_REPORT, denialLabelForQuery, reportFirestoreDenial, reportFirestoreServerRead, scheduleRefusedReopen, subscribeFirestoreSessionHeal } from "./firestore-denial-reporter.js";
|
|
22
22
|
import { armFirestoreStallWatch, noteFirestoreServerAnswer } from "./firebase/firestore-stall-recovery.js";
|
|
23
|
-
import { trackListenConfirmation } from "./helpers/listen-confirmation.js";
|
|
23
|
+
import { createListenHandle, trackListenConfirmation } from "./helpers/listen-confirmation.js";
|
|
24
24
|
const RETRY_DELAY_MS = 400;
|
|
25
25
|
const MAX_RETRIES = 5;
|
|
26
26
|
/**
|
|
@@ -44,6 +44,7 @@ const MAX_RETRIES = 5;
|
|
|
44
44
|
// from the server yet must not read as server-confirmed.
|
|
45
45
|
const [fromCache, setFromCache] = useState(true);
|
|
46
46
|
const [serverDenied, setServerDenied] = useState(false);
|
|
47
|
+
const [listen] = useState(createListenHandle);
|
|
47
48
|
const buildQueryRef = useRef(buildQuery);
|
|
48
49
|
buildQueryRef.current = buildQuery;
|
|
49
50
|
const idField = options.idField;
|
|
@@ -101,7 +102,7 @@ const MAX_RETRIES = 5;
|
|
|
101
102
|
* first server-confirmed snapshot, by an error (a refusal is not a
|
|
102
103
|
* stall) and by cleanup.
|
|
103
104
|
*/ const disarmStall = armFirestoreStallWatch(q.firestore);
|
|
104
|
-
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation();
|
|
105
|
+
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen);
|
|
105
106
|
/** Whether the rows on screen came from the cache (AGL-4120). */ let shownFromCache = false;
|
|
106
107
|
// Disappearance tracking (AGL-1196); inert unless opted in.
|
|
107
108
|
const seen = new Set();
|
|
@@ -312,7 +313,7 @@ const MAX_RETRIES = 5;
|
|
|
312
313
|
return ()=>{
|
|
313
314
|
cancelled = true;
|
|
314
315
|
disarmStall();
|
|
315
|
-
confirmation.
|
|
316
|
+
confirmation.close();
|
|
316
317
|
unsubscribeHeal();
|
|
317
318
|
if (timer) clearTimeout(timer);
|
|
318
319
|
cancelRefusedReopen == null ? void 0 : cancelRefusedReopen();
|
|
@@ -325,7 +326,8 @@ const MAX_RETRIES = 5;
|
|
|
325
326
|
status,
|
|
326
327
|
error,
|
|
327
328
|
fromCache,
|
|
328
|
-
serverDenied
|
|
329
|
+
serverDenied,
|
|
330
|
+
listen
|
|
329
331
|
};
|
|
330
332
|
}
|
|
331
333
|
export default useFirestoreCollection;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-collection.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'use client'\n\nimport {\n getDocsFromServer,\n onSnapshot,\n type DocumentData,\n type FirestoreError,\n type Query,\n type QueryDocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport { trackListenConfirmation } from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n\n/*\n * The cadence once a refusal streak has outlived the retry budget lives in\n * `firestore-denial-reporter.ts` (`scheduleRefusedReopen`), shared by all\n * three listener hooks. It starts at 2s while the fault could be the whole\n * session and at 60s once another listener's server answer proves the\n * session reads and this refusal is about the ref (AGL-1440), then grows\n * with the streak's age to a five-minute ceiling (AGL-2945). A hidden tab\n * sets no timer (AGL-2944). The tab becoming visible, the window regaining\n * focus and a heal broadcast (`subscribeFirestoreSessionHeal`) all reopen\n * at once.\n */\n\nexport type FirestoreCollectionStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreCollectionOptions {\n idField?: string\n /**\n * Confirm against the server when a document disappears from a NON-EMPTY\n * result, instead of trusting the live snapshot (AGL-1196).\n *\n * OPT-IN, and only worth setting for a query whose `where` reads a MUTABLE\n * field. Such a document can stop matching mid-session — a scope edit, an\n * un/republish — leave the query target, and get cached as a `noDocument`\n * tombstone at its own path, which is then served to every other reader of\n * that path including single-document reads (AGL-827/929).\n *\n * A query with no predicate, or one keyed on `documentId()`, cannot produce\n * this and must not pay for the extra read. Where the predicate can be\n * dropped entirely, drop it — that removes the mechanism rather than\n * repairing it after the fact (AGL-1190).\n */\n confirmDisappearances?: boolean\n}\n\nexport interface UseFirestoreCollectionResult<T> {\n data: T[]\n status: FirestoreCollectionStatus\n error: FirestoreError | undefined\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\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 * Kept after the flip rather than folded into `status`, because it says\n * something `status` does not: WHY the listen is failing. `status:\n * 'error'` covers every terminal error; this one counts `permission-denied`\n * alone, so it cannot fire offline, and a single server snapshot clears it.\n * A consumer asking \"is what I am rendering cache-only because the session\n * is refused\" wants this; one asking \"did the read fail at all\" wants\n * `status`.\n */\n serverDenied: boolean\n}\n\n/**\n * Collection-query counterpart to reactfire's `useFirestoreCollectionData`,\n * but backed by a raw `onSnapshot` listener with its own retry/backoff\n * instead of reactfire's cached Observable. That cache terminates forever on\n * its first error — a transient `permission-denied` right after sign-in\n * (before Firestore's own credential provider has attached the user's ID\n * token) permanently breaks the query for the rest of the session, even\n * across remounts. A fresh `onSnapshot` call each retry reopens a genuinely\n * new listener, so it recovers once the token has propagated (AGL-216/217).\n *\n * `buildQuery` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `Query` object itself.\n */\nexport function useFirestoreCollection<T = DocumentData>(\n buildQuery: () => Query<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreCollectionOptions = {},\n): UseFirestoreCollectionResult<T> {\n const [data, setData] = useState<T[]>([])\n const [status, setStatus] = useState<FirestoreCollectionStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const buildQueryRef = useRef(buildQuery)\n buildQueryRef.current = buildQuery\n const idField = options.idField\n const confirmDisappearances = options.confirmDisappearances\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on EVERY dep change, not only when the query goes null: when\n // the scope moves between two live queries (org A → org B, host A →\n // host B) the old rows would otherwise stay rendered until the new\n // snapshot arrives — the org-switch \"remnants\" bug (AGL-591). Same\n // hold-nothing-rather-than-show-the-wrong-org rule as useOrgHosts.\n setData([])\n setFromCache(true)\n setServerDenied(false)\n\n const q = buildQueryRef.current()\n if (!q) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Deliberately not `attempt`: that one is reset by any snapshot,\n * including a cached one, so under `persistentLocalCache` it never\n * reaches its budget and can never report anything.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the last thing the server did was refuse\n * (AGL-1066).\n *\n * This is what makes `status: 'error'` STICK. Every reopened listen emits\n * from the cache before it learns it is still refused, and an\n * unconditional `setStatus('success')` in the success handler would hand\n * the page back to `success` on that emission — so the surface would\n * oscillate error → success → error at the retry cadence, which is worse\n * to look at than either state. Only a snapshot the SERVER answered\n * clears this, for the same reason it is the only thing that clears\n * `deniedStreak`: a cached emission is not evidence about the server.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(q)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(q.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation()\n /** Whether the rows on screen came from the cache (AGL-4120). */\n let shownFromCache = false\n // Disappearance tracking (AGL-1196); inert unless opted in.\n const seen = new Set<string>()\n const confirmedGone = new Set<string>()\n\n const emit = (\n docs: QueryDocumentSnapshot<DocumentData>[],\n cached: boolean,\n changed: boolean,\n ) => {\n // A server-answered emission is the one thing that ends the refusal,\n // including the `getDocsFromServer` confirmation path below.\n if (!cached) terminal = false\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n setFromCache(cached)\n confirmation.report(cached, !cached && shownFromCache && changed)\n shownFromCache = cached\n setData(\n docs.map((docSnap) => {\n const value = { ...docSnap.data() } as Record<string, unknown>\n if (idField) value[idField] = docSnap.id\n return value as T\n }),\n )\n }\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n q,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n /**\n * Only a SERVER-answered snapshot refunds the retry budget — the\n * AGL-1066 flip, and the reason it took four commits to become\n * safe.\n *\n * Under `persistentLocalCache` a reopened listen emits from the\n * cache BEFORE it learns the server refused it. Refunding on that\n * emission handed the budget back every cycle, so `attempt` never\n * reached `MAX_RETRIES`, `status` could never become `'error'`, and\n * a dead session looked exactly like a healthy one on every\n * listener-backed page for as long as it stayed dead.\n *\n * Landing this alone would have been a regression, and the three\n * things that made it one are now in place:\n *\n * - the budget is 5 x 400ms, and the error branch used to stop\n * retrying for good, while the heal is an AGL-664 in-place\n * re-auth that takes as long as a human takes to type a\n * password. A resolved re-auth now broadcasts and this listener\n * reopens on it (`subscribeFirestoreSessionHeal` below), and a\n * refusal streak keeps a slow road back for a recovery nobody\n * announced (see the error branch);\n * - `status: 'error'` had to become STICKY, or the cached emission\n * that precedes each refusal would flip it straight back — see\n * `terminal` above;\n * - the surfaces that BLANK on `error` had to learn the\n * difference between \"never had data\" and \"have data, the server\n * refused\". They read `hasEmitted` now, so the besigner canvas\n * and the host setup Theme tab keep rendering across a refusal\n * instead of collapsing to \"Not found\".\n *\n * The withholding is keyed on a REFUSAL having happened, not on the\n * emission being cached, and that is load-bearing: offline stays\n * exactly as inert as it was. A lost network yields `unavailable`\n * (when it yields an error callback at all), which never enters\n * `deniedStreak`, so a cached emission still refunds the budget and\n * an offline listener still never goes terminal. The cache exists\n * for offline; this must not change what happens there.\n */\n // Only the SERVER answering is evidence the session can read.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(q.firestore)\n attempt = 0\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — so this is not the AGL-1066 fault and the budget is\n // refunded exactly as it always was.\n attempt = 0\n }\n\n // Only the values count: a metadata-only tick is not a change.\n const changed = snapshot.docChanges?.().length > 0\n\n if (confirmDisappearances) {\n const present = new Set(snapshot.docs.map((d) => d.id))\n const vanished = [...seen].filter(\n (id) => !present.has(id) && !confirmedGone.has(id),\n )\n if (vanished.length) {\n // A fresh (non-resumed) read ignores the resume token, returns\n // the true set and rewrites the cache, dropping any tombstone.\n getDocsFromServer(q)\n .then((fresh) => {\n if (cancelled) return\n const freshIds = new Set(fresh.docs.map((d) => d.id))\n // Only an absence the SERVER agrees with is real. One that\n // came back was a tombstone and must stay eligible to heal\n // if it vanishes again.\n vanished.forEach((id) => {\n if (!freshIds.has(id)) confirmedGone.add(id)\n })\n freshIds.forEach((id) => seen.add(id))\n // `getDocsFromServer` is server-confirmed by definition.\n emit(fresh.docs, false, true)\n })\n .catch(() => {\n // Couldn't confirm: show the live result rather than an\n // error. A possibly-short list beats an empty one.\n if (!cancelled) {\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n }\n })\n return\n }\n snapshot.docs.forEach((d) => seen.add(d.id))\n }\n\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n // When the streak began — the reference point that lets\n // `refusedRetryDelayMs` ask whether the session has read from\n // the server SINCE this listen started being refused (AGL-1440).\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n /**\n * A refusal streak keeps a slow road back (AGL-1066).\n *\n * Before the flip this listener reopened forever, which is also\n * what HEALED it — a token that attached late, an App Check\n * hiccup, one of the AGL-1143 transient token-layer denials.\n * None of those broadcast a heal, because none of them involved\n * a re-auth the console asked for, so stopping here would leave\n * every listen in the console terminal until the user reloaded.\n * The status is corrected; the recovery is not taken away.\n *\n * Any OTHER terminal error still stops exactly as before — this\n * is deliberately keyed on the refusal streak, not on `attempt`.\n * How slow the road is depends on whether the refusal looks like\n * the session or the ref (AGL-1440) and on how long it has\n * lasted (AGL-2945), and a hidden tab waits to be looked at\n * (AGL-2944) — see `scheduleRefusedReopen`.\n */\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * The session came back — reopen NOW rather than on the next tick of a\n * cadence tuned for a session that has not (AGL-1066).\n *\n * Gated on this listener actually being refused. A healthy listener has\n * an open subscription and nothing to recover, so it must ignore the\n * broadcast entirely: without this gate a heal would tear down and\n * reopen every listen in the console at once, which is a listener storm\n * dressed up as a fix.\n *\n * What is refunded is `attempt` — the retry BUDGET, which was spent on a\n * fault that is now over. `deniedStreak` is deliberately left alone: it\n * is evidence about the server, and only the server answering may clear\n * it. So `serverDenied` stays true across the heal and goes false on the\n * snapshot that actually proves the read works, and a heal that turns\n * out to be wishful thinking falls straight back to the slow cadence\n * instead of resuming a 400ms storm.\n *\n * `denialReported` IS reset: the outage ended here. If reads are still\n * refused afterwards that is a new one, and it has to be able to raise\n * the AGL-1063 banner again.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.release()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, fromCache, serverDenied }\n}\n\nexport default useFirestoreCollection\n"],"names":["getDocsFromServer","onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","useFirestoreCollection","buildQuery","deps","options","data","setData","status","setStatus","error","setError","undefined","fromCache","setFromCache","serverDenied","setServerDenied","buildQueryRef","current","idField","confirmDisappearances","q","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","shownFromCache","seen","Set","confirmedGone","emit","docs","cached","changed","report","map","docSnap","value","id","subscribe","snapshot","metadata","docChanges","length","present","d","vanished","filter","has","then","fresh","freshIds","forEach","add","catch","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,iBAAiB,EACjBC,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAA6B,QAAO;AACxE,SAASC,0BAA0B,QAAQ,8BAA0B;AACrE,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,qBAAq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gBAClE,IAAIyC,CAAAA,uBAAAA,IAAKE,IAAI,MAAK,qBAAqB;oBACrCvC,gBAAgB;oBAChB,wDAAwD;oBACxD,8DAA8D;oBAC9D,iEAAiE;oBACjE,IAAIA,iBAAiB,GAAGC,wBAAwBuC,KAAKC,GAAG;oBACxD,IAAIzC,gBAAgBpC,yBAAyB;wBAC3CyB,gBAAgB;wBAChB,IAAI,CAACa,gBAAgB;4BACnBA,iBAAiB;4BACjBpC,sBAAsBsC;wBACxB;oBACF;gBACF;gBACA,IAAIL,UAAUzB,aAAa;oBACzByB,WAAW;oBACX,IAAIC,eAAe1B,aAAa;wBAC9BwB,sBAAsB9B,sBACpBqD,WACApB;oBAEJ,OAAO;wBACLJ,QAAQ6C,WAAWrB,WAAWhD;oBAChC;gBACF,OAAO;oBACL8B,WAAW;oBACXrB,UAAU;oBACVE,SAASqD;oBACT;;;;;;;;;;;;;;;;;aAiBC,GACD,IAAIrC,eAAe1B,aAAa;wBAC9BwB,sBAAsB9B,sBACpBqD,WACApB;oBAEJ;gBACF;YACF;QAEJ;QACAoB;QAEA;;;;;;;;;;;;;;;;;;;;;KAqBC,GACD,MAAMsB,kBAAkB1E,8BAA8B;YACpD,IAAI0B,aAAaK,iBAAiB,GAAG;YACrC,IAAIH,OAAO;gBACT+C,aAAa/C;gBACbA,QAAQ;YACV;YACAC,uCAAAA;YACAA,sBAAsB;YACtBF,+BAAAA;YACAG,UAAU;YACVG,iBAAiB;YACjBmB;QACF;QAEA,OAAO;YACL1B,YAAY;YACZU;YACAE,aAAa+B,OAAO;YACpBK;YACA,IAAI9C,OAAO+C,aAAa/C;YACxBC,uCAAAA;YACAF,+BAAAA;QACF;IACA,uDAAuD;IACzD,GAAGnB;IAEH,OAAO;QAAEE;QAAME;QAAQE;QAAOG;QAAWE;IAAa;AACxD;AAEA,eAAeb,uBAAsB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-collection.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'use client'\n\nimport {\n getDocsFromServer,\n onSnapshot,\n type DocumentData,\n type FirestoreError,\n type Query,\n type QueryDocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport {\n createListenHandle,\n trackListenConfirmation,\n type ListenHandle,\n} from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n\n/*\n * The cadence once a refusal streak has outlived the retry budget lives in\n * `firestore-denial-reporter.ts` (`scheduleRefusedReopen`), shared by all\n * three listener hooks. It starts at 2s while the fault could be the whole\n * session and at 60s once another listener's server answer proves the\n * session reads and this refusal is about the ref (AGL-1440), then grows\n * with the streak's age to a five-minute ceiling (AGL-2945). A hidden tab\n * sets no timer (AGL-2944). The tab becoming visible, the window regaining\n * focus and a heal broadcast (`subscribeFirestoreSessionHeal`) all reopen\n * at once.\n */\n\nexport type FirestoreCollectionStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreCollectionOptions {\n idField?: string\n /**\n * Confirm against the server when a document disappears from a NON-EMPTY\n * result, instead of trusting the live snapshot (AGL-1196).\n *\n * OPT-IN, and only worth setting for a query whose `where` reads a MUTABLE\n * field. Such a document can stop matching mid-session — a scope edit, an\n * un/republish — leave the query target, and get cached as a `noDocument`\n * tombstone at its own path, which is then served to every other reader of\n * that path including single-document reads (AGL-827/929).\n *\n * A query with no predicate, or one keyed on `documentId()`, cannot produce\n * this and must not pay for the extra read. Where the predicate can be\n * dropped entirely, drop it — that removes the mechanism rather than\n * repairing it after the fact (AGL-1190).\n */\n confirmDisappearances?: boolean\n}\n\nexport interface UseFirestoreCollectionResult<T> {\n data: T[]\n status: FirestoreCollectionStatus\n error: FirestoreError | undefined\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\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 * Kept after the flip rather than folded into `status`, because it says\n * something `status` does not: WHY the listen is failing. `status:\n * 'error'` covers every terminal error; this one counts `permission-denied`\n * alone, so it cannot fire offline, and a single server snapshot clears it.\n * A consumer asking \"is what I am rendering cache-only because the session\n * is refused\" wants this; one asking \"did the read fail at all\" wants\n * `status`.\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/**\n * Collection-query counterpart to reactfire's `useFirestoreCollectionData`,\n * but backed by a raw `onSnapshot` listener with its own retry/backoff\n * instead of reactfire's cached Observable. That cache terminates forever on\n * its first error — a transient `permission-denied` right after sign-in\n * (before Firestore's own credential provider has attached the user's ID\n * token) permanently breaks the query for the rest of the session, even\n * across remounts. A fresh `onSnapshot` call each retry reopens a genuinely\n * new listener, so it recovers once the token has propagated (AGL-216/217).\n *\n * `buildQuery` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `Query` object itself.\n */\nexport function useFirestoreCollection<T = DocumentData>(\n buildQuery: () => Query<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreCollectionOptions = {},\n): UseFirestoreCollectionResult<T> {\n const [data, setData] = useState<T[]>([])\n const [status, setStatus] = useState<FirestoreCollectionStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const buildQueryRef = useRef(buildQuery)\n buildQueryRef.current = buildQuery\n const idField = options.idField\n const confirmDisappearances = options.confirmDisappearances\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on EVERY dep change, not only when the query goes null: when\n // the scope moves between two live queries (org A → org B, host A →\n // host B) the old rows would otherwise stay rendered until the new\n // snapshot arrives — the org-switch \"remnants\" bug (AGL-591). Same\n // hold-nothing-rather-than-show-the-wrong-org rule as useOrgHosts.\n setData([])\n setFromCache(true)\n setServerDenied(false)\n\n const q = buildQueryRef.current()\n if (!q) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Deliberately not `attempt`: that one is reset by any snapshot,\n * including a cached one, so under `persistentLocalCache` it never\n * reaches its budget and can never report anything.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the last thing the server did was refuse\n * (AGL-1066).\n *\n * This is what makes `status: 'error'` STICK. Every reopened listen emits\n * from the cache before it learns it is still refused, and an\n * unconditional `setStatus('success')` in the success handler would hand\n * the page back to `success` on that emission — so the surface would\n * oscillate error → success → error at the retry cadence, which is worse\n * to look at than either state. Only a snapshot the SERVER answered\n * clears this, for the same reason it is the only thing that clears\n * `deniedStreak`: a cached emission is not evidence about the server.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(q)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(q.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen)\n /** Whether the rows on screen came from the cache (AGL-4120). */\n let shownFromCache = false\n // Disappearance tracking (AGL-1196); inert unless opted in.\n const seen = new Set<string>()\n const confirmedGone = new Set<string>()\n\n const emit = (\n docs: QueryDocumentSnapshot<DocumentData>[],\n cached: boolean,\n changed: boolean,\n ) => {\n // A server-answered emission is the one thing that ends the refusal,\n // including the `getDocsFromServer` confirmation path below.\n if (!cached) terminal = false\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n setFromCache(cached)\n confirmation.report(cached, !cached && shownFromCache && changed)\n shownFromCache = cached\n setData(\n docs.map((docSnap) => {\n const value = { ...docSnap.data() } as Record<string, unknown>\n if (idField) value[idField] = docSnap.id\n return value as T\n }),\n )\n }\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n q,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n /**\n * Only a SERVER-answered snapshot refunds the retry budget — the\n * AGL-1066 flip, and the reason it took four commits to become\n * safe.\n *\n * Under `persistentLocalCache` a reopened listen emits from the\n * cache BEFORE it learns the server refused it. Refunding on that\n * emission handed the budget back every cycle, so `attempt` never\n * reached `MAX_RETRIES`, `status` could never become `'error'`, and\n * a dead session looked exactly like a healthy one on every\n * listener-backed page for as long as it stayed dead.\n *\n * Landing this alone would have been a regression, and the three\n * things that made it one are now in place:\n *\n * - the budget is 5 x 400ms, and the error branch used to stop\n * retrying for good, while the heal is an AGL-664 in-place\n * re-auth that takes as long as a human takes to type a\n * password. A resolved re-auth now broadcasts and this listener\n * reopens on it (`subscribeFirestoreSessionHeal` below), and a\n * refusal streak keeps a slow road back for a recovery nobody\n * announced (see the error branch);\n * - `status: 'error'` had to become STICKY, or the cached emission\n * that precedes each refusal would flip it straight back — see\n * `terminal` above;\n * - the surfaces that BLANK on `error` had to learn the\n * difference between \"never had data\" and \"have data, the server\n * refused\". They read `hasEmitted` now, so the besigner canvas\n * and the host setup Theme tab keep rendering across a refusal\n * instead of collapsing to \"Not found\".\n *\n * The withholding is keyed on a REFUSAL having happened, not on the\n * emission being cached, and that is load-bearing: offline stays\n * exactly as inert as it was. A lost network yields `unavailable`\n * (when it yields an error callback at all), which never enters\n * `deniedStreak`, so a cached emission still refunds the budget and\n * an offline listener still never goes terminal. The cache exists\n * for offline; this must not change what happens there.\n */\n // Only the SERVER answering is evidence the session can read.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(q.firestore)\n attempt = 0\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — so this is not the AGL-1066 fault and the budget is\n // refunded exactly as it always was.\n attempt = 0\n }\n\n // Only the values count: a metadata-only tick is not a change.\n const changed = snapshot.docChanges?.().length > 0\n\n if (confirmDisappearances) {\n const present = new Set(snapshot.docs.map((d) => d.id))\n const vanished = [...seen].filter(\n (id) => !present.has(id) && !confirmedGone.has(id),\n )\n if (vanished.length) {\n // A fresh (non-resumed) read ignores the resume token, returns\n // the true set and rewrites the cache, dropping any tombstone.\n getDocsFromServer(q)\n .then((fresh) => {\n if (cancelled) return\n const freshIds = new Set(fresh.docs.map((d) => d.id))\n // Only an absence the SERVER agrees with is real. One that\n // came back was a tombstone and must stay eligible to heal\n // if it vanishes again.\n vanished.forEach((id) => {\n if (!freshIds.has(id)) confirmedGone.add(id)\n })\n freshIds.forEach((id) => seen.add(id))\n // `getDocsFromServer` is server-confirmed by definition.\n emit(fresh.docs, false, true)\n })\n .catch(() => {\n // Couldn't confirm: show the live result rather than an\n // error. A possibly-short list beats an empty one.\n if (!cancelled) {\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n }\n })\n return\n }\n snapshot.docs.forEach((d) => seen.add(d.id))\n }\n\n emit(snapshot.docs, snapshot.metadata.fromCache, changed)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n // When the streak began — the reference point that lets\n // `refusedRetryDelayMs` ask whether the session has read from\n // the server SINCE this listen started being refused (AGL-1440).\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n /**\n * A refusal streak keeps a slow road back (AGL-1066).\n *\n * Before the flip this listener reopened forever, which is also\n * what HEALED it — a token that attached late, an App Check\n * hiccup, one of the AGL-1143 transient token-layer denials.\n * None of those broadcast a heal, because none of them involved\n * a re-auth the console asked for, so stopping here would leave\n * every listen in the console terminal until the user reloaded.\n * The status is corrected; the recovery is not taken away.\n *\n * Any OTHER terminal error still stops exactly as before — this\n * is deliberately keyed on the refusal streak, not on `attempt`.\n * How slow the road is depends on whether the refusal looks like\n * the session or the ref (AGL-1440) and on how long it has\n * lasted (AGL-2945), and a hidden tab waits to be looked at\n * (AGL-2944) — see `scheduleRefusedReopen`.\n */\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * The session came back — reopen NOW rather than on the next tick of a\n * cadence tuned for a session that has not (AGL-1066).\n *\n * Gated on this listener actually being refused. A healthy listener has\n * an open subscription and nothing to recover, so it must ignore the\n * broadcast entirely: without this gate a heal would tear down and\n * reopen every listen in the console at once, which is a listener storm\n * dressed up as a fix.\n *\n * What is refunded is `attempt` — the retry BUDGET, which was spent on a\n * fault that is now over. `deniedStreak` is deliberately left alone: it\n * is evidence about the server, and only the server answering may clear\n * it. So `serverDenied` stays true across the heal and goes false on the\n * snapshot that actually proves the read works, and a heal that turns\n * out to be wishful thinking falls straight back to the slow cadence\n * instead of resuming a 400ms storm.\n *\n * `denialReported` IS reset: the outage ended here. If reads are still\n * refused afterwards that is a new one, and it has to be able to raise\n * the AGL-1063 banner again.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, fromCache, serverDenied, listen }\n}\n\nexport default useFirestoreCollection\n"],"names":["getDocsFromServer","onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","createListenHandle","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","useFirestoreCollection","buildQuery","deps","options","data","setData","status","setStatus","error","setError","undefined","fromCache","setFromCache","serverDenied","setServerDenied","listen","buildQueryRef","current","idField","confirmDisappearances","q","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","shownFromCache","seen","Set","confirmedGone","emit","docs","cached","changed","report","map","docSnap","value","id","subscribe","snapshot","metadata","docChanges","length","present","d","vanished","filter","has","then","fresh","freshIds","forEach","add","catch","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,iBAAiB,EACjBC,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAA6B,QAAO;AACxE,SAASC,0BAA0B,QAAQ,8BAA0B;AACrE,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,qBAAqB,EACrBC,yBAAyB,EACzBC,qBAAqB,EACrBC,6BAA6B,QACxB,iCAA6B;AACpC,SACEC,sBAAsB,EACtBC,yBAAyB,QACpB,yCAAqC;AAC5C,SACEC,kBAAkB,EAClBC,uBAAuB,QAElB,mCAA+B;AAEtC,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AAmEpB;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,uBACdC,UAAwD,EACxDC,IAAoB,EACpBC,UAAyC,CAAC,CAAC;IAE3C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AACc,gBAAgB;4BACnBA,iBAAiB;4BACjBtC,sBAAsBwC;wBACxB;oBACF;gBACF;gBACA,IAAIL,UAAU1B,aAAa;oBACzB0B,WAAW;oBACX,IAAIC,eAAe3B,aAAa;wBAC9ByB,sBAAsBhC,sBACpBuD,WACApB;oBAEJ,OAAO;wBACLJ,QAAQ6C,WAAWrB,WAAWjD;oBAChC;gBACF,OAAO;oBACL+B,WAAW;oBACXtB,UAAU;oBACVE,SAASsD;oBACT;;;;;;;;;;;;;;;;;aAiBC,GACD,IAAIrC,eAAe3B,aAAa;wBAC9ByB,sBAAsBhC,sBACpBuD,WACApB;oBAEJ;gBACF;YACF;QAEJ;QACAoB;QAEA;;;;;;;;;;;;;;;;;;;;;KAqBC,GACD,MAAMsB,kBAAkB5E,8BAA8B;YACpD,IAAI4B,aAAaK,iBAAiB,GAAG;YACrC,IAAIH,OAAO;gBACT+C,aAAa/C;gBACbA,QAAQ;YACV;YACAC,uCAAAA;YACAA,sBAAsB;YACtBF,+BAAAA;YACAG,UAAU;YACVG,iBAAiB;YACjBmB;QACF;QAEA,OAAO;YACL1B,YAAY;YACZU;YACAE,aAAasC,KAAK;YAClBF;YACA,IAAI9C,OAAO+C,aAAa/C;YACxBC,uCAAAA;YACAF,+BAAAA;QACF;IACA,uDAAuD;IACzD,GAAGpB;IAEH,OAAO;QAAEE;QAAME;QAAQE;QAAOG;QAAWE;QAAcE;IAAO;AAChE;AAEA,eAAef,uBAAsB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type DocumentData, type DocumentReference, type FirestoreError } from 'firebase/firestore';
|
|
2
2
|
import { type DependencyList } from 'react';
|
|
3
|
+
import { type ListenHandle } from './helpers/listen-confirmation';
|
|
3
4
|
export type FirestoreDocStatus = 'loading' | 'success' | 'error';
|
|
4
5
|
export interface UseFirestoreDocOptions {
|
|
5
6
|
idField?: string;
|
|
@@ -27,6 +28,12 @@ export interface UseFirestoreDocResult<T> {
|
|
|
27
28
|
* `UseFirestoreCollectionResult.serverDenied`.
|
|
28
29
|
*/
|
|
29
30
|
serverDenied: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* This hook's listener, for a guarded save seeded from `data` to wait on
|
|
33
|
+
* alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of
|
|
34
|
+
* the hook.
|
|
35
|
+
*/
|
|
36
|
+
listen: ListenHandle;
|
|
30
37
|
}
|
|
31
38
|
/** Where a document read stands: still loading, failed, answered with nothing, or answered. */
|
|
32
39
|
export type FirestoreDocPhase = 'loading' | 'error' | 'missing' | 'ready';
|
|
@@ -20,7 +20,7 @@ import { useEffect, useRef, useState } from "react";
|
|
|
20
20
|
import { CONFIRMABLE_LISTEN_OPTIONS } from "./helpers/listen-options.js";
|
|
21
21
|
import { DENIAL_STREAK_TO_REPORT, denialLabelForQuery, reportFirestoreDenial, reportFirestoreServerRead, scheduleRefusedReopen, subscribeFirestoreSessionHeal } from "./firestore-denial-reporter.js";
|
|
22
22
|
import { armFirestoreStallWatch, noteFirestoreServerAnswer } from "./firebase/firestore-stall-recovery.js";
|
|
23
|
-
import { sameDocument, trackListenConfirmation } from "./helpers/listen-confirmation.js";
|
|
23
|
+
import { createListenHandle, sameDocument, trackListenConfirmation } from "./helpers/listen-confirmation.js";
|
|
24
24
|
const RETRY_DELAY_MS = 400;
|
|
25
25
|
const MAX_RETRIES = 5;
|
|
26
26
|
/**
|
|
@@ -52,6 +52,7 @@ const MAX_RETRIES = 5;
|
|
|
52
52
|
// from the server yet must not read as server-confirmed.
|
|
53
53
|
const [fromCache, setFromCache] = useState(true);
|
|
54
54
|
const [serverDenied, setServerDenied] = useState(false);
|
|
55
|
+
const [listen] = useState(createListenHandle);
|
|
55
56
|
const buildRefRef = useRef(buildRef);
|
|
56
57
|
buildRefRef.current = buildRef;
|
|
57
58
|
const idField = options.idField;
|
|
@@ -96,7 +97,7 @@ const MAX_RETRIES = 5;
|
|
|
96
97
|
* first server-confirmed snapshot, by an error (a refusal is not a
|
|
97
98
|
* stall) and by cleanup.
|
|
98
99
|
*/ const disarmStall = armFirestoreStallWatch(ref.firestore);
|
|
99
|
-
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation();
|
|
100
|
+
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen);
|
|
100
101
|
/** The cached snapshot on screen, while one is (AGL-4120). */ let shownFromCache = null;
|
|
101
102
|
const subscribe = ()=>{
|
|
102
103
|
unsubscribe = onSnapshot(ref, // Without this the cache→server confirmation is never delivered and
|
|
@@ -203,7 +204,7 @@ const MAX_RETRIES = 5;
|
|
|
203
204
|
return ()=>{
|
|
204
205
|
cancelled = true;
|
|
205
206
|
disarmStall();
|
|
206
|
-
confirmation.
|
|
207
|
+
confirmation.close();
|
|
207
208
|
unsubscribeHeal();
|
|
208
209
|
if (timer) clearTimeout(timer);
|
|
209
210
|
cancelRefusedReopen == null ? void 0 : cancelRefusedReopen();
|
|
@@ -217,7 +218,8 @@ const MAX_RETRIES = 5;
|
|
|
217
218
|
error,
|
|
218
219
|
hasPendingWrites,
|
|
219
220
|
fromCache,
|
|
220
|
-
serverDenied
|
|
221
|
+
serverDenied,
|
|
222
|
+
listen
|
|
221
223
|
};
|
|
222
224
|
}
|
|
223
225
|
export default useFirestoreDoc;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-doc.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'use client'\n\nimport {\n onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n type FirestoreError,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport { sameDocument, trackListenConfirmation } from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\nexport type FirestoreDocStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreDocOptions {\n idField?: string\n}\n\nexport interface UseFirestoreDocResult<T> {\n data: T | undefined\n status: FirestoreDocStatus\n error: FirestoreError | undefined\n /**\n * `data` still carries writes this client made that the server has NOT\n * acknowledged. Carried rather than dropped for the same reason as\n * `ObservableStatus.hasPendingWrites` — see that comment (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\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) — the reason behind an\n * `error`, not a duplicate of it. See\n * `UseFirestoreCollectionResult.serverDenied`.\n */\n serverDenied: boolean\n}\n\n/** Where a document read stands: still loading, failed, answered with nothing, or answered. */\nexport type FirestoreDocPhase = 'loading' | 'error' | 'missing' | 'ready'\n\n/**\n * Where a {@link useFirestoreDoc} read stands (AGL-4089), for a page that\n * must not state a document's empty values as facts while it loads. A\n * document is only `missing` once the SERVER says so: the cache answers\n * \"missing\" first for a document it has never held, and while another tab\n * holds the shared cache that answer can stand for half a minute.\n */\nexport function firestoreDocPhase(\n read: Pick<UseFirestoreDocResult<unknown>, 'data' | 'status' | 'fromCache'>,\n): FirestoreDocPhase {\n if (read.data) return 'ready'\n if (read.status === 'error') return 'error'\n return read.status === 'loading' || read.fromCache ? 'loading' : 'missing'\n}\n\n/**\n * Single-document counterpart to `useFirestoreCollection` — see that hook's\n * doc comment for why this exists instead of reactfire's\n * `useFirestoreDocData` (AGL-216/217).\n *\n * `buildRef` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `DocumentReference`\n * object itself.\n */\nexport function useFirestoreDoc<T = DocumentData>(\n buildRef: () => DocumentReference<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreDocOptions = {},\n): UseFirestoreDocResult<T> {\n const [data, setData] = useState<T | undefined>(undefined)\n const [status, setStatus] = useState<FirestoreDocStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const buildRefRef = useRef(buildRef)\n buildRefRef.current = buildRef\n const idField = options.idField\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on every dep change (AGL-591): a scope move between two live\n // refs must not keep showing the previous doc until the new snapshot\n // arrives. Mirrors use-firestore-collection.\n setData(undefined)\n setHasPendingWrites(false)\n setFromCache(true)\n setServerDenied(false)\n\n const ref = buildRefRef.current()\n if (!ref) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n // Refusals since the last SERVER snapshot (AGL-1066) — see the note on\n // `DENIAL_STREAK_TO_REPORT` for why this is not `attempt`.\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(ref)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(ref.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation()\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n setFromCache(snapshot.metadata.fromCache)\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n // Only the SERVER answering is evidence the session can read — and\n // the only thing that refunds the retry budget (AGL-1066). See the\n // long note on the same gate in `use-firestore-collection`.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(ref.firestore)\n attempt = 0\n terminal = false\n setStatus('success')\n setError(undefined)\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!snapshot.exists()) {\n setData(undefined)\n return\n }\n const value = { ...snapshot.data() } as Record<string, unknown>\n if (idField) value[idField] = snapshot.id\n setData(value as T)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n // Reopen when the session heals — see the long note on the same\n // subscription in `use-firestore-collection` (AGL-1066). Gated on this\n // listen actually being refused, so a healthy one ignores the broadcast.\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.release()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, hasPendingWrites, fromCache, serverDenied }\n}\n\nexport default useFirestoreDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","sameDocument","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","firestoreDocPhase","read","data","status","fromCache","useFirestoreDoc","buildRef","deps","options","setData","undefined","setStatus","error","setError","hasPendingWrites","setHasPendingWrites","setFromCache","serverDenied","setServerDenied","buildRefRef","current","idField","ref","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","shownFromCache","subscribe","snapshot","metadata","report","exists","value","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAA6B,QAAO;AACxE,SAASC,0BAA0B,QAAQ,8BAA0B;AACrE,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,qBAAqB,EACrBC,yBA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ACLd,YAAY;YACZU;YACAE,aAAaU,OAAO;YACpBK;YACA,IAAIzB,OAAO0B,aAAa1B;YACxBC,uCAAAA;YACAF,+BAAAA;QACF;IACA,uDAAuD;IACzD,GAAGjB;IAEH,OAAO;QAAEL;QAAMC;QAAQS;QAAOE;QAAkBV;QAAWa;IAAa;AAC1E;AAEA,eAAeZ,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-firestore-doc.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'use client'\n\nimport {\n onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n type FirestoreError,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState, type DependencyList } from 'react'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './helpers/listen-options'\nimport {\n DENIAL_STREAK_TO_REPORT,\n denialLabelForQuery,\n reportFirestoreDenial,\n reportFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from './firestore-denial-reporter'\nimport {\n armFirestoreStallWatch,\n noteFirestoreServerAnswer,\n} from './firebase/firestore-stall-recovery'\nimport {\n createListenHandle,\n sameDocument,\n trackListenConfirmation,\n type ListenHandle,\n} from './helpers/listen-confirmation'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\nexport type FirestoreDocStatus = 'loading' | 'success' | 'error'\n\nexport interface UseFirestoreDocOptions {\n idField?: string\n}\n\nexport interface UseFirestoreDocResult<T> {\n data: T | undefined\n status: FirestoreDocStatus\n error: FirestoreError | undefined\n /**\n * `data` still carries writes this client made that the server has NOT\n * acknowledged. Carried rather than dropped for the same reason as\n * `ObservableStatus.hasPendingWrites` — see that comment (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * `data` came from the local cache and the server has not confirmed it\n * (AGL-1066). See `ObservableStatus.fromCache` for why this matters and\n * why it is the signal to reach for rather than `staleSession`.\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) — the reason behind an\n * `error`, not a duplicate of it. See\n * `UseFirestoreCollectionResult.serverDenied`.\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/** Where a document read stands: still loading, failed, answered with nothing, or answered. */\nexport type FirestoreDocPhase = 'loading' | 'error' | 'missing' | 'ready'\n\n/**\n * Where a {@link useFirestoreDoc} read stands (AGL-4089), for a page that\n * must not state a document's empty values as facts while it loads. A\n * document is only `missing` once the SERVER says so: the cache answers\n * \"missing\" first for a document it has never held, and while another tab\n * holds the shared cache that answer can stand for half a minute.\n */\nexport function firestoreDocPhase(\n read: Pick<UseFirestoreDocResult<unknown>, 'data' | 'status' | 'fromCache'>,\n): FirestoreDocPhase {\n if (read.data) return 'ready'\n if (read.status === 'error') return 'error'\n return read.status === 'loading' || read.fromCache ? 'loading' : 'missing'\n}\n\n/**\n * Single-document counterpart to `useFirestoreCollection` — see that hook's\n * doc comment for why this exists instead of reactfire's\n * `useFirestoreDocData` (AGL-216/217).\n *\n * `buildRef` is re-invoked from `deps` the same way a `useEffect`/`useMemo`\n * callback would be — pass the same primitive values (ids, uid, firestore)\n * you'd put in a `useMemo` dependency array, not the `DocumentReference`\n * object itself.\n */\nexport function useFirestoreDoc<T = DocumentData>(\n buildRef: () => DocumentReference<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UseFirestoreDocOptions = {},\n): UseFirestoreDocResult<T> {\n const [data, setData] = useState<T | undefined>(undefined)\n const [status, setStatus] = useState<FirestoreDocStatus>('loading')\n const [error, setError] = useState<FirestoreError | undefined>(undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise: a hook that has not heard\n // from the server yet must not read as server-confirmed.\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const buildRefRef = useRef(buildRef)\n buildRefRef.current = buildRef\n const idField = options.idField\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n // Clear on every dep change (AGL-591): a scope move between two live\n // refs must not keep showing the previous doc until the new snapshot\n // arrives. Mirrors use-firestore-collection.\n setData(undefined)\n setHasPendingWrites(false)\n setFromCache(true)\n setServerDenied(false)\n\n const ref = buildRefRef.current()\n if (!ref) {\n return\n }\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n // Refusals since the last SERVER snapshot (AGL-1066) — see the note on\n // `DENIAL_STREAK_TO_REPORT` for why this is not `attempt`.\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n let denialReported = false\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n const denialLabel = denialLabelForQuery(ref)\n /**\n * A listen the server has not confirmed within `FIRESTORE_STALL_MS`,\n * while the browser is online and the tab is visible, is the multi-tab\n * wedge (AGL-3373): no tab is syncing, so an empty cache raises no first\n * snapshot at all and a warm one never confirms. The client is asked to\n * recover — a network cycle that forces the lease election — and this\n * listener then hears from the server like any other. Disarmed by the\n * first server-confirmed snapshot, by an error (a refusal is not a\n * stall) and by cleanup.\n */\n const disarmStall = armFirestoreStallWatch(ref.firestore)\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen)\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n setFromCache(snapshot.metadata.fromCache)\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n // Only the SERVER answering is evidence the session can read — and\n // the only thing that refunds the retry budget (AGL-1066). See the\n // long note on the same gate in `use-firestore-collection`.\n if (!snapshot.metadata.fromCache) {\n disarmStall()\n noteFirestoreServerAnswer(ref.firestore)\n attempt = 0\n terminal = false\n setStatus('success')\n setError(undefined)\n deniedStreak = 0\n denialReported = false\n setServerDenied(false)\n // Proof the session can read — stronger than any accumulated\n // denial, and what stops a scoped collaborator's by-design\n // denials from ever adding up to a re-auth prompt.\n reportFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!snapshot.exists()) {\n setData(undefined)\n return\n }\n const value = { ...snapshot.data() } as Record<string, unknown>\n if (idField) value[idField] = snapshot.id\n setData(value as T)\n },\n (err) => {\n if (cancelled) return\n disarmStall()\n confirmation.release()\n unsubscribe?.()\n // Say so once per outage, and only for a refusal — a lost network\n // produces no error callback at all, so this cannot fire offline.\n if (err?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) {\n setServerDenied(true)\n if (!denialReported) {\n denialReported = true\n reportFirestoreDenial(denialLabel)\n }\n }\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n // Reopen when the session heals — see the long note on the same\n // subscription in `use-firestore-collection` (AGL-1066). Gated on this\n // listen actually being refused, so a healthy one ignores the broadcast.\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n denialReported = false\n subscribe()\n })\n\n return () => {\n cancelled = true\n disarmStall()\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n\n return { data, status, error, hasPendingWrites, fromCache, serverDenied, listen }\n}\n\nexport default useFirestoreDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","CONFIRMABLE_LISTEN_OPTIONS","DENIAL_STREAK_TO_REPORT","denialLabelForQuery","reportFirestoreDenial","reportFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","armFirestoreStallWatch","noteFirestoreServerAnswer","createListenHandle","sameDocument","trackListenConfirmation","RETRY_DELAY_MS","MAX_RETRIES","firestoreDocPhase","read","data","status","fromCache","useFirestoreDoc","buildRef","deps","options","setData","undefined","setStatus","error","setError","hasPendingWrites","setHasPendingWrites","setFromCache","serverDenied","setServerDenied","listen","buildRefRef","current","idField","ref","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","denialReported","terminal","denialLabel","disarmStall","firestore","confirmation","shownFromCache","subscribe","snapshot","metadata","report","exists","value","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SACEA,UAAU,QAKL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAA6B,QAAO;AACxE,SAASC,0BAA0B,QAAQ,8BAA0B;AACrE,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,qBAAqB,EACrBC,yBAAyB,EACzBC,qBAAqB,EACrBC,6BAA6B,QACxB,iCAA6B;AACpC,SACEC,sBAAsB,EACtBC,yBAAyB,QACpB,yCAAqC;AAC5C,SACEC,kBAAkB,EAClBC,YAAY,EACZC,uBAAuB,QAElB,mCAA+B;AAEtC,MAAMC,iBAAiB;AACvB,MAAMC,cAAc;AA4CpB;;;;;;CAMC,GACD,OAAO,SAASC,kBACdC,IAA2E;IAE3E,IAAIA,KAAKC,IAAI,EAAE,OAAO;IACtB,IAAID,KAAKE,MAAM,KAAK,SAAS,OAAO;IACpC,OAAOF,KAAKE,MAAM,KAAK,aAAaF,KAAKG,SAAS,GAAG,YAAY;AACnE;AAEA;;;;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AAqB;oBACrClB,gBAAgB;oBAChB,IAAIA,iBAAiB,GAAGC,wBAAwBkB,KAAKC,GAAG;oBACxD,IAAIpB,gBAAgB1C,yBAAyB;wBAC3C+B,gBAAgB;wBAChB,IAAI,CAACa,gBAAgB;4BACnBA,iBAAiB;4BACjB1C,sBAAsB4C;wBACxB;oBACF;gBACF;gBACA,IAAIL,UAAU7B,aAAa;oBACzB6B,WAAW;oBACX,IAAIC,eAAe9B,aAAa;wBAC9B4B,sBAAsBpC,sBACpB+C,WACAR;oBAEJ,OAAO;wBACLJ,QAAQwB,WAAWZ,WAAWxC;oBAChC;gBACF,OAAO;oBACLkC,WAAW;oBACXrB,UAAU;oBACVE,SAASgC;oBACT,gEAAgE;oBAChE,iEAAiE;oBACjE,kEAAkE;oBAClE,8DAA8D;oBAC9D,qBAAqB;oBACrB,IAAIhB,eAAe9B,aAAa;wBAC9B4B,sBAAsBpC,sBACpB+C,WACAR;oBAEJ;gBACF;YACF;QAEJ;QACAQ;QAEA,gEAAgE;QAChE,uEAAuE;QACvE,yEAAyE;QACzE,MAAMa,kBAAkB3D,8BAA8B;YACpD,IAAIgC,aAAaK,iBAAiB,GAAG;YACrC,IAAIH,OAAO;gBACT0B,aAAa1B;gBACbA,QAAQ;YACV;YACAC,uCAAAA;YACAA,sBAAsB;YACtBF,+BAAAA;YACAG,UAAU;YACVG,iBAAiB;YACjBO;QACF;QAEA,OAAO;YACLd,YAAY;YACZU;YACAE,aAAaiB,KAAK;YAClBF;YACA,IAAIzB,OAAO0B,aAAa1B;YACxBC,uCAAAA;YACAF,+BAAAA;QACF;IACA,uDAAuD;IACzD,GAAGlB;IAEH,OAAO;QAAEL;QAAMC;QAAQS;QAAOE;QAAkBV;QAAWa;QAAcE;IAAO;AAClF;AAEA,eAAed,gBAAe"}
|
|
@@ -25,7 +25,13 @@ export interface UsePagedCollectionOptions extends UseFirestoreCollectionOptions
|
|
|
25
25
|
*/
|
|
26
26
|
pageSize?: number;
|
|
27
27
|
}
|
|
28
|
-
export interface UsePagedCollectionResult<T> extends UseFirestoreCollectionResult<T> {
|
|
28
|
+
export interface UsePagedCollectionResult<T> extends Omit<UseFirestoreCollectionResult<T>, 'listen'> {
|
|
29
|
+
/**
|
|
30
|
+
* The listener the rows came from, for a guarded save to wait on (AGL-4135).
|
|
31
|
+
* `null` for a window assembled from more than one listener, which names
|
|
32
|
+
* neither.
|
|
33
|
+
*/
|
|
34
|
+
listen: UseFirestoreCollectionResult<T>['listen'] | null;
|
|
29
35
|
/** The current page's rows. `data` holds the probe row; this never does. */
|
|
30
36
|
rows: T[];
|
|
31
37
|
/** A further page exists. A FACT from the probe row, not a guess. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-paged-collection.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 { DocumentData, Query } from 'firebase/firestore'\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type DependencyList,\n} from 'react'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport {\n useFirestoreCollection,\n type UseFirestoreCollectionOptions,\n type UseFirestoreCollectionResult,\n} from './use-firestore-collection'\n\nexport interface UsePagedCollectionOptions\n extends UseFirestoreCollectionOptions {\n /**\n * Rows per page. Defaults to the console-wide smallest option — a list\n * that picks its own number is how five different ones appear, and on a\n * query bounded by its page size the smallest page is the smallest bill.\n */\n pageSize?: number\n}\n\nexport interface UsePagedCollectionResult<T>\n extends UseFirestoreCollectionResult<T> {\n /** The current page's rows. `data` holds the probe row; this never does. */\n rows: T[]\n /** A further page exists. A FACT from the probe row, not a guess. */\n hasMore: boolean\n /** Zero-based, to match `ListPagination` and MUI. */\n page: number\n setPage: (page: number) => void\n pageSize: number\n setPageSize: (pageSize: number) => void\n}\n\n/**\n * A paged window over a live collection, instead of a big read sliced small.\n *\n * ## The shape this replaces\n *\n * A card would listen with `limit(300)` and render `rows.slice(0, 50)`. That\n * is wrong twice over. Two hundred and fifty documents are read, billed and\n * discarded on every mount — and the rows past the slice are not merely\n * wasted, they are UNREACHABLE, because nothing renders them and no control\n * asks for more. A merchant with sixty gift cards sees fifty and no\n * indication that ten more exist; past three hundred, a card issued this\n * morning cannot be reached at all.\n *\n * Here the window IS the query, and it is expressed in PAGES so the same\n * `ListPagination` footer serves this and a cursor feed. The listener is\n * widened to cover every page up to the one being read, so paging BACK costs\n * nothing — the rows are already in the snapshot — and paging forward costs\n * one page more.\n *\n * ## Why the window covers page 0..n rather than page n alone\n *\n * This is a live `onSnapshot`, not a fetch. Firestore cursors need a document\n * snapshot to resume from, which a listener that has never read page n - 1\n * does not have. Widening the limit is what makes forward and backward\n * symmetrical without a second read path, and the cost is bounded by how deep\n * the reader actually goes — with the shared default of ten, page three is\n * thirty-one documents, and most readers never leave page one.\n *\n * ## Why over-fetch by one\n *\n * `hasMore` has to be a fact. Comparing `length === limit` is wrong exactly\n * when the count is an even multiple of the page size — the case that offers\n * a \"next page\" leading nowhere, or hides one that leads somewhere. The probe\n * row answers it outright and is never rendered.\n *\n * ## Why the window resets on `deps`\n *\n * `deps` identify the SUBJECT being listened to. Without the reset, a card\n * paged three deep on one site opens the next site three pages in — a read\n * the reader never asked for, charged to whoever they switched to.\n *\n * `buildQuery` receives the limit to apply, so the caller keeps ownership of\n * ordering and predicates:\n *\n * ```ts\n * usePagedCollection<Card>(\n * (pageLimit) =>\n * hostId\n * ? query(collection(firestore, 'hosts', hostId, 'giftCards'),\n * orderBy('createdAt', 'desc'), limit(pageLimit))\n * : null,\n * [firestore, hostId],\n * { idField: '$id' },\n * )\n * ```\n */\nexport function usePagedCollection<T = DocumentData>(\n buildQuery: (pageLimit: number) => Query<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UsePagedCollectionOptions = {},\n): UsePagedCollectionResult<T> {\n const { pageSize: initialPageSize = TABLE_PAGE_SIZE_DEFAULT, ...collectionOptions } =\n options\n const [pageSize, setPageSizeState] = useState(initialPageSize)\n const [page, setPage] = useState(0)\n const buildQueryRef = useRef(buildQuery)\n buildQueryRef.current = buildQuery\n\n /*\n * A new subject starts at page one. Spreading `deps` is the same contract\n * `useFirestoreCollection` documents — pass the primitive ids, not the\n * Query.\n */\n useEffect(() => {\n setPage(0)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps])\n\n // Everything up to and including the page being read, plus the probe row.\n const windowSize = pageSize * (page + 1)\n const result = useFirestoreCollection<T>(\n () => buildQueryRef.current(windowSize + 1),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [...deps, windowSize],\n collectionOptions,\n )\n\n const hasMore = (result.data?.length ?? 0) > windowSize\n const rows = useMemo(\n () => (result.data ?? []).slice(page * pageSize, windowSize),\n [result.data, page, pageSize, windowSize],\n )\n const setPageSize = useCallback((next: number) => {\n setPageSizeState(next)\n // Page four of a ten-row list does not exist once the reader asks for\n // fifty at a time, and an out-of-range page renders as an empty list\n // with no explanation — which reads as the data having gone.\n setPage(0)\n }, [])\n\n return { ...result, rows, hasMore, page, setPage, pageSize, setPageSize }\n}\n"],"names":["useCallback","useEffect","useMemo","useRef","useState","TABLE_PAGE_SIZE_DEFAULT","useFirestoreCollection","usePagedCollection","buildQuery","deps","options","result","pageSize","initialPageSize","collectionOptions","setPageSizeState","page","setPage","buildQueryRef","current","windowSize","hasMore","data","length","rows","slice","setPageSize","next"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;AAGD,SACEA,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SACEC,sBAAsB,QAGjB,gCAA4B;
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-paged-collection.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 { DocumentData, Query } from 'firebase/firestore'\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type DependencyList,\n} from 'react'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport {\n useFirestoreCollection,\n type UseFirestoreCollectionOptions,\n type UseFirestoreCollectionResult,\n} from './use-firestore-collection'\n\nexport interface UsePagedCollectionOptions\n extends UseFirestoreCollectionOptions {\n /**\n * Rows per page. Defaults to the console-wide smallest option — a list\n * that picks its own number is how five different ones appear, and on a\n * query bounded by its page size the smallest page is the smallest bill.\n */\n pageSize?: number\n}\n\nexport interface UsePagedCollectionResult<T>\n extends Omit<UseFirestoreCollectionResult<T>, 'listen'> {\n /**\n * The listener the rows came from, for a guarded save to wait on (AGL-4135).\n * `null` for a window assembled from more than one listener, which names\n * neither.\n */\n listen: UseFirestoreCollectionResult<T>['listen'] | null\n /** The current page's rows. `data` holds the probe row; this never does. */\n rows: T[]\n /** A further page exists. A FACT from the probe row, not a guess. */\n hasMore: boolean\n /** Zero-based, to match `ListPagination` and MUI. */\n page: number\n setPage: (page: number) => void\n pageSize: number\n setPageSize: (pageSize: number) => void\n}\n\n/**\n * A paged window over a live collection, instead of a big read sliced small.\n *\n * ## The shape this replaces\n *\n * A card would listen with `limit(300)` and render `rows.slice(0, 50)`. That\n * is wrong twice over. Two hundred and fifty documents are read, billed and\n * discarded on every mount — and the rows past the slice are not merely\n * wasted, they are UNREACHABLE, because nothing renders them and no control\n * asks for more. A merchant with sixty gift cards sees fifty and no\n * indication that ten more exist; past three hundred, a card issued this\n * morning cannot be reached at all.\n *\n * Here the window IS the query, and it is expressed in PAGES so the same\n * `ListPagination` footer serves this and a cursor feed. The listener is\n * widened to cover every page up to the one being read, so paging BACK costs\n * nothing — the rows are already in the snapshot — and paging forward costs\n * one page more.\n *\n * ## Why the window covers page 0..n rather than page n alone\n *\n * This is a live `onSnapshot`, not a fetch. Firestore cursors need a document\n * snapshot to resume from, which a listener that has never read page n - 1\n * does not have. Widening the limit is what makes forward and backward\n * symmetrical without a second read path, and the cost is bounded by how deep\n * the reader actually goes — with the shared default of ten, page three is\n * thirty-one documents, and most readers never leave page one.\n *\n * ## Why over-fetch by one\n *\n * `hasMore` has to be a fact. Comparing `length === limit` is wrong exactly\n * when the count is an even multiple of the page size — the case that offers\n * a \"next page\" leading nowhere, or hides one that leads somewhere. The probe\n * row answers it outright and is never rendered.\n *\n * ## Why the window resets on `deps`\n *\n * `deps` identify the SUBJECT being listened to. Without the reset, a card\n * paged three deep on one site opens the next site three pages in — a read\n * the reader never asked for, charged to whoever they switched to.\n *\n * `buildQuery` receives the limit to apply, so the caller keeps ownership of\n * ordering and predicates:\n *\n * ```ts\n * usePagedCollection<Card>(\n * (pageLimit) =>\n * hostId\n * ? query(collection(firestore, 'hosts', hostId, 'giftCards'),\n * orderBy('createdAt', 'desc'), limit(pageLimit))\n * : null,\n * [firestore, hostId],\n * { idField: '$id' },\n * )\n * ```\n */\nexport function usePagedCollection<T = DocumentData>(\n buildQuery: (pageLimit: number) => Query<DocumentData> | null | undefined,\n deps: DependencyList,\n options: UsePagedCollectionOptions = {},\n): UsePagedCollectionResult<T> {\n const { pageSize: initialPageSize = TABLE_PAGE_SIZE_DEFAULT, ...collectionOptions } =\n options\n const [pageSize, setPageSizeState] = useState(initialPageSize)\n const [page, setPage] = useState(0)\n const buildQueryRef = useRef(buildQuery)\n buildQueryRef.current = buildQuery\n\n /*\n * A new subject starts at page one. Spreading `deps` is the same contract\n * `useFirestoreCollection` documents — pass the primitive ids, not the\n * Query.\n */\n useEffect(() => {\n setPage(0)\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...deps])\n\n // Everything up to and including the page being read, plus the probe row.\n const windowSize = pageSize * (page + 1)\n const result = useFirestoreCollection<T>(\n () => buildQueryRef.current(windowSize + 1),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [...deps, windowSize],\n collectionOptions,\n )\n\n const hasMore = (result.data?.length ?? 0) > windowSize\n const rows = useMemo(\n () => (result.data ?? []).slice(page * pageSize, windowSize),\n [result.data, page, pageSize, windowSize],\n )\n const setPageSize = useCallback((next: number) => {\n setPageSizeState(next)\n // Page four of a ten-row list does not exist once the reader asks for\n // fifty at a time, and an out-of-range page renders as an empty list\n // with no explanation — which reads as the data having gone.\n setPage(0)\n }, [])\n\n return { ...result, rows, hasMore, page, setPage, pageSize, setPageSize }\n}\n"],"names":["useCallback","useEffect","useMemo","useRef","useState","TABLE_PAGE_SIZE_DEFAULT","useFirestoreCollection","usePagedCollection","buildQuery","deps","options","result","pageSize","initialPageSize","collectionOptions","setPageSizeState","page","setPage","buildQueryRef","current","windowSize","hasMore","data","length","rows","slice","setPageSize","next"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;AAGD,SACEA,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SACEC,sBAAsB,QAGjB,gCAA4B;AA+BnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GACD,OAAO,SAASC,mBACdC,UAAyE,EACzEC,IAAoB,EACpBC,UAAqC,CAAC,CAAC;;QA4BtBC;IA1BjB,MAAM,EAAEC,UAAUC,kBAAkBR,uBAAuB,EAAwB,GACjFK,SAD8DI,qDAC9DJ;;;IACF,MAAM,CAACE,UAAUG,iBAAiB,GAAGX,SAASS;IAC9C,MAAM,CAACG,MAAMC,QAAQ,GAAGb,SAAS;IACjC,MAAMc,gBAAgBf,OAAOK;IAC7BU,cAAcC,OAAO,GAAGX;IAExB;;;;GAIC,GACDP,UAAU;QACRgB,QAAQ;IACR,uDAAuD;IACzD,GAAG;WAAIR;KAAK;IAEZ,0EAA0E;IAC1E,MAAMW,aAAaR,WAAYI,CAAAA,OAAO,CAAA;IACtC,MAAML,SAASL,uBACb,IAAMY,cAAcC,OAAO,CAACC,aAAa,IACzC,uDAAuD;IACvD;WAAIX;QAAMW;KAAW,EACrBN;IAGF,MAAMO,UAAU,UAACV,eAAAA,OAAOW,IAAI,qBAAXX,aAAaY,MAAM,mBAAI,KAAKH;IAC7C,MAAMI,OAAOtB,QACX;YAAOS;eAAD,EAACA,eAAAA,OAAOW,IAAI,YAAXX,eAAe,EAAE,EAAEc,KAAK,CAACT,OAAOJ,UAAUQ;OACjD;QAACT,OAAOW,IAAI;QAAEN;QAAMJ;QAAUQ;KAAW;IAE3C,MAAMM,cAAc1B,YAAY,CAAC2B;QAC/BZ,iBAAiBY;QACjB,sEAAsE;QACtE,qEAAqE;QACrE,6DAA6D;QAC7DV,QAAQ;IACV,GAAG,EAAE;IAEL,OAAO,aAAKN;QAAQa;QAAMH;QAASL;QAAMC;QAASL;QAAUc;;AAC9D"}
|
|
@@ -205,7 +205,9 @@ import { useFirestoreCollection } from "./use-firestore-collection.js";
|
|
|
205
205
|
status,
|
|
206
206
|
error: (_keyedRead_error = keyedRead.error) != null ? _keyedRead_error : scanOpen ? scanRead.error : undefined,
|
|
207
207
|
fromCache: keyedRead.fromCache || scanOpen && scanRead.fromCache,
|
|
208
|
-
serverDenied: keyedRead.serverDenied || scanOpen && scanRead.serverDenied
|
|
208
|
+
serverDenied: keyedRead.serverDenied || scanOpen && scanRead.serverDenied,
|
|
209
|
+
// Two listeners, so no one of them is the seed (AGL-4135).
|
|
210
|
+
listen: null
|
|
209
211
|
};
|
|
210
212
|
}
|
|
211
213
|
export default useSortedPagedCollection;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-sorted-paged-collection.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'use client'\n\nimport type { DocumentData, Query } from 'firebase/firestore'\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n type DependencyList,\n} from 'react'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport {\n planKeyedSegment,\n planSortedWindow,\n sortedKeyedQuery,\n sortedScanLimit,\n sortedUnkeyedQuery,\n sortFieldIsTotal,\n type CollectionSort,\n} from './sorted-collection-window'\nimport {\n useFirestoreCollection,\n type FirestoreCollectionStatus,\n type UseFirestoreCollectionOptions,\n} from './use-firestore-collection'\nimport type { UsePagedCollectionResult } from './use-paged-collection'\n\nexport interface UseSortedPagedCollectionOptions\n extends UseFirestoreCollectionOptions {\n /**\n * Required: the keyed and unkeyed segments are two listeners, and a\n * document moving between them is recognized by its id.\n */\n idField: string\n /** Rows per page. Defaults to the console-wide smallest option. */\n pageSize?: number\n /**\n * The fields `buildBase` pins by EQUALITY. A sort on one of them needs no\n * unkeyed segment — see `sortFieldIsTotal`.\n */\n equalityFields?: readonly string[]\n}\n\n/** `Object.is` over two dependency lists, the comparison React itself uses. */\nconst sameDeps = (a: DependencyList, b: DependencyList) =>\n a.length === b.length && a.every((value, index) => Object.is(value, b[index]))\n\n/**\n * The request a read's CURRENT rows were delivered for.\n *\n * `useFirestoreCollection` re-subscribes in an effect, so the render in which\n * its inputs change still returns the previous subscription's rows — rows for\n * another limit, sort or subject. Planning on them would judge a window by a\n * read that was never made for it: page two's window measured against page\n * one's eleven rows looks like a walk that ran out.\n *\n * So rows are labeled with the request that was current when they ARRIVED,\n * which is the render their array first appears in, and a render whose request\n * has since moved on treats them as unread. Held as state and adjusted during\n * render — the pattern React documents for state that follows a prop — so no\n * render ever pairs a request with rows read for another.\n */\nfunction useCurrentRows(rows: unknown, request: DependencyList): boolean {\n const [delivered, setDelivered] = useState<{\n rows: unknown\n request: DependencyList\n }>(() => ({ rows, request }))\n if (delivered.rows !== rows) {\n setDelivered({ rows, request })\n return true\n }\n return sameDeps(delivered.request, request)\n}\n\n/**\n * A paged window over a live collection SORTED BY A FIELD, which still drops\n * no document that lacks the field (AGL-2853).\n *\n * The same contract as `usePagedCollection` — the window is the query, one\n * page plus a probe row, `hasMore` a fact — over the two-segment walk in\n * `sorted-collection-window.ts`: the documents that carry the sort field in\n * its order, then the ones that do not, in name order. See that module for why\n * both segments are needed and what the second one costs.\n *\n * `buildBase` returns the collection with any EQUALITY predicates and nothing\n * else; the ordering and the limits are this hook's. `deps` identify the\n * subject as they do for `useFirestoreCollection`. A new subject, sort or\n * filter starts again from page one.\n *\n * ```ts\n * useSortedPagedCollection<Entry>(\n * () => query(\n * collection(firestore, 'hosts', hostId, 'collections', collectionId, 'entries'),\n * where('status', '==', status),\n * ),\n * { field: 'publishedAt', direction: 'desc' },\n * [firestore, hostId, collectionId, status],\n * { idField: '$id', equalityFields: ['status'] },\n * )\n * ```\n */\nexport function useSortedPagedCollection<T = DocumentData>(\n buildBase: () => Query<DocumentData> | null | undefined,\n sort: CollectionSort,\n deps: DependencyList,\n options: UseSortedPagedCollectionOptions,\n): UsePagedCollectionResult<T> {\n const {\n pageSize: initialPageSize = TABLE_PAGE_SIZE_DEFAULT,\n equalityFields = [],\n ...collectionOptions\n } = options\n const idField = options.idField\n const [pageSize, setPageSizeState] = useState(initialPageSize)\n const buildBaseRef = useRef(buildBase)\n buildBaseRef.current = buildBase\n\n const equalityKey = equalityFields.join('\\n')\n const subject: DependencyList = [\n ...deps,\n sort.field,\n sort.direction,\n equalityKey,\n ]\n\n /*\n * The reader's position belongs to ONE subject. It resets in the render the\n * subject changes in, not in an effect after it: an effect would let that\n * render subscribe the new sort at the old page's limit, and a sort change\n * on page four would bill forty-one documents to show ten.\n */\n const [cursor, setCursor] = useState(() => ({\n subject,\n page: 0,\n widenedTo: 0,\n }))\n const sameSubject = sameDeps(cursor.subject, subject)\n const position = sameSubject ? cursor : { subject, page: 0, widenedTo: 0 }\n if (!sameSubject) setCursor(position)\n const { page } = position\n\n const keyedIsTotal = sortFieldIsTotal(sort, equalityFields)\n const { keyedLimit } = planKeyedSegment({\n page,\n pageSize,\n keyed: undefined,\n keyedSettled: false,\n keyedIsTotal,\n })\n\n const keyedRequest: DependencyList = [...subject, keyedLimit]\n const keyedRead = useFirestoreCollection<T>(\n () => {\n const base = buildBaseRef.current()\n return base\n ? sortedKeyedQuery(base, sort, keyedLimit, equalityFields)\n : null\n },\n keyedRequest,\n collectionOptions,\n )\n const keyedCurrent = useCurrentRows(keyedRead.data, keyedRequest)\n const keyed =\n keyedCurrent && keyedRead.status !== 'loading' ? keyedRead.data : undefined\n const keyedSettled =\n keyedCurrent && keyedRead.status === 'success' && !keyedRead.fromCache\n\n const keyedPlan = planKeyedSegment({\n page,\n pageSize,\n keyed,\n keyedSettled,\n keyedIsTotal,\n })\n const scanLimit = sortedScanLimit(keyedPlan, position.widenedTo)\n\n const scanRequest: DependencyList = [...subject, scanLimit]\n const scanRead = useFirestoreCollection<T>(\n () => {\n if (scanLimit <= 0) return null\n const base = buildBaseRef.current()\n return base ? sortedUnkeyedQuery(base, scanLimit) : null\n },\n scanRequest,\n collectionOptions,\n )\n const scanCurrent = useCurrentRows(scanRead.data, scanRequest)\n const scanOpen = scanLimit > 0\n\n const sorted = planSortedWindow<T>({\n page,\n pageSize,\n sort,\n keyedIsTotal,\n keyed,\n keyedSettled,\n scan:\n scanOpen && scanCurrent && scanRead.status !== 'loading'\n ? scanRead.data\n : undefined,\n scanSettled:\n scanOpen &&\n scanCurrent &&\n scanRead.status === 'success' &&\n !scanRead.fromCache,\n scanLimit,\n idOf: (row) => String((row as Record<string, unknown>)[idField]),\n })\n\n /*\n * Widening is remembered for the subject, so paging back to where the scan\n * is not needed and forward again re-opens it at the width it reached\n * instead of doubling its way back up.\n */\n const widenTo = sorted.scanLimit\n useEffect(() => {\n if (widenTo <= position.widenedTo) return\n setCursor((previous) =>\n sameDeps(previous.subject, position.subject) &&\n widenTo > previous.widenedTo\n ? { ...previous, widenedTo: widenTo }\n : previous,\n )\n }, [widenTo, position.widenedTo, position.subject])\n\n const setPage = useCallback((next: number) => {\n setCursor((previous) => ({ ...previous, page: next }))\n }, [])\n const setPageSize = useCallback((next: number) => {\n setPageSizeState(next)\n // Page four of a ten-row list does not exist once the reader asks for\n // fifty at a time, and an out-of-range page renders as an empty list.\n setCursor((previous) => ({ ...previous, page: 0 }))\n }, [])\n\n /*\n * A short window is a claim that the list ENDS here, so it is `loading`\n * until the server has confirmed both segments. A window holding its probe\n * row claims only that more exists, which a cached read can say.\n */\n const errored =\n keyedRead.status === 'error' || (scanOpen && scanRead.status === 'error')\n const status: FirestoreCollectionStatus = errored\n ? 'error'\n : keyed === undefined\n ? 'loading'\n : sorted.hasMore || sorted.settled\n ? 'success'\n : 'loading'\n\n return {\n data: sorted.ordered,\n rows: sorted.rows,\n hasMore: sorted.hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n status,\n error: keyedRead.error ?? (scanOpen ? scanRead.error : undefined),\n fromCache: keyedRead.fromCache || (scanOpen && scanRead.fromCache),\n serverDenied:\n keyedRead.serverDenied || (scanOpen && scanRead.serverDenied),\n }\n}\n\nexport default useSortedPagedCollection\n"],"names":["useCallback","useEffect","useRef","useState","TABLE_PAGE_SIZE_DEFAULT","planKeyedSegment","planSortedWindow","sortedKeyedQuery","sortedScanLimit","sortedUnkeyedQuery","sortFieldIsTotal","useFirestoreCollection","sameDeps","a","b","length","every","value","index","Object","is","useCurrentRows","rows","request","delivered","setDelivered","useSortedPagedCollection","buildBase","sort","deps","options","keyedRead","pageSize","initialPageSize","equalityFields","collectionOptions","idField","setPageSizeState","buildBaseRef","current","equalityKey","join","subject","field","direction","cursor","setCursor","page","widenedTo","sameSubject","position","keyedIsTotal","keyedLimit","keyed","undefined","keyedSettled","keyedRequest","base","keyedCurrent","data","status","fromCache","keyedPlan","scanLimit","scanRequest","scanRead","scanCurrent","scanOpen","sorted","scan","scanSettled","idOf","row","String","widenTo","previous","setPage","next","setPageSize","errored","hasMore","settled","ordered","error","serverDenied"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SACEA,WAAW,EACXC,SAAS,EACTC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,gBAAgB,EAChBC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,QAEX,gCAA4B;AACnC,SACEC,sBAAsB,QAGjB,gCAA4B;AAmBnC,6EAA6E,GAC7E,MAAMC,WAAW,CAACC,GAAmBC,IACnCD,EAAEE,MAAM,KAAKD,EAAEC,MAAM,IAAIF,EAAEG,KAAK,CAAC,CAACC,OAAOC,QAAUC,OAAOC,EAAE,CAACH,OAAOH,CAAC,CAACI,MAAM;AAE9E;;;;;;;;;;;;;;CAcC,GACD,SAASG,eAAeC,IAAa,EAAEC,OAAuB;IAC5D,MAAM,CAACC,WAAWC,aAAa,GAAGtB,SAG/B,IAAO,CAAA;YAAEmB;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D;QAASxB,SAASF,SAAS;QAAEE,SAASR,OAAO;KAAC;IAElD,MAAMkC,UAAU5E,YAAY,CAAC6E;QAC3B/B,UAAU,CAAC6B,WAAc,aAAKA;gBAAU5B,MAAM8B;;IAChD,GAAG,EAAE;IACL,MAAMC,cAAc9E,YAAY,CAAC6E;QAC/BxC,iBAAiBwC;QACjB,sEAAsE;QACtE,sEAAsE;QACtE/B,UAAU,CAAC6B,WAAc,aAAKA;gBAAU5B,MAAM;;IAChD,GAAG,EAAE;IAEL;;;;GAIC,GACD,MAAMgC,UACJhD,UAAU6B,MAAM,KAAK,WAAYO,YAAYF,SAASL,MAAM,KAAK;IACnE,MAAMA,SAAoCmB,UACtC,UACA1B,UAAUC,YACR,YACAc,OAAOY,OAAO,IAAIZ,OAAOa,OAAO,GAC9B,YACA;IAER,OAAO;QACLtB,MAAMS,OAAOc,OAAO;QACpB5D,MAAM8C,OAAO9C,IAAI;QACjB0D,SAASZ,OAAOY,OAAO;QACvBjC;QACA6B;QACA5C;QACA8C;QACAlB;QACAuB,KAAK,GAAEpD,mBAAAA,UAAUoD,KAAK,YAAfpD,mBAAoBoC,WAAWF,SAASkB,KAAK,GAAG7B;QACvDO,WAAW9B,UAAU8B,SAAS,IAAKM,YAAYF,SAASJ,SAAS;QACjEuB,cACErD,UAAUqD,YAAY,IAAKjB,YAAYF,SAASmB,YAAY;IAChE;AACF;AAEA,eAAe1D,yBAAwB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-sorted-paged-collection.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'use client'\n\nimport type { DocumentData, Query } from 'firebase/firestore'\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n type DependencyList,\n} from 'react'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport {\n planKeyedSegment,\n planSortedWindow,\n sortedKeyedQuery,\n sortedScanLimit,\n sortedUnkeyedQuery,\n sortFieldIsTotal,\n type CollectionSort,\n} from './sorted-collection-window'\nimport {\n useFirestoreCollection,\n type FirestoreCollectionStatus,\n type UseFirestoreCollectionOptions,\n} from './use-firestore-collection'\nimport type { UsePagedCollectionResult } from './use-paged-collection'\n\nexport interface UseSortedPagedCollectionOptions\n extends UseFirestoreCollectionOptions {\n /**\n * Required: the keyed and unkeyed segments are two listeners, and a\n * document moving between them is recognized by its id.\n */\n idField: string\n /** Rows per page. Defaults to the console-wide smallest option. */\n pageSize?: number\n /**\n * The fields `buildBase` pins by EQUALITY. A sort on one of them needs no\n * unkeyed segment — see `sortFieldIsTotal`.\n */\n equalityFields?: readonly string[]\n}\n\n/** `Object.is` over two dependency lists, the comparison React itself uses. */\nconst sameDeps = (a: DependencyList, b: DependencyList) =>\n a.length === b.length && a.every((value, index) => Object.is(value, b[index]))\n\n/**\n * The request a read's CURRENT rows were delivered for.\n *\n * `useFirestoreCollection` re-subscribes in an effect, so the render in which\n * its inputs change still returns the previous subscription's rows — rows for\n * another limit, sort or subject. Planning on them would judge a window by a\n * read that was never made for it: page two's window measured against page\n * one's eleven rows looks like a walk that ran out.\n *\n * So rows are labeled with the request that was current when they ARRIVED,\n * which is the render their array first appears in, and a render whose request\n * has since moved on treats them as unread. Held as state and adjusted during\n * render — the pattern React documents for state that follows a prop — so no\n * render ever pairs a request with rows read for another.\n */\nfunction useCurrentRows(rows: unknown, request: DependencyList): boolean {\n const [delivered, setDelivered] = useState<{\n rows: unknown\n request: DependencyList\n }>(() => ({ rows, request }))\n if (delivered.rows !== rows) {\n setDelivered({ rows, request })\n return true\n }\n return sameDeps(delivered.request, request)\n}\n\n/**\n * A paged window over a live collection SORTED BY A FIELD, which still drops\n * no document that lacks the field (AGL-2853).\n *\n * The same contract as `usePagedCollection` — the window is the query, one\n * page plus a probe row, `hasMore` a fact — over the two-segment walk in\n * `sorted-collection-window.ts`: the documents that carry the sort field in\n * its order, then the ones that do not, in name order. See that module for why\n * both segments are needed and what the second one costs.\n *\n * `buildBase` returns the collection with any EQUALITY predicates and nothing\n * else; the ordering and the limits are this hook's. `deps` identify the\n * subject as they do for `useFirestoreCollection`. A new subject, sort or\n * filter starts again from page one.\n *\n * ```ts\n * useSortedPagedCollection<Entry>(\n * () => query(\n * collection(firestore, 'hosts', hostId, 'collections', collectionId, 'entries'),\n * where('status', '==', status),\n * ),\n * { field: 'publishedAt', direction: 'desc' },\n * [firestore, hostId, collectionId, status],\n * { idField: '$id', equalityFields: ['status'] },\n * )\n * ```\n */\nexport function useSortedPagedCollection<T = DocumentData>(\n buildBase: () => Query<DocumentData> | null | undefined,\n sort: CollectionSort,\n deps: DependencyList,\n options: UseSortedPagedCollectionOptions,\n): UsePagedCollectionResult<T> {\n const {\n pageSize: initialPageSize = TABLE_PAGE_SIZE_DEFAULT,\n equalityFields = [],\n ...collectionOptions\n } = options\n const idField = options.idField\n const [pageSize, setPageSizeState] = useState(initialPageSize)\n const buildBaseRef = useRef(buildBase)\n buildBaseRef.current = buildBase\n\n const equalityKey = equalityFields.join('\\n')\n const subject: DependencyList = [\n ...deps,\n sort.field,\n sort.direction,\n equalityKey,\n ]\n\n /*\n * The reader's position belongs to ONE subject. It resets in the render the\n * subject changes in, not in an effect after it: an effect would let that\n * render subscribe the new sort at the old page's limit, and a sort change\n * on page four would bill forty-one documents to show ten.\n */\n const [cursor, setCursor] = useState(() => ({\n subject,\n page: 0,\n widenedTo: 0,\n }))\n const sameSubject = sameDeps(cursor.subject, subject)\n const position = sameSubject ? cursor : { subject, page: 0, widenedTo: 0 }\n if (!sameSubject) setCursor(position)\n const { page } = position\n\n const keyedIsTotal = sortFieldIsTotal(sort, equalityFields)\n const { keyedLimit } = planKeyedSegment({\n page,\n pageSize,\n keyed: undefined,\n keyedSettled: false,\n keyedIsTotal,\n })\n\n const keyedRequest: DependencyList = [...subject, keyedLimit]\n const keyedRead = useFirestoreCollection<T>(\n () => {\n const base = buildBaseRef.current()\n return base\n ? sortedKeyedQuery(base, sort, keyedLimit, equalityFields)\n : null\n },\n keyedRequest,\n collectionOptions,\n )\n const keyedCurrent = useCurrentRows(keyedRead.data, keyedRequest)\n const keyed =\n keyedCurrent && keyedRead.status !== 'loading' ? keyedRead.data : undefined\n const keyedSettled =\n keyedCurrent && keyedRead.status === 'success' && !keyedRead.fromCache\n\n const keyedPlan = planKeyedSegment({\n page,\n pageSize,\n keyed,\n keyedSettled,\n keyedIsTotal,\n })\n const scanLimit = sortedScanLimit(keyedPlan, position.widenedTo)\n\n const scanRequest: DependencyList = [...subject, scanLimit]\n const scanRead = useFirestoreCollection<T>(\n () => {\n if (scanLimit <= 0) return null\n const base = buildBaseRef.current()\n return base ? sortedUnkeyedQuery(base, scanLimit) : null\n },\n scanRequest,\n collectionOptions,\n )\n const scanCurrent = useCurrentRows(scanRead.data, scanRequest)\n const scanOpen = scanLimit > 0\n\n const sorted = planSortedWindow<T>({\n page,\n pageSize,\n sort,\n keyedIsTotal,\n keyed,\n keyedSettled,\n scan:\n scanOpen && scanCurrent && scanRead.status !== 'loading'\n ? scanRead.data\n : undefined,\n scanSettled:\n scanOpen &&\n scanCurrent &&\n scanRead.status === 'success' &&\n !scanRead.fromCache,\n scanLimit,\n idOf: (row) => String((row as Record<string, unknown>)[idField]),\n })\n\n /*\n * Widening is remembered for the subject, so paging back to where the scan\n * is not needed and forward again re-opens it at the width it reached\n * instead of doubling its way back up.\n */\n const widenTo = sorted.scanLimit\n useEffect(() => {\n if (widenTo <= position.widenedTo) return\n setCursor((previous) =>\n sameDeps(previous.subject, position.subject) &&\n widenTo > previous.widenedTo\n ? { ...previous, widenedTo: widenTo }\n : previous,\n )\n }, [widenTo, position.widenedTo, position.subject])\n\n const setPage = useCallback((next: number) => {\n setCursor((previous) => ({ ...previous, page: next }))\n }, [])\n const setPageSize = useCallback((next: number) => {\n setPageSizeState(next)\n // Page four of a ten-row list does not exist once the reader asks for\n // fifty at a time, and an out-of-range page renders as an empty list.\n setCursor((previous) => ({ ...previous, page: 0 }))\n }, [])\n\n /*\n * A short window is a claim that the list ENDS here, so it is `loading`\n * until the server has confirmed both segments. A window holding its probe\n * row claims only that more exists, which a cached read can say.\n */\n const errored =\n keyedRead.status === 'error' || (scanOpen && scanRead.status === 'error')\n const status: FirestoreCollectionStatus = errored\n ? 'error'\n : keyed === undefined\n ? 'loading'\n : sorted.hasMore || sorted.settled\n ? 'success'\n : 'loading'\n\n return {\n data: sorted.ordered,\n rows: sorted.rows,\n hasMore: sorted.hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n status,\n error: keyedRead.error ?? (scanOpen ? scanRead.error : undefined),\n fromCache: keyedRead.fromCache || (scanOpen && scanRead.fromCache),\n serverDenied:\n keyedRead.serverDenied || (scanOpen && scanRead.serverDenied),\n // Two listeners, so no one of them is the seed (AGL-4135).\n listen: null,\n }\n}\n\nexport default useSortedPagedCollection\n"],"names":["useCallback","useEffect","useRef","useState","TABLE_PAGE_SIZE_DEFAULT","planKeyedSegment","planSortedWindow","sortedKeyedQuery","sortedScanLimit","sortedUnkeyedQuery","sortFieldIsTotal","useFirestoreCollection","sameDeps","a","b","length","every","value","index","Object","is","useCurrentRows","rows","request","delivered","setDelivered","useSortedPagedCollection","buildBase","sort","deps","options","keyedRead","pageSize","initialPageSize","equalityFields","collectionOptions","idField","setPageSizeState","buildBaseRef","current","equalityKey","join","subject","field","direction","cursor","setCursor","page","widenedTo","sameSubject","position","keyedIsTotal","keyedLimit","keyed","undefined","keyedSettled","keyedRequest","base","keyedCurrent","data","status","fromCache","keyedPlan","scanLimit","scanRequest","scanRead","scanCurrent","scanOpen","sorted","scan","scanSettled","idOf","row","String","widenTo","previous","setPage","next","setPageSize","errored","hasMore","settled","ordered","error","serverDenied","listen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,SACEA,WAAW,EACXC,SAAS,EACTC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,gBAAgB,EAChBC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,QAEX,gCAA4B;AACnC,SACEC,sBAAsB,QAGjB,gCAA4B;AAmBnC,6EAA6E,GAC7E,MAAMC,WAAW,CAACC,GAAmBC,IACnCD,EAAEE,MAAM,KAAKD,EAAEC,MAAM,IAAIF,EAAEG,KAAK,CAAC,CAACC,OAAOC,QAAUC,OAAOC,EAAE,CAACH,OAAOH,CAAC,CAACI,MAAM;AAE9E;;;;;;;;;;;;;;CAcC,GACD,SAASG,eAAeC,IAAa,EAAEC,OAAuB;IAC5D,MAAM,CAACC,WAAWC,aAAa,GAAGtB,SAG/B,IAAO,CAAA;YAAEmB;YAAMC;QAAQ,CAAA;IAC1B,IAAIC,UAAUF,IAAI,KAAKA,MAAM;QAC3BG,aAAa;YAAEH;YAAMC;QAAQ;QAC7B,OAAO;IACT;IACA,OAAOX,SAASY,UAAUD,OAAO,EAAEA;AACrC;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,SAASG,yBACdC,SAAuD,EACvDC,IAAoB,EACpBC,IAAoB,EACpBC,OAAwC;QA0J/BC;IAxJT,MAAM,EACJC,UAAUC,kBAAkB7B,uBAAuB,EACnD8B,iBAAiB,EAAE,EAEpB,GAAGJ,SADCK,qDACDL;;;;IACJ,MAAMM,UAAUN,QAAQM,OAAO;IAC/B,MAAM,CAACJ,UAAUK,iBAAiB,GAAGlC,SAAS8B;IAC9C,MAAMK,eAAepC,OAAOyB;IAC5BW,aAAaC,OAAO,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S,OAAOc,OAAO;QACpB5D,MAAM8C,OAAO9C,IAAI;QACjB0D,SAASZ,OAAOY,OAAO;QACvBjC;QACA6B;QACA5C;QACA8C;QACAlB;QACAuB,KAAK,GAAEpD,mBAAAA,UAAUoD,KAAK,YAAfpD,mBAAoBoC,WAAWF,SAASkB,KAAK,GAAG7B;QACvDO,WAAW9B,UAAU8B,SAAS,IAAKM,YAAYF,SAASJ,SAAS;QACjEuB,cACErD,UAAUqD,YAAY,IAAKjB,YAAYF,SAASmB,YAAY;QAC9D,2DAA2D;QAC3DC,QAAQ;IACV;AACF;AAEA,eAAe3D,yBAAwB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/testing/list-query-double.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\n/**\n * A TEST DOUBLE for `useListQuery` (AGL-3321) — for specs only.\n *\n * It runs the REAL `planListQuery` over the request, then answers the plan\n * the way Firestore would: each of `plan.filters` (==, !=, ranges, in,\n * array-contains, array-contains-any, the document id) over fixture rows,\n * the plan's one order, and pages of the requested size. A card spec mocks\n * the hook with it:\n *\n * jest.mock('@aglyn/tenant-feature-instance/hooks/use-list-query', () =>\n * require('@aglyn/tenant-feature-instance/testing/list-query-double')\n * .listQueryModule(\n * () => mockRows,\n * jest.requireActual('@aglyn/tenant-feature-instance/hooks/use-list-query'),\n * ))\n *\n * and asserts both what the plan asked for (`lastListQueryPlan()`) and which\n * rows came back — so a spec can prove a match past the first page is found.\n *\n * ⛔ Never import this outside a spec. It is exactly the in-memory matching\n * the lists stopped doing; a production path through it is the bug AGL-3321\n * removed.\n */\n\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n LIST_QUERY_ID_PATH,\n type ListQueryFilter,\n type ListQueryPlan,\n planListQuery,\n} from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useMemo, useState } from 'react'\nimport type { UseListQueryOptions, UseListQueryResult } from '../hooks/use-list-query'\n\ntype Row = Record<string, unknown> & { $id?: string }\n\nconst read = (row: Row, path: string): unknown =>\n path === LIST_QUERY_ID_PATH\n ? row.$id\n : path.split('.').reduce<unknown>(\n (at, key) => (at == null ? undefined : (at as Record<string, unknown>)[key]),\n row,\n )\n\nconst comparable = (value: unknown): unknown => {\n if (value instanceof Date) return value.getTime()\n if (value && typeof value === 'object' && 'toMillis' in value) {\n return (value as { toMillis(): number }).toMillis()\n }\n if (value && typeof value === 'object' && 'seconds' in value) {\n return (value as { seconds: number }).seconds * 1000\n }\n return value\n}\n\n/** Whether a row answers one predicate, as Firestore reads it. */\nexport function rowAnswers(row: Row, filter: ListQueryFilter): boolean {\n const held = read(row, filter.path)\n const want = filter.value\n switch (filter.op) {\n case '==':\n return want === null ? held === null : comparable(held) === comparable(want)\n case '!=':\n // Firestore's `!=` also requires the field to exist.\n return held !== undefined && comparable(held) !== comparable(want)\n case 'in':\n return (want as readonly unknown[]).some((entry) => comparable(entry) === comparable(held))\n case 'array-contains':\n return Array.isArray(held) && held.includes(want as never)\n case 'array-contains-any':\n return Array.isArray(held) && (want as readonly unknown[]).some((entry) => held.includes(entry))\n default: {\n if (held === undefined || held === null) return false\n const a = comparable(held) as number | string\n const b = comparable(want) as number | string\n if (filter.op === '<') return a < b\n if (filter.op === '<=') return a <= b\n if (filter.op === '>') return a > b\n return a >= b\n }\n }\n}\n\n/** The rows a plan's query returns, in its order — Firestore's answer, restated. */\nexport function answerListQuery<T extends Row>(rows: readonly T[], plan: ListQueryPlan): T[] {\n const { path, direction } = plan.orderBy\n return rows\n .filter((row) => plan.filters.every((filter) => rowAnswers(row, filter)))\n // `orderBy` drops a document missing the field it sorts by.\n .filter((row) => path === LIST_QUERY_ID_PATH || read(row, path) !== undefined)\n .sort((left, right) => {\n const a = comparable(read(left, path)) as number | string\n const b = comparable(read(right, path)) as number | string\n const order = a < b ? -1 : a > b ? 1 : String(left.$id).localeCompare(String(right.$id))\n return direction === 'desc' ? -order : order\n })\n}\n\nlet lastPlan: ListQueryPlan | null = null\n\n/** The plan the double answered last, for a spec to assert what was asked. */\nexport const lastListQueryPlan = (): ListQueryPlan | null => lastPlan\n\n/**\n * `useListQuery`, answered from `rows()` instead of Firestore — same\n * signature, same paging surface as `usePagedCollection`.\n */\nexport function useListQueryDouble<T = Row>(\n rows: () => readonly Row[],\n options: UseListQueryOptions,\n): UseListQueryResult<T> {\n const { declaration, request } = options\n const pageSizeOption = options.pageSize ?? 10\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(pageSizeOption)\n const plan = useMemo(\n () => planListQuery(declaration, request, nameSearchNormalizers),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [declaration, JSON.stringify(request)],\n )\n lastPlan = plan\n const matched = answerListQuery(rows(), plan)\n const windowRows = matched.slice(0, pageSize * (page + 1) + 1)\n return {\n data: windowRows as unknown as T[],\n rows: matched.slice(page * pageSize, (page + 1) * pageSize) as unknown as T[],\n hasMore: matched.length > pageSize * (page + 1),\n page,\n setPage,\n pageSize,\n setPageSize: (next: number) => {\n setPageSize(next)\n setPage(0)\n },\n status: 'success',\n error: undefined,\n fromCache: false,\n serverDenied: false,\n plan,\n } as unknown as UseListQueryResult<T>\n}\n\n/**\n * A module to hand `jest.mock('…/hooks/use-list-query', …)`: the double in\n * place of the hook, the real `listQueryConstraints` beside it.\n *\n * `actual` is the real module, which the spec's factory passes in as\n * `jest.requireActual(…)`. Jest injects `jest` into each spec module rather\n * than setting it on `globalThis`, so this file cannot reach it itself.\n */\nexport function listQueryModule(rows: () => readonly Row[], actual: object) {\n return {\n ...actual,\n useListQuery: (options: UseListQueryOptions) => useListQueryDouble(rows, options),\n }\n}\n"],"names":["nameSearchNormalizers","LIST_QUERY_ID_PATH","planListQuery","useMemo","useState","read","row","path","$id","split","reduce","at","key","undefined","comparable","value","Date","getTime","toMillis","seconds","rowAnswers","filter","held","want","op","some","entry","Array","isArray","includes","a","b","answerListQuery","rows","plan","direction","orderBy","filters","every","sort","left","right","order","String","localeCompare","lastPlan","lastListQueryPlan","useListQueryDouble","options","declaration","request","pageSizeOption","pageSize","page","setPage","setPageSize","JSON","stringify","matched","windowRows","slice","data","hasMore","length","next","status","error","fromCache","serverDenied","listQueryModule","actual","useListQuery"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,SAASA,qBAAqB,QAAQ,qCAAoC;AAC1E,SACEC,kBAAkB,EAGlBC,aAAa,QACR,6CAA4C;AACnD,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAKzC,MAAMC,OAAO,CAACC,KAAUC,OACtBA,SAASN,qBACLK,IAAIE,GAAG,GACPD,KAAKE,KAAK,CAAC,KAAKC,MAAM,CACpB,CAACC,IAAIC,MAASD,MAAM,OAAOE,YAAY,AAACF,EAA8B,CAACC,IAAI,EAC3EN;AAGR,MAAMQ,aAAa,CAACC;IAClB,IAAIA,iBAAiBC,MAAM,OAAOD,MAAME,OAAO;IAC/C,IAAIF,SAAS,OAAOA,UAAU,YAAY,cAAcA,OAAO;QAC7D,OAAO,AAACA,MAAiCG,QAAQ;IACnD;IACA,IAAIH,SAAS,OAAOA,UAAU,YAAY,aAAaA,OAAO;QAC5D,OAAO,AAACA,MAA8BI,OAAO,GAAG;IAClD;IACA,OAAOJ;AACT;AAEA,gEAAgE,GAChE,OAAO,SAASK,WAAWd,GAAQ,EAAEe,MAAuB;IAC1D,MAAMC,OAAOjB,KAAKC,KAAKe,OAAOd,IAAI;IAClC,MAAMgB,OAAO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AMe;;AAE7E"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/testing/list-query-double.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\n/**\n * A TEST DOUBLE for `useListQuery` (AGL-3321) — for specs only.\n *\n * It runs the REAL `planListQuery` over the request, then answers the plan\n * the way Firestore would: each of `plan.filters` (==, !=, ranges, in,\n * array-contains, array-contains-any, the document id) over fixture rows,\n * the plan's one order, and pages of the requested size. A card spec mocks\n * the hook with it:\n *\n * jest.mock('@aglyn/tenant-feature-instance/hooks/use-list-query', () =>\n * require('@aglyn/tenant-feature-instance/testing/list-query-double')\n * .listQueryModule(\n * () => mockRows,\n * jest.requireActual('@aglyn/tenant-feature-instance/hooks/use-list-query'),\n * ))\n *\n * and asserts both what the plan asked for (`lastListQueryPlan()`) and which\n * rows came back — so a spec can prove a match past the first page is found.\n *\n * ⛔ Never import this outside a spec. It is exactly the in-memory matching\n * the lists stopped doing; a production path through it is the bug AGL-3321\n * removed.\n */\n\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n LIST_QUERY_ID_PATH,\n type ListQueryFilter,\n type ListQueryPlan,\n planListQuery,\n} from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useMemo, useState } from 'react'\nimport type { UseListQueryOptions, UseListQueryResult } from '../hooks/use-list-query'\n\ntype Row = Record<string, unknown> & { $id?: string }\n\nconst read = (row: Row, path: string): unknown =>\n path === LIST_QUERY_ID_PATH\n ? row.$id\n : path.split('.').reduce<unknown>(\n (at, key) => (at == null ? undefined : (at as Record<string, unknown>)[key]),\n row,\n )\n\nconst comparable = (value: unknown): unknown => {\n if (value instanceof Date) return value.getTime()\n if (value && typeof value === 'object' && 'toMillis' in value) {\n return (value as { toMillis(): number }).toMillis()\n }\n if (value && typeof value === 'object' && 'seconds' in value) {\n return (value as { seconds: number }).seconds * 1000\n }\n return value\n}\n\n/** Whether a row answers one predicate, as Firestore reads it. */\nexport function rowAnswers(row: Row, filter: ListQueryFilter): boolean {\n const held = read(row, filter.path)\n const want = filter.value\n switch (filter.op) {\n case '==':\n return want === null ? held === null : comparable(held) === comparable(want)\n case '!=':\n // Firestore's `!=` also requires the field to exist.\n return held !== undefined && comparable(held) !== comparable(want)\n case 'in':\n return (want as readonly unknown[]).some((entry) => comparable(entry) === comparable(held))\n case 'array-contains':\n return Array.isArray(held) && held.includes(want as never)\n case 'array-contains-any':\n return Array.isArray(held) && (want as readonly unknown[]).some((entry) => held.includes(entry))\n default: {\n if (held === undefined || held === null) return false\n const a = comparable(held) as number | string\n const b = comparable(want) as number | string\n if (filter.op === '<') return a < b\n if (filter.op === '<=') return a <= b\n if (filter.op === '>') return a > b\n return a >= b\n }\n }\n}\n\n/** The rows a plan's query returns, in its order — Firestore's answer, restated. */\nexport function answerListQuery<T extends Row>(rows: readonly T[], plan: ListQueryPlan): T[] {\n const { path, direction } = plan.orderBy\n return rows\n .filter((row) => plan.filters.every((filter) => rowAnswers(row, filter)))\n // `orderBy` drops a document missing the field it sorts by.\n .filter((row) => path === LIST_QUERY_ID_PATH || read(row, path) !== undefined)\n .sort((left, right) => {\n const a = comparable(read(left, path)) as number | string\n const b = comparable(read(right, path)) as number | string\n const order = a < b ? -1 : a > b ? 1 : String(left.$id).localeCompare(String(right.$id))\n return direction === 'desc' ? -order : order\n })\n}\n\nlet lastPlan: ListQueryPlan | null = null\n\n/** The plan the double answered last, for a spec to assert what was asked. */\nexport const lastListQueryPlan = (): ListQueryPlan | null => lastPlan\n\n/**\n * `useListQuery`, answered from `rows()` instead of Firestore — same\n * signature, same paging surface as `usePagedCollection`.\n */\nexport function useListQueryDouble<T = Row>(\n rows: () => readonly Row[],\n options: UseListQueryOptions,\n): UseListQueryResult<T> {\n const { declaration, request } = options\n const pageSizeOption = options.pageSize ?? 10\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(pageSizeOption)\n const plan = useMemo(\n () => planListQuery(declaration, request, nameSearchNormalizers),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [declaration, JSON.stringify(request)],\n )\n lastPlan = plan\n const matched = answerListQuery(rows(), plan)\n const windowRows = matched.slice(0, pageSize * (page + 1) + 1)\n return {\n data: windowRows as unknown as T[],\n rows: matched.slice(page * pageSize, (page + 1) * pageSize) as unknown as T[],\n hasMore: matched.length > pageSize * (page + 1),\n page,\n setPage,\n pageSize,\n setPageSize: (next: number) => {\n setPageSize(next)\n setPage(0)\n },\n status: 'success',\n error: undefined,\n fromCache: false,\n serverDenied: false,\n listen: null,\n plan,\n } as unknown as UseListQueryResult<T>\n}\n\n/**\n * A module to hand `jest.mock('…/hooks/use-list-query', …)`: the double in\n * place of the hook, the real `listQueryConstraints` beside it.\n *\n * `actual` is the real module, which the spec's factory passes in as\n * `jest.requireActual(…)`. Jest injects `jest` into each spec module rather\n * than setting it on `globalThis`, so this file cannot reach it itself.\n */\nexport function listQueryModule(rows: () => readonly Row[], actual: object) {\n return {\n ...actual,\n useListQuery: (options: UseListQueryOptions) => useListQueryDouble(rows, options),\n }\n}\n"],"names":["nameSearchNormalizers","LIST_QUERY_ID_PATH","planListQuery","useMemo","useState","read","row","path","$id","split","reduce","at","key","undefined","comparable","value","Date","getTime","toMillis","seconds","rowAnswers","filter","held","want","op","some","entry","Array","isArray","includes","a","b","answerListQuery","rows","plan","direction","orderBy","filters","every","sort","left","right","order","String","localeCompare","lastPlan","lastListQueryPlan","useListQueryDouble","options","declaration","request","pageSizeOption","pageSize","page","setPage","setPageSize","JSON","stringify","matched","windowRows","slice","data","hasMore","length","next","status","error","fromCache","serverDenied","listen","listQueryModule","actual","useListQuery"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,SAASA,qBAAqB,QAAQ,qCAAoC;AAC1E,SACEC,kBAAkB,EAGlBC,aAAa,QACR,6CAA4C;AACnD,SAASC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AAKzC,MAAMC,OAAO,CAACC,KAAUC,OACtBA,SAASN,qBACLK,IAAIE,GAAG,GACPD,KAAKE,KAAK,CAAC,KAAKC,MAAM,CACpB,CAACC,IAAIC,MAASD,MAAM,OAAOE,YAAY,AAACF,EAA8B,CAACC,IAAI,EAC3EN;AAGR,MAAMQ,aAAa,CAACC;IAClB,IAAIA,iBAAiBC,MAAM,OAAOD,MAAME,OAAO;IAC/C,IAAIF,SAAS,OAAOA,UAAU,YAAY,cAAcA,OAAO;QAC7D,OAAO,AAACA,MAAiCG,QAAQ;IACnD;IACA,IAAIH,SAAS,OAAOA,UAAU,YAAY,aAAaA,OAAO;QAC5D,OAAO,AAACA,MAA8BI,OAAO,GAAG;IAClD;IACA,OAAOJ;AACT;AAEA,gEAAgE,GAChE,OAAO,SAASK,WAAWd,GAAQ,EAAEe,MAAuB;IAC1D,MAAMC,OAAOjB,KAAKC,KAAKe,OAAOd,IAAI;IAClC,MAAMgB,OAAOF,OAAON,KAAK;IACzB,OAAQM,OAAOG,EAAE;QACf,KAAK;YACH,OAAOD,SAAS,OAAOD,SAAS,OAAOR,WAAWQ,UAAUR,WAAWS;QACzE,KAAK;YACH,qDAAqD;YACrD,OAAOD,SAAST,aAAaC,WAAWQ,UAAUR,WAAWS;QAC/D,KAAK;YACH,OAAO,AAACA,KAA4BE,IAAI,CAAC,CAACC,QAAUZ,WAAWY,WAAWZ,WAAWQ;QACvF,KAAK;YACH,OAAOK,MAAMC,OAAO,CAACN,SAASA,KAAKO,QAAQ,CAACN;QAC9C,KAAK;YACH,OAAOI,MAAMC,OA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