🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(replica): prepare @lobechat/replica for extraction (#21415)
Arvin Xu659adc6007a9
diff --git a/.agents/skills/zustand/SKILL.md b/.agents/skills/zustand/SKILL.mdindex 9f765008992..0426c1a31d4 100644--- a/.agents/skills/zustand/SKILL.md+++ b/.agents/skills/zustand/SKILL.md@@ -40,7 +40,7 @@ Server lists and details the UI paints go through `@/libs/replica`, not a hand-w3. Bind it in the private class: `createReplicaSlice(resource, { get, set, stateKey: 'xxxReplica', view: recordLens('xxxMap'), … })`. When the same entity lives in several replicas (list row + detail), link them with `linkReplicaEntity([list, detail])`.4. Read: `slice.useSync(params)` returns only fetch flags (`isHydrated`, `isValidating`, `error`, `revalidate`). Data comes from selectors over `xxxMap`. "Entry is `undefined`" is the loading signal — do not add `xxxInit` flags or `loadingXxxIds`.5. Read with no view mounted (hover prefetch, refresh after a mutation): `await slice.fetch(params)` (`{ fresh: true }` after a write). Never call the service and `slice.replace(...)` by hand, because that skips the scope, removal, clear and superseded-request guards. Side effects of every response (not-found maps, seeding another store) go in the slice `effects` (`onApplied` / `onMissing` / `onPurge` / `onError`) with `isMissing`, not in one hook's `onSuccess`.-6. Cold start without a skeleton: `useSync` hydrates only after the component mounts. For a list that must paint from the local copy, add a `preHydrate` action (`ensureScope` + `hydrate`) and call it from the route's `loader` through a lazy wrapper (`src/spa/router/pageListLoader.ts`, `agentChatTopicListLoader.ts`) bounded by `PRE_PAINT_HYDRATE_TIMEOUT`.+6. Cold start without a skeleton: `useSync` hydrates only after the component mounts. For a list that must paint from the local copy, add a `preHydrate` action (`ensureScope` + `hydrate`) and call it from the route's `loader` through a lazy wrapper (`src/spa/router/pageListLoader.ts`, `agentChatTopicListLoader.ts`) bounded by `settleWithin(…, PRE_PAINT_HYDRATE_TIMEOUT)` from `@/libs/replica/prePaint`. `@/libs/replica` presets the cache scope, IndexedDB / localStorage storage (`@/libs/queryProjectionStorage`) and the app's SWR driver; the package README stays app-agnostic.7. Write: `slice.optimistic(key, apply, serverCall)` or `entity.optimistic(id, fn | 'remove', serverCall)`. A failed call rolls back to the confirmed value, so deletes are optimistic too. Rows that exist only on the client (temp ids) are declared with `isClientOnly` and seeded with `update(key, fn, { persist: false })`.Outside test seeding, write a replica's view only through its slice. A plain `set` bypasses the engine's bookkeeping (persistence, rollback base, entity links).diff --git a/packages/replica/README.md b/packages/replica/README.mdindex e7fe54dd1b7..b3f0a8dd91e 100644--- a/packages/replica/README.md+++ b/packages/replica/README.md@@ -10,17 +10,17 @@ Every list and detail the UI shows is a **replica**: a local copy of server stat## Layers-| Entry | What it owns |-| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `@lobechat/replica` | Core engine, framework-agnostic: resource definition, pure reducer, paging (offset / cursor, forward / backward), entity links, serialized persistence. |-| `@lobechat/replica/zustand` | Zustand adapter: binds a resource to one location in a domain store (`recordLens`). Adds a `useSync` hook that schedules fetches through a `ReplicaSyncDriver` (`createSWRDriver` for SWR). |+| Entry | What it owns |+| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `@lobechat/replica` | Core engine, framework-agnostic: resource definition, pure reducer, paging (offset / cursor, forward / backward), entity links, serialized persistence, storage adapters (see [Storage](#storage)). |+| `@lobechat/replica/zustand` | Zustand adapter: binds a resource to one location in a domain store (`recordLens`). Adds a `useSync` hook that schedules fetches through a `ReplicaSyncDriver` (`createSWRDriver` for SWR). |The host store stays the only UI source of truth. Components read the store through their usual selectors. `useSync` only reports fetch flags (`isHydrated`, `isValidating`, `error`, `revalidate`) and never returns data.## Usage```ts-import { definePagedReplica } from '@lobechat/replica';+import { definePagedReplica, KeyValueReplicaStorage } from '@lobechat/replica';import { createReplicaSlice, createSWRDriver, recordLens } from '@lobechat/replica/zustand';const topicList = definePagedReplica<Params, Topic, number, TopicPage>({@@ -29,7 +29,7 @@ const topicList = definePagedReplica<Params, Topic, number, TopicPage>({paging: { direction: 'forward', getId: (t) => t.id, mode: 'offset', persist: { pages: 1 } },query: ({ sortBy }) => ({ sortBy }), // query identity beyond the keyscope, // ReplicaScope: { get, use, canPersist }- storage: (namespace) => new MyIndexedDBStorage(namespace), // ReplicaStorage+ storage: (namespace) => new KeyValueReplicaStorage({ namespace, store }), // see Storageversion: 1,});@@ -47,11 +47,20 @@ slice.loadMore(key);slice.optimistic(key, apply, serverCall);```-A persisted read is asynchronous, so a list hydrated only by `useSync` paints its loading state for a few frames on a cold start. When that list must paint without a skeleton, seed it from the route loader before the route commits: `slice.ensureScope(scope)` + `slice.hydrate(params, scope)`, bounded by `settleWithin(…, PRE_PAINT_HYDRATE_TIMEOUT)` from `@/libs/replica/prePaint`. A later `useSync` hydrate is a no-op once the slot is filled.+A persisted read is asynchronous, so a list hydrated only by `useSync` paints its loading state for a few frames on a cold start. When that list must paint without a skeleton, seed it from the route loader before the route commits: `slice.ensureScope(scope)` + `slice.hydrate(params, scope)`, bounded by `settleWithin(hydrate, ms)` so a stalled storage never holds the route back. A later `useSync` hydrate is a no-op once the slot is filled.A persisted row is only rewritten when its value changes: a persist whose value is deep-equal to what the engine last wrote to (or hydrated from) that row is skipped, so an unchanged revalidation costs no storage write. A failed write, a delete, an entity patch, an eviction or a `clear()` forgets what the row holds, so the next persist writes it again. The engine only tracks its own writes: a row changed behind it (another tab) is corrected by the next changed value or the next session.-Inside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / localStorage storage and the app's SWR driver.+## Storage++A resource persists through any `ReplicaStorage` (`get` / `getStrict` / `set` / `remove`; see [Invalidation](#invalidation) for the failure contract). Two adapters ship with the package, both keyed `<namespace>:<scope>:<queryKey>`:++| Adapter | Backing | Use |+| ---------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |+| `KeyValueReplicaStorage` | Any async key-value store `{ get, set, delete, initialize? }`: an IndexedDB object store, SQLite over IPC … | Lists and details of any size. Rows are stored as objects, so the store decides what it can clone. |+| `LocalStorageReplicaStorage` | `window.localStorage` through a codec (JSON by default; pass superjson or similar for `Date`, `Map` …) | Small values that must paint inside pre-paint initialization: `getSync(key)` reads a row without yielding a frame. |++Both reject failed writes and deletes and implement `getStrict`, so every destructive pass works on them. Outside a browser `LocalStorageReplicaStorage` is a no-op miss.## Fetching without a mounted viewdiff --git a/packages/replica/src/core/engine.persistence.test.ts b/packages/replica/src/core/engine.persistence.test.tsindex bf6dfd0d5b9..0c54f185887 100644--- a/packages/replica/src/core/engine.persistence.test.ts+++ b/packages/replica/src/core/engine.persistence.test.ts@@ -683,3 +683,48 @@ describe('useSync pins the entry it shows', () => {expect(Object.keys(store.getState().lists)).toEqual(['c']);});});++describe('entity patches of unloaded rows', () => {+ it('writes a `null` the entity adapter maps to as a value, and drops the row only on `undefined`', async () => {+ resetScope();+ const storage = createStorage();+ const setup = () => {+ const resource = defineReplica<ListParams, Item[] | null>({+ key: ({ id }) => id,+ name: 'list',+ query: ({ q }) => ({ q }),+ scope,+ storage: storage.storage,+ version: 1,+ });+ const host = createHost<Item[] | null>();+ const engine = createReplicaEngine(resource, {+ // `null` is a real value of this resource: "cleared", not "gone".+ entity: {+ has: (data, id) => !!data?.some((entry) => entry.id === id),+ map: (data, id, fn) => {+ if (!data?.some((entry) => entry.id === id)) return data;+ const next = data.map((entry) => (entry.id === id ? fn(entry) : entry));+ if (next.includes(undefined)) return id === 'gone' ? undefined : null;+ return next as Item[];+ },+ },+ port: host.port,+ });+ return engine;+ };+ const first = setup();+ first.replace({ id: 'a' }, [item('cleared')]);+ first.replace({ id: 'b' }, [item('gone')]);+ await flush();++ // A fresh session holds neither entry in memory, so both go through storage.+ const engine = setup();+ await engine.removeEntity('cleared');+ await engine.removeEntity('gone');+ await flush();++ expect(storage.rows.get(`${SCOPE}|a?{}`)?.data).toBeNull();+ expect(storage.rows.has(`${SCOPE}|b?{}`)).toBe(false);+ });+});diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.tsindex 98f46477c88..ede1698e257 100644--- a/packages/replica/src/core/engine.ts+++ b/packages/replica/src/core/engine.ts@@ -1,29 +1,29 @@import isEqual from 'fast-deep-equal';-import { isReplicaStorageKeyOf, replicaStorageKey, stableQueryKey } from './defineReplica';+import { replicaStorageKey, stableQueryKey } from './defineReplica';+import { createEntityPropagation } from './entityPropagation';import {applyHeadPage,applyNextPage,collapseToHead,getNextPageCursor,- hasPagedItem,insertHeadItems,joinPages,- mapPagedItem,pagingFor,type ReplicaPagedData,type ReplicaPageResult,type ReplicaPagingContext,toPersistedPage,} from './paging';+import { createPersistedRows } from './persistedRows';import type { ReplicaAction, ReplicaEffect, ReplicaViewWrite } from './reducer';import { replicaReducer } from './reducer';-import { createTombstones, DEFAULT_REMOVAL_TOMBSTONE_LIMIT } from './tombstones';+import { createEntityRemovalGuards, createRemovalGuards } from './removalGuards';import type { ReplicaResource, ReplicaSource, ReplicaState } from './types';-import { readReplicaRowStrict, ReplicaWriteQueue } from './writeQueue';+import { ReplicaWriteQueue } from './writeQueue';/** Reserved storage key of the per-scope index of persisted rows. */-export const REPLICA_INDEX_KEY = '__replica:index';+export { REPLICA_INDEX_KEY } from './persistedRows';/*** The engine's view of the host store. The engine never owns the rendered@@ -155,82 +155,10 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(/** Keys with a `loadMore` request in flight (the only valid `isLoadingMore`). */const loadingMore = new Set<string>();- // ---- removal guard ----------------------------------------------------- // An explicit removal (a deleted / unauthorized aggregate, or a subject whose- // attachment is gone) drops the entry AND its persisted row — but a read of- // that row that started before the removal still holds the old value, and a- // removal leaves no trace in the slots for the `hydrate` guard to see. So a- // scope+key is remembered as removed and refuses hydration until a server- // value supersedes it, otherwise the late read resurrects the exact value the- // removal just dropped.- const removedEntries = createTombstones();- /**- * Keys whose persisted row delete was actually queued. `runEffects` refuses to- * write while the scope is untrusted, so a removal made on a cold boot can arm- * the guard without clearing the row. The guard alone must therefore not turn- * a later removal into a no-op, or the stale row would survive and hydrate- * again once the scope becomes trusted.- */- const purgedEntries = createTombstones();- /**- * Bumped on every removal of a scope+key. A network response whose request- * started before the entry was removed (deleted, access revoked, pruned by an- * authoritative parent list) must not `replace` it back: the slice records- * the generation a request starts under and drops a response that crossed a- * removal. Bounded like the tombstones; an evicted key reads 0, which only- * ever drops a response (the next revalidate refetches), never admits one.- */- const removalGenerations = new Map<string, number>();- const removalId = (scope: string, key: string) => `${scope}\u0000${key}`;- const removalGeneration = (scope: string, key: string) =>- removalGenerations.get(removalId(scope, key)) ?? 0;- const markRemoved = (scope: string, key: string) => {- removedEntries.add(scope, key);- const id = removalId(scope, key);- const next = (removalGenerations.get(id) ?? 0) + 1;- // Re-insert so the map's insertion order is least-recently-removed first.- removalGenerations.delete(id);- removalGenerations.set(id, next);- if (removalGenerations.size > DEFAULT_REMOVAL_TOMBSTONE_LIMIT)- removalGenerations.delete(removalGenerations.keys().next().value as string);- };- const clearRemoved = (scope: string, key: string) => {- removedEntries.clear(scope, key);- purgedEntries.clear(scope, key);- };- const isRemoved = (scope: string, key: string) => removedEntries.has(scope, key);- const markPurged = (scope: string, key: string) => purgedEntries.add(scope, key);- const isPurged = (scope: string, key: string) => purgedEntries.has(scope, key);-- // ---- entity removal guards ---------------------------------------------- // A hydrate that read its row before `removeEntity` patched storage still- // holds the entity, so it is stripped from every value that hydrates while- // such a read may be pending. A guard's lifetime follows the hydrates, not a- // count: it is released once its storage patch landed (`releasedAt`) and is- // dropped as soon as no hydrate that started before that point is pending.- // So memory stays bounded by in-flight reads, and no guard a pending read- // still needs is ever evicted. A patch that did not land is never released:- // the unloaded row still holds the entity, so every later hydrate needs the- // guard. A server value holding the entity again (restored) lifts it early.- /** Logical clock shared by hydrate starts and guard releases. */- let guardClock = 0;- /** Start ticks of the hydrates in flight, per scope. */- const pendingHydrates = new Map<string, Set<number>>();- /** Removed entity ids per scope; `releasedAt` is unset until the storage patch landed. */- const removedEntities = new Map<string, Map<string, { releasedAt?: number }>>();- const removedIds = (scope: string) => [...(removedEntities.get(scope)?.keys() ?? [])];-- /** Drop the guards no pending hydrate of `scope` can still need. */- const pruneEntityGuards = (scope: string) => {- const guards = removedEntities.get(scope);- if (!guards) return;- let oldestPending = Infinity;- for (const start of pendingHydrates.get(scope) ?? [])- oldestPending = Math.min(oldestPending, start);- for (const [id, guard] of guards)- if (guard.releasedAt !== undefined && guard.releasedAt <= oldestPending) guards.delete(id);- if (guards.size === 0) removedEntities.delete(scope);- };+ // ---- removal guards (see `removalGuards.ts`) -----------------------------+ const { clearRemoved, isPurged, isRemoved, markPurged, markRemoved, removalGeneration } =+ createRemovalGuards();+ const entityGuards = createEntityRemovalGuards();// ---- resource-wide clear ----------------------------------------------/** Bumped by every `clear()` of a scope; reads started before it are stale. */@@ -254,310 +182,21 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(return options.toPersisted ? options.toPersisted(paged) : paged;};- // ---- persisted-row index ---------------------------------------------- // Storage has no key listing, so each scope keeps an index row of the- // storage keys this resource persisted. Entity changes use it to patch rows- // whose entry is not loaded in memory (e.g. a status update for a list the- // user navigated away from), so a later visit never hydrates a stale value.- const indexKey = (scope: string) => ({ queryKey: REPLICA_INDEX_KEY, scope });- /** Keys known to be in the index row, per scope (skips redundant index writes). */- const indexed = new Map<string, Set<string>>();-- /**- * Latest queued write per row (`scope` + storage key), from one monotonic- * counter. A confirmed delete only takes its key out of the index when no- * later write re-created the row in the meantime.- */- const rowWrites = new Map<string, number>();- let writeCounter = 0;- const rowId = (scope: string, queryKey: string) => `${scope}\u0000${queryKey}`;- const noteWrite = (scope: string, queryKey: string) => {- const seq = ++writeCounter;- rowWrites.set(rowId(scope, queryKey), seq);- return seq;- };-- // ---- last persisted value per row ---------------------------------------- // What this session knows a row holds in storage: the value of its latest- // write once that write is confirmed (`ReplicaStorage.set` resolved), or the- // value read back by a hydrate no write raced. A write still in flight, or one- // that failed, leaves the row unknown. A persist of a- // deep-equal value is skipped — an unchanged revalidation must not rewrite- // the same row. Every path that may change a row behind it (a delete, a- // patch, a clear, an eviction) forgets the row, so the next persist writes.- const storedValues = new Map<string, Map<string, unknown>>();- const rememberStored = (scope: string, queryKey: string, data: unknown) => {- const rows = storedValues.get(scope) ?? new Map<string, unknown>();- storedValues.set(scope, rows);- rows.set(queryKey, data);- };- const forgetStored = (scope: string, queryKeys: Iterable<string>) => {- const rows = storedValues.get(scope);- if (!rows) return;- for (const queryKey of queryKeys) rows.delete(queryKey);- if (rows.size === 0) storedValues.delete(scope);- };- const isStored = (scope: string, queryKey: string, data: unknown) => {- const rows = storedValues.get(scope);- return !!rows?.has(queryKey) && isEqual(rows.get(queryKey), data);- };-- // ---- bounded persisted entries ----------------------------------------- // With `persist.maxEntries`, the index is kept in least-recently-used order- // (oldest first — the order an unbounded index is appended in, so rows an- // earlier release indexed keep their place) and every use of a row moves it- // to the end. Past the cap the oldest rows that nothing pins are evicted.- const maxEntries = resource.maxPersistedEntries;- /** Mounted readers per storage key and per entry key (see `retain`). */- const retainedRows = new Map<string, number>();- const retainedKeys = new Map<string, number>();- /** Rows whose eviction delete is queued, per scope. */- const evicting = new Map<string, Set<string>>();-- const bump = (counts: Map<string, number>, id: string, by: number) => {- const next = (counts.get(id) ?? 0) + by;- if (next > 0) counts.set(id, next);- else counts.delete(id);- };-- /**- * Pin an entry (and the row of the query it asks for) while something shows- * it: eviction never drops a retained row or the memory entry of a retained- * key. `useSync` retains for as long as it is mounted. Returns the release.- */- const retain = (key: string, queryKey: string = replicaStorageKey(key)) => {- bump(retainedKeys, key, 1);- bump(retainedRows, queryKey, 1);- let released = false;- return () => {- if (released) return;- released = true;- bump(retainedKeys, key, -1);- bump(retainedRows, queryKey, -1);- };- };-- /** Rows the memory of `scope` holds, by storage key → entry key. */- const loadedRows = (scope: string) => {- const slot = getSlot();- const rows = new Map<string, string>();- if (slot.scope !== scope) return rows;- for (const [key, entry] of Object.entries(slot.entries))- rows.set(replicaStorageKey(key, entry.query), key);- return rows;- };-- /** A row on screen, or whose entry has writes / a page load in flight. */- const isPinned = (queryKey: string, entryKey: string | undefined) =>- retainedRows.has(queryKey) ||- (entryKey !== undefined &&- (retainedKeys.has(entryKey) ||- (getSlot().entries[entryKey]?.pending.length ?? 0) > 0 ||- loadingMore.has(entryKey)));-- /** The oldest unpinned rows past the cap (`keys` is oldest first). */- const pickEvictions = (scope: string, keys: string[], touched: string): string[] => {- const going = evicting.get(scope);- let excess = keys.length - maxEntries! - keys.filter((key) => going?.has(key)).length;- if (excess <= 0) return [];- const loaded = loadedRows(scope);- const picked: string[] = [];- for (const queryKey of keys) {- if (excess <= 0) break;- if (queryKey === touched || going?.has(queryKey)) continue;- if (isPinned(queryKey, loaded.get(queryKey))) continue;- picked.push(queryKey);- excess -= 1;- }- return picked;- };-- /**- * Evict rows: drop the memory entries that answer them (one commit), then- * delete the rows. A row leaves the index only once its delete landed, so a- * failed eviction is picked again by a later use.- */- const evictRows = (scope: string, queryKeys: string[]) => {- if (resource.scope.get() !== scope || !resource.scope.canPersist()) return;- const going = evicting.get(scope) ?? new Set<string>();- evicting.set(scope, going);- const loaded = loadedRows(scope);- // Re-check: a row may have been pinned since it was picked.- const rows = queryKeys.filter(- (queryKey) => !going.has(queryKey) && !isPinned(queryKey, loaded.get(queryKey)),- );- if (rows.length === 0) return;- for (const queryKey of rows) going.add(queryKey);- const dropped = rows.flatMap((queryKey) => {- const key = loaded.get(queryKey);- return key === undefined ? [] : [key];- });- if (dropped.length > 0) {- const slot = getSlot();- const entries = { ...slot.entries };- for (const key of dropped) delete entries[key];+ // ---- persisted rows (see `persistedRows.ts`) -----------------------------+ const rows = createPersistedRows<TData>({+ commit: (keys, state) =>port.commit(- dropped.map((key) => ({ data: undefined, key })),- { entries, scope },+ keys.map((key) => ({ data: undefined, key })),+ state,`${prefix}/evict`,- );- }- void deleteRows(scope, rows).finally(() => {- for (const queryKey of rows) going.delete(queryKey);- if (going.size === 0 && evicting.get(scope) === going) evicting.delete(scope);- });- };-- /**- * A bounded resource used a row: move it to the end of the index and evict- * past the cap. No-op for an unbounded resource.- */- const touchStorageKey = (scope: string, queryKey: string) => {- if (!writeQueue || maxEntries === undefined) return;- const known = indexed.get(scope) ?? new Set<string>();- indexed.set(scope, known);- known.add(queryKey);- let picked: string[] = [];- void writeQueue- .update(- indexKey(scope),- (current) => {- const keys = (current?.data as unknown as string[] | undefined) ?? [];- const next = [...keys.filter((key) => key !== queryKey), queryKey];- picked = pickEvictions(scope, next, queryKey);- if (keys.length === next.length && keys.at(-1) === queryKey) return undefined;- return { data: next as unknown as TData, updatedAt: Date.now() };- },- { read: 'prefer-strict' },- )- .then((touched) => {- // Unreadable index: leave it untouched, retry the append on the next use.- if (!touched) return void known.delete(queryKey);- if (picked.length > 0) evictRows(scope, picked);- });- };-- /** Record a persisted row in the index (queued after the row write). */- const trackStorageKey = (scope: string, queryKey: string) => {- if (!writeQueue) return;- noteWrite(scope, queryKey);- if (maxEntries !== undefined) return touchStorageKey(scope, queryKey);- const known = indexed.get(scope) ?? new Set<string>();- indexed.set(scope, known);- if (known.has(queryKey)) return;- known.add(queryKey);- void writeQueue- .update(- indexKey(scope),- (current) => {- const keys = new Set((current?.data as unknown as string[] | undefined) ?? []);- if (keys.has(queryKey)) return undefined;- keys.add(queryKey);- return { data: [...keys] as unknown as TData, updatedAt: Date.now() };- },- { read: 'prefer-strict' },- )- // An unreadable index is left untouched (never rewritten as just this- // key); forget the key so the next write of the row retries the append.- .then((tracked) => {- if (!tracked) known.delete(queryKey);- });- };-- /**- * Read the index for a destructive pass (remove / clear / entity patch).- * Uses the storage's strict read when it has one, so an unreadable index- * rejects instead of looking empty — a purge must never report success for- * rows it could not enumerate.- */- const readIndex = async (scope: string): Promise<string[]> => {- // A storage without `getStrict` rejects here: its `get` cannot tell an- // unreadable index from an empty one.- const row = await readReplicaRowStrict(resource.storage!, indexKey(scope));- return (row?.data as unknown as string[] | undefined) ?? [];- };-- /**- * Drop storage keys from the index (both the session's view of it and the- * persisted row, which may list keys this session never wrote).- */- const untrackStorageKeys = (scope: string, queryKeys: string[]) => {- if (!writeQueue || queryKeys.length === 0) return;- const known = indexed.get(scope);- for (const queryKey of queryKeys) known?.delete(queryKey);- const dropped = new Set(queryKeys);- writeQueue.update(- indexKey(scope),- (current) => {- const keys = (current?.data as unknown as string[] | undefined) ?? [];- const next = keys.filter((queryKey) => !dropped.has(queryKey));- if (!current || next.length === keys.length) return undefined;- return { data: next as unknown as TData, updatedAt: Date.now() };- },- { read: 'prefer-strict' },- );- };-- /** Take rows whose delete landed out of the index, unless rewritten since. */- const confirmDeleted = (scope: string, deleted: [queryKey: string, seq: number][]) => {- const gone = deleted- .filter(([queryKey, seq]) => rowWrites.get(rowId(scope, queryKey)) === seq)- .map(([queryKey]) => queryKey);- for (const queryKey of gone) rowWrites.delete(rowId(scope, queryKey));- untrackStorageKeys(scope, gone);- };-- /**- * Queue row deletes now (ordered before any later write to the same rows).- * A key leaves the index only once its delete is confirmed: a failed delete- * stays indexed, so the next `remove` / `clear` finds and retries it.- * Resolves `true` when every delete landed.- */- const deleteRows = (scope: string, queryKeys: string[]): Promise<boolean> => {- const queue = writeQueue!;- forgetStored(scope, queryKeys);- const queued = queryKeys.map((queryKey) => {- const seq = noteWrite(scope, queryKey);- return queue- .remove({ queryKey, scope })- .then((removed): [string, number] | undefined => (removed ? [queryKey, seq] : undefined));- });- return Promise.all(queued).then((results) => {- confirmDeleted(- scope,- results.filter((result): result is [string, number] => !!result),- );- return results.every(Boolean);- });- };-- /**- * Delete every persisted row of entry `key` in `scope` — `current` (the row- * memory knows about, queued right away so it orders before any later write)- * plus every other query variant the index lists. Resolves `true` once all- * deletes landed.- */- const removeStoredVariants = (scope: string, key: string, current: string) => {- const first = deleteRows(scope, [current]);- const rest = readIndex(scope).then(- (persisted) => {- // A server value that superseded the removal while the index was read- // owns its (fresh) row: keep it, delete only the stale variants.- const slot = getSlot();- const live = !isRemoved(scope, key) && slot.scope === scope ? slot.entries[key] : undefined;- const liveKey = live && replicaStorageKey(key, live.query);- const variants = new Set(- [...(indexed.get(scope) ?? []), ...persisted].filter(- (queryKey) =>- queryKey !== current && queryKey !== liveKey && isReplicaStorageKeyOf(queryKey, key),- ),- );- return variants.size === 0 ? true : deleteRows(scope, [...variants]);- },- () => false,- );- return Promise.all([first, rest]).then((results) => results.every(Boolean));- };+ ),+ getSlot,+ isRemoved,+ loadingMore,+ resource,+ writeQueue,+ });+ const { deleteRows, readIndex, removeStoredVariants, retain, touchStorageKey } = rows;const runEffects = (effects: ReplicaEffect<TData>[]) => {if (!writeQueue || effects.length === 0) return;@@ -587,23 +226,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(void deleteRows(effect.scope, [key.queryKey]);continue;}- // The row already holds this value: an unchanged revalidation is no write.- if (isStored(effect.scope, key.queryKey, data)) {- touchStorageKey(effect.scope, key.queryKey);- continue;- }- // Until this write is confirmed the row's content is unknown: forget what- // it held, and only remember `data` once the write observably landed and- // is still the latest queued for the row. A failed (or best-effort,- // silently dropped) write therefore never makes a later identical persist- // look redundant — that one writes again.- forgetStored(effect.scope, [key.queryKey]);- trackStorageKey(effect.scope, key.queryKey);- const id = rowId(effect.scope, key.queryKey);- const seq = rowWrites.get(id);- void writeQueue.set(key, { data, updatedAt: Date.now() }).then((written) => {- if (written && rowWrites.get(id) === seq) rememberStored(effect.scope, key.queryKey, data);- });+ rows.writeRow(effect.scope, key.queryKey, data);}};@@ -650,7 +273,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(const read = (key: string) => readThrough(writes, key);if (slot.scope !== undefined && slot.scope !== activeScope) {// Memory moves to another identity; what we knew of its rows can go.- storedValues.delete(slot.scope);+ rows.forgetScope(slot.scope);const reset = replicaReducer(slot, { scope: activeScope, type: 'resetScope' }, read);writes.push(...reset.writes);slot = reset.state;@@ -724,16 +347,11 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(// the removal (see `replace`), so a stale row can never repaint it.if (isRemoved(scope, key)) return false;// Pending until settled: entity guards outlive every read that may hold them.- const start = ++guardClock;- const pending = pendingHydrates.get(scope) ?? new Set<number>();- pendingHydrates.set(scope, pending);- pending.add(start);+ const settle = entityGuards.startHydrate(scope);try {return await readAndHydrate(params, key, scope, overwrite);} finally {- pending.delete(start);- if (pending.size === 0) pendingHydrates.delete(scope);- pruneEntityGuards(scope);+ settle();}};@@ -751,15 +369,14 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(if (purge && !(await purge)) return false;const query = resource.query(params);const { queryKey } = storageKey(key, query);- const writesBefore = writeCounter;+ const writesBefore = rows.writeCount();const cached = await storage.get({ queryKey, scope });if (!cached) return false;// Re-check after the read: a removal or a clear that landed while it was in// flight must not resurrect the row it just dropped.if (isRemoved(scope, key) || clearGeneration(scope) !== generation) return false;// The row holds what was read, unless a write was queued while reading.- if (writeCounter === writesBefore && !storedValues.get(scope)?.has(queryKey))- rememberStored(scope, queryKey, cached.data);+ rows.rememberRead(scope, queryKey, cached.data, writesBefore);if (options.isHydratable && !options.isHydratable(cached.data, params)) return false;// Entities deleted while the read was in flight may still be in the row.const stored = withoutRemovedEntities(scope, cached.data);@@ -986,7 +603,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(const scope = resource.scope.get();clearGenerations.set(scope, clearGeneration(scope) + 1);port.commit([{ type: 'clear' }], { entries: {}, scope }, `${prefix}/clear`);- storedValues.delete(scope);+ rows.forgetScope(scope);const purge = purgeScope(scope);scopePurges.set(scope, purge);return purge;@@ -1017,7 +634,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(// Until identity resolves the scope is a guess; never write into it.if (!resource.scope.canPersist()) return false;// Rows this session knows about are queued now, ahead of any later write.- const queued = deleteRows(scope, [...(indexed.get(scope) ?? [])]);+ const queued = deleteRows(scope, [...(rows.indexedKeys(scope) ?? [])]);let persisted: string[];try {persisted = await readIndex(scope);@@ -1026,7 +643,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(}// Keys this session tracks are already queued above, or were written by a// newer response since the clear (their row is fresh): skip both.- const known = indexed.get(scope);+ const known = rows.indexedKeys(scope);const stale = persisted.filter((queryKey) => !known?.has(queryKey));const [first, rest] = await Promise.all([queued, deleteRows(scope, stale)]);return first && rest;@@ -1162,330 +779,29 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(}): false;- // ---- entity propagation ------------------------------------------------- const entityKeys = (id: string): string[] => {- const keys = port.keys?.() ?? Object.keys(getSlot().entries);- return keys.filter((key) => {- const data = port.read(key);- if (data === undefined) return false;- if (paging) return hasPagedItem(data as any, id, paging);- return options.entity ? options.entity.has(data, id) : false;- });- };-- /** Map one entity inside a value; `undefined` means the whole value goes away. */- const mapEntity = <TItem>(- data: TData,- id: string,- fn: (item: TItem) => TItem | undefined,- ): TData | undefined => {- if (paging) return mapPagedItem(data as any, id, fn as any, paging) as TData;- const entity = options.entity;- if (!entity || !entity.has(data, id)) return data;- return entity.map(data, id, fn);- };-- /** Which of `ids` are held by `data`. */- const heldEntities = (data: TData, ids: string[]): string[] => {- if (paging) {- const items = (data as unknown as ReplicaPagedData<unknown, unknown>).items ?? [];- const present = new Set(items.map((item) => paging.getId(item)));- return ids.filter((id) => present.has(id));- }- const entity = options.entity;- return entity ? ids.filter((id) => entity.has(data, id)) : [];- };-- /** Strip entities removed in `scope` from a value read back from storage. */- const withoutRemovedEntities = (scope: string, data: TData): TData | undefined => {- const removed = removedIds(scope);- if (removed.length === 0) return data;- let next: TData | undefined = data;- for (const id of heldEntities(data, removed)) {- next = mapEntity(next!, id, () => undefined);- if (next === undefined) break;- }- return next;- };-- /** A server value holding a removed entity again (restored) lifts its guard. */- const forgetRestoredEntities = (scope: string, data: TData | undefined) => {- const removed = removedIds(scope);- if (removed.length === 0 || data === undefined) return;- const guards = removedEntities.get(scope)!;- for (const id of heldEntities(data, removed)) guards.delete(id);- if (guards.size === 0) removedEntities.delete(scope);- };-- /**- * Apply an entity change to persisted rows that memory does not hold (the- * memory path already persists loaded entries). Read-modify-write runs in- * the per-key write queue, so it sees every earlier write; a missing row is- * never recreated. Resolves once the patches have settled: `true` when every- * unloaded row is known to be patched (or nothing is persisted), `false` when- * a row may still hold the old entity (untrusted scope, unreadable index or- * row, a failed write, an identity switch mid-pass).- */- const patchStoredEntityRows = async <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- scope: string = resource.scope.get(),- ): Promise<boolean> => {- if (!writeQueue) return true;- if (!resource.scope.canPersist()) return false;- // A scope left behind is patched on purpose: nothing of it is loaded, and an- // identity switch while reading its index does not make its rows foreign.- const offScope = scope !== resource.scope.get();- const slot = getSlot();- // Rows memory holds are patched through memory — but only in the active- // scope; a view still showing a scope left behind is not what it persists.- const loaded = new Set(- !offScope && slot.scope === scope- ? Object.entries(slot.entries).map(([key, entry]) => storageKey(key, entry.query).queryKey)- : [],- );- let keys: string[];- try {- keys = await readIndex(scope);- } catch (error) {- // Rows cannot be enumerated: nothing to patch. Loaded entries are already- // updated, and a removal keeps guarding later hydrates (`removeEntity`).- console.error(`[replica:${resource.name}] failed to read the persisted index`, error);- return false;- }- // Identity changed while reading the index: those rows are not ours to touch.- if (!offScope && resource.scope.get() !== scope) return false;- // Rows this session wrote to the scope may not be in the persisted index yet- // (their row or index write is still queued — e.g. just before an account- // switch). Patch them too: each patch is queued behind the row's own write,- // so it reads the row once that write landed.- for (const queryKey of indexed.get(scope) ?? [])- if (!keys.includes(queryKey)) keys.push(queryKey);- const patches: Promise<boolean>[] = [];- for (const queryKey of keys) {- if (loaded.has(queryKey)) continue;- const seq = noteWrite(scope, queryKey);- forgetStored(scope, [queryKey]);- let dropped = false;- const patch = writeQueue- .update(- { queryKey, scope },- (current) => {- if (!current) return undefined;- const next = mapEntity(current.data, id, fn);- if (next === current.data) return undefined;- if (next === undefined) {- dropped = true;- return null;- }- return { data: next, updatedAt: Date.now() };- },- { read: 'strict' },- )- .then((written) => {- if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);- return written;- });- patches.push(patch);- }- return (await Promise.all(patches)).every(Boolean);- };-- const patchStoredEntity = async <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- ): Promise<void> => {- await patchStoredEntityRows(id, fn);- };-- /**- * Read-modify-write the persisted rows memory does not hold, keyed by row- * rather than by entity: a cached list for a folder the user is not viewing- * gets its projection patched in the per-key write queue, so a later visit- * hydrates the reconciled value instead of a stale page. `fn` returns the- * next data, the same reference (or `undefined`) to skip, or `null` to drop- * the row. Runs in the write queue, so it sees every earlier write.- */- const patchStoredRows = async (fn: (data: TData) => TData | null | undefined): Promise<void> => {- if (!writeQueue || !resource.scope.canPersist()) return;- const scope = resource.scope.get();- const slot = getSlot();- const loaded = new Set(- slot.scope === scope- ? Object.entries(slot.entries).map(([key, entry]) => storageKey(key, entry.query).queryKey)- : [],- );- let keys: string[];- try {- keys = await readIndex(scope);- } catch (error) {- console.error(`[replica:${resource.name}] failed to read the persisted index`, error);- return;- }- // Identity changed while reading the index: those rows are not ours to touch.- if (resource.scope.get() !== scope) return;- const patches: Promise<void>[] = [];- for (const queryKey of keys) {- if (loaded.has(queryKey)) continue;- const seq = noteWrite(scope, queryKey);- forgetStored(scope, [queryKey]);- let dropped = false;- const patch = writeQueue- .update(- { queryKey, scope },- (current) => {- if (!current) return undefined;- const next = fn(current.data);- if (next === current.data || next === undefined) return undefined;- if (next === null) {- dropped = true;- return null;- }- return { data: next, updatedAt: Date.now() };- },- { read: 'strict' },- )- .then((written) => {- if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);- });- patches.push(patch);- }- await Promise.all(patches);- };-- /**- * `updateEntity`, returning the persisted-row patch (if any) to wait on —- * `true` once every unloaded row is patched.- */- const applyEntity = <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- { persist = true }: { persist?: boolean } = {},- ): Promise<boolean> | undefined => {- const patch = persist ? patchStoredEntityRows(id, fn) : undefined;- for (const key of entityKeys(id)) {- const current = port.read(key);- if (current === undefined) continue;- const next = mapEntity(current, id, fn);- if (next === undefined) remove(key);- else- update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {- persist,- });- }- return patch;- };-- /**- * An entity patch started for a scope that was not active settled. If the- * user switched back to that scope meanwhile, an entry may have hydrated the- * pre-patch row before the patch landed: apply the same change to what is- * loaded now, in memory only — storage already holds it.- */- const reconcileLoaded = <TItem>(- scope: string,- id: string,- fn: (item: TItem) => TItem | undefined,- ) => {- if (resource.scope.get() !== scope || getSlot().scope !== scope) return;- for (const key of entityKeys(id)) {- const current = port.read(key);- if (current === undefined) continue;- // A hydrate during the patch may have recorded the pre-patch row as stored.- forgetStored(scope, [storageKey(key, getSlot().entries[key]?.query).queryKey]);- if (mapEntity(current, id, fn) === undefined) remove(key);- else- update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {- persist: false,- });- }- };-- /**- * Confirmed patch of one entity everywhere it is loaded and in the persisted- * rows of unloaded entries. `scope` targets a scope captured earlier (a- * write confirmed after the account switched): when it is no longer active,- * only that scope's persisted rows are patched and the view on screen —- * another identity's — is left alone.- */- const updateEntity = <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- options?: { persist?: boolean; scope?: string },- ) => {- if (options?.scope !== undefined && options.scope !== resource.scope.get()) {- const scope = options.scope;- if (options.persist === false) return;- const settle = () => reconcileLoaded(scope, id, fn);- void patchStoredEntityRows(id, fn, scope).then(settle, settle);- return;- }- void applyEntity(id, fn, options);- };-- /**- * Confirmed removal of one entity everywhere (see `updateEntity`, including- * its captured `scope`). Unlike a plain mapper returning `undefined`, it is- * also remembered for that scope:- * a value hydrated afterwards — even by a read already in flight — comes- * back without the entity (see `removedEntities`).- */- const removeEntity = (id: string, options?: { persist?: boolean; scope?: string }) => {- const scope = options?.scope ?? resource.scope.get();- // A removal confirmed after the account switched belongs to the scope that- // asked for it: guard and patch that scope's rows, never the active view.- const offScope = scope !== resource.scope.get();- const guard: { releasedAt?: number } = {};- const guards = removedEntities.get(scope) ?? new Map<string, { releasedAt?: number }>();- removedEntities.set(scope, guards);- guards.set(id, guard);- const release = () => {- // A newer removal of the same id owns the slot now.- if (guards.get(id) !== guard) return;- guard.releasedAt = ++guardClock;- pruneEntityGuards(scope);- };- // A scope left behind has nothing on screen: only its persisted rows drop- // the entity, and the guard keeps a later hydrate there from reading it back.- const patch = offScope- ? options?.persist === false- ? undefined- : patchStoredEntityRows(id, () => undefined, scope).then((patched) => {- // Switched back meanwhile: drop it from anything hydrated since.- reconcileLoaded(scope, id, () => undefined);- return patched;- })- : applyEntity(id, () => undefined, options);- // Without a storage patch (`persist: false`) only reads already in flight- // can hold the entity; with one, reads that start before it lands can too.- // A patch that did not land (untrusted scope, unreadable index or row, a- // failed write, an identity switch) leaves the entity in an unloaded row:- // every later hydrate of that row could resurrect it, so the guard is kept- // — until a server value holds the entity again, or a later removal of the- // same id lands its patch.- if (patch)- void patch.then(- (patched) => {- if (patched) release();- },- () => undefined,- );- else release();- };-- const beginEntityOptimistic = <TItem>(- id: string,- fn: (item: TItem) => TItem | undefined,- ): ReplicaOptimisticToken<TData>[] =>- entityKeys(id).flatMap((key) => {- // Removing a whole value (a detail) is applied on commit, not optimistically.- if (!paging) {- const current = port.read(key);- if (current !== undefined && mapEntity(current, id, fn) === undefined) return [];- }- return [beginOptimistic(key, (data) => mapEntity(data, id, fn) ?? data)];- });+ // ---- entity propagation (see `entityPropagation.ts`) ---------------------+ const entities = createEntityPropagation<TData>({+ beginOptimistic,+ entity: options.entity,+ entityGuards,+ getSlot,+ paging,+ port,+ remove,+ resource,+ rows,+ update,+ });+ const {+ beginEntityOptimistic,+ entityKeys,+ forgetRestoredEntities,+ patchStoredEntity,+ removeEntity,+ updateEntity,+ withoutRemovedEntities,+ } = entities;+ const { patchStoredRows } = rows;return {applyHead,diff --git a/packages/replica/src/core/entityPropagation.ts b/packages/replica/src/core/entityPropagation.tsnew file mode 100644index 00000000000..ffc3062acab--- /dev/null+++ b/packages/replica/src/core/entityPropagation.ts@@ -0,0 +1,296 @@+import { replicaStorageKey } from './defineReplica';+import type { ReplicaEntityAdapter, ReplicaOptimisticToken, ReplicaStorePort } from './engine';+import {+ hasPagedItem,+ mapPagedItem,+ type ReplicaPagedData,+ type ReplicaPagingConfig,+} from './paging';+import { DROP_ROW, type ReplicaPersistedRows } from './persistedRows';+import type { ReplicaEntityRemovalGuards } from './removalGuards';+import type { ReplicaResource, ReplicaSource, ReplicaState } from './types';++export interface ReplicaEntityPropagationDeps<TData> {+ beginOptimistic: (key: string, apply: (data: TData) => TData) => ReplicaOptimisticToken<TData>;+ /** Non-paged resources: how entities sit in the value. */+ entity?: ReplicaEntityAdapter<TData, any>;+ entityGuards: ReplicaEntityRemovalGuards;+ getSlot: () => ReplicaState<TData>;+ paging?: ReplicaPagingConfig<any, any>;+ port: ReplicaStorePort<TData>;+ remove: (key: string) => boolean;+ resource: ReplicaResource<any, TData, any>;+ rows: ReplicaPersistedRows<TData>;+ update: (+ key: string,+ apply: (data: TData | undefined) => TData | undefined,+ options?: { persist?: boolean; seedTag?: string; source?: ReplicaSource },+ ) => boolean;+}++/**+ * Entity propagation: a change to one entity (e.g. a topic) applied to every+ * entry that holds it — in memory, in persisted rows memory does not hold,+ * and in rows a hydrate reads back while a removal is still landing.+ */+export const createEntityPropagation = <TData>({+ beginOptimistic,+ entity,+ entityGuards,+ getSlot,+ paging,+ port,+ remove,+ resource,+ rows,+ update,+}: ReplicaEntityPropagationDeps<TData>) => {+ const entityKeys = (id: string): string[] => {+ const keys = port.keys?.() ?? Object.keys(getSlot().entries);+ return keys.filter((key) => {+ const data = port.read(key);+ if (data === undefined) return false;+ if (paging) return hasPagedItem(data as any, id, paging);+ return entity ? entity.has(data, id) : false;+ });+ };++ /** Map one entity inside a value; `undefined` means the whole value goes away. */+ const mapEntity = <TItem>(+ data: TData,+ id: string,+ fn: (item: TItem) => TItem | undefined,+ ): TData | undefined => {+ if (paging) return mapPagedItem(data as any, id, fn as any, paging) as TData;+ if (!entity || !entity.has(data, id)) return data;+ return entity.map(data, id, fn);+ };++ /** Which of `ids` are held by `data`. */+ const heldEntities = (data: TData, ids: string[]): string[] => {+ if (paging) {+ const items = (data as unknown as ReplicaPagedData<unknown, unknown>).items ?? [];+ const present = new Set(items.map((item) => paging.getId(item)));+ return ids.filter((id) => present.has(id));+ }+ return entity ? ids.filter((id) => entity.has(data, id)) : [];+ };++ /** Strip entities removed in `scope` from a value read back from storage. */+ const withoutRemovedEntities = (scope: string, data: TData): TData | undefined => {+ const removed = entityGuards.removedIds(scope);+ if (removed.length === 0) return data;+ let next: TData | undefined = data;+ for (const id of heldEntities(data, removed)) {+ next = mapEntity(next!, id, () => undefined);+ if (next === undefined) break;+ }+ return next;+ };++ /** A server value holding a removed entity again (restored) lifts its guard. */+ const forgetRestoredEntities = (scope: string, data: TData | undefined) => {+ const removed = entityGuards.removedIds(scope);+ if (removed.length === 0 || data === undefined) return;+ entityGuards.liftEntityGuards(scope, heldEntities(data, removed));+ };++ /**+ * Apply an entity change to persisted rows that memory does not hold (the+ * memory path already persists loaded entries). Read-modify-write runs in+ * the per-key write queue, so it sees every earlier write; a missing row is+ * never recreated. Resolves once the patches have settled: `true` when every+ * unloaded row is known to be patched (or nothing is persisted), `false` when+ * a row may still hold the old entity (untrusted scope, unreadable index or+ * row, a failed write, an identity switch mid-pass).+ */+ const patchStoredEntityRows = async <TItem>(+ id: string,+ fn: (item: TItem) => TItem | undefined,+ scope: string = resource.scope.get(),+ ): Promise<boolean> => {+ if (!resource.storage) return true;+ if (!resource.scope.canPersist()) return false;+ // A scope left behind is patched on purpose: nothing of it is loaded, and an+ // identity switch while reading its index does not make its rows foreign.+ const offScope = scope !== resource.scope.get();+ const slot = getSlot();+ // Rows memory holds are patched through memory — but only in the active+ // scope; a view still showing a scope left behind is not what it persists.+ const loaded = new Set(+ !offScope && slot.scope === scope+ ? Object.entries(slot.entries).map(([key, entry]) => replicaStorageKey(key, entry.query))+ : [],+ );+ let keys: string[];+ try {+ keys = await rows.readIndex(scope);+ } catch (error) {+ // Rows cannot be enumerated: nothing to patch. Loaded entries are already+ // updated, and a removal keeps guarding later hydrates (`removeEntity`).+ console.error(`[replica:${resource.name}] failed to read the persisted index`, error);+ return false;+ }+ // Identity changed while reading the index: those rows are not ours to touch.+ if (!offScope && resource.scope.get() !== scope) return false;+ // Rows this session wrote to the scope may not be in the persisted index yet+ // (their row or index write is still queued — e.g. just before an account+ // switch). Patch them too: each patch is queued behind the row's own write,+ // so it reads the row once that write landed.+ for (const queryKey of rows.indexedKeys(scope) ?? [])+ if (!keys.includes(queryKey)) keys.push(queryKey);+ const patches: Promise<boolean>[] = [];+ for (const queryKey of keys) {+ if (loaded.has(queryKey)) continue;+ patches.push(+ rows.patchRow(scope, queryKey, (data) => {+ const next = mapEntity(data, id, fn);+ if (next === data) return undefined;+ return next === undefined ? DROP_ROW : next;+ }),+ );+ }+ return (await Promise.all(patches)).every(Boolean);+ };++ const patchStoredEntity = async <TItem>(+ id: string,+ fn: (item: TItem) => TItem | undefined,+ ): Promise<void> => {+ await patchStoredEntityRows(id, fn);+ };++ /**+ * `updateEntity`, returning the persisted-row patch (if any) to wait on —+ * `true` once every unloaded row is patched.+ */+ const applyEntity = <TItem>(+ id: string,+ fn: (item: TItem) => TItem | undefined,+ { persist = true }: { persist?: boolean } = {},+ ): Promise<boolean> | undefined => {+ const patch = persist ? patchStoredEntityRows(id, fn) : undefined;+ for (const key of entityKeys(id)) {+ const current = port.read(key);+ if (current === undefined) continue;+ const next = mapEntity(current, id, fn);+ if (next === undefined) remove(key);+ else+ update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {+ persist,+ });+ }+ return patch;+ };++ /**+ * An entity patch started for a scope that was not active settled. If the+ * user switched back to that scope meanwhile, an entry may have hydrated the+ * pre-patch row before the patch landed: apply the same change to what is+ * loaded now, in memory only — storage already holds it.+ */+ const reconcileLoaded = <TItem>(+ scope: string,+ id: string,+ fn: (item: TItem) => TItem | undefined,+ ) => {+ if (resource.scope.get() !== scope || getSlot().scope !== scope) return;+ for (const key of entityKeys(id)) {+ const current = port.read(key);+ if (current === undefined) continue;+ // A hydrate during the patch may have recorded the pre-patch row as stored.+ rows.forgetStored(scope, [replicaStorageKey(key, getSlot().entries[key]?.query)]);+ if (mapEntity(current, id, fn) === undefined) remove(key);+ else+ update(key, (data) => (data === undefined ? data : (mapEntity(data, id, fn) ?? data)), {+ persist: false,+ });+ }+ };++ /**+ * Confirmed patch of one entity everywhere it is loaded and in the persisted+ * rows of unloaded entries. `scope` targets a scope captured earlier (a+ * write confirmed after the account switched): when it is no longer active,+ * only that scope's persisted rows are patched and the view on screen —+ * another identity's — is left alone.+ */+ const updateEntity = <TItem>(+ id: string,+ fn: (item: TItem) => TItem | undefined,+ options?: { persist?: boolean; scope?: string },+ ) => {+ if (options?.scope !== undefined && options.scope !== resource.scope.get()) {+ const scope = options.scope;+ if (options.persist === false) return;+ const settle = () => reconcileLoaded(scope, id, fn);+ void patchStoredEntityRows(id, fn, scope).then(settle, settle);+ return;+ }+ void applyEntity(id, fn, options);+ };++ /**+ * Confirmed removal of one entity everywhere (see `updateEntity`, including+ * its captured `scope`). Unlike a plain mapper returning `undefined`, it is+ * also remembered for that scope:+ * a value hydrated afterwards — even by a read already in flight — comes+ * back without the entity (see `createEntityRemovalGuards`).+ */+ const removeEntity = (id: string, options?: { persist?: boolean; scope?: string }) => {+ const scope = options?.scope ?? resource.scope.get();+ // A removal confirmed after the account switched belongs to the scope that+ // asked for it: guard and patch that scope's rows, never the active view.+ const offScope = scope !== resource.scope.get();+ const release = entityGuards.guardEntity(scope, id);+ // A scope left behind has nothing on screen: only its persisted rows drop+ // the entity, and the guard keeps a later hydrate there from reading it back.+ const patch = offScope+ ? options?.persist === false+ ? undefined+ : patchStoredEntityRows(id, () => undefined, scope).then((patched) => {+ // Switched back meanwhile: drop it from anything hydrated since.+ reconcileLoaded(scope, id, () => undefined);+ return patched;+ })+ : applyEntity(id, () => undefined, options);+ // Without a storage patch (`persist: false`) only reads already in flight+ // can hold the entity; with one, reads that start before it lands can too.+ // A patch that did not land (untrusted scope, unreadable index or row, a+ // failed write, an identity switch) leaves the entity in an unloaded row:+ // every later hydrate of that row could resurrect it, so the guard is kept+ // — until a server value holds the entity again, or a later removal of the+ // same id lands its patch.+ if (patch)+ void patch.then(+ (patched) => {+ if (patched) release();+ },+ () => undefined,+ );+ else release();+ };++ const beginEntityOptimistic = <TItem>(+ id: string,+ fn: (item: TItem) => TItem | undefined,+ ): ReplicaOptimisticToken<TData>[] =>+ entityKeys(id).flatMap((key) => {+ // Removing a whole value (a detail) is applied on commit, not optimistically.+ if (!paging) {+ const current = port.read(key);+ if (current !== undefined && mapEntity(current, id, fn) === undefined) return [];+ }+ return [beginOptimistic(key, (data) => mapEntity(data, id, fn) ?? data)];+ });++ return {+ beginEntityOptimistic,+ entityKeys,+ forgetRestoredEntities,+ patchStoredEntity,+ removeEntity,+ updateEntity,+ withoutRemovedEntities,+ };+};diff --git a/packages/replica/src/core/persistedRows.ts b/packages/replica/src/core/persistedRows.tsnew file mode 100644index 00000000000..add218b1cb9--- /dev/null+++ b/packages/replica/src/core/persistedRows.ts@@ -0,0 +1,468 @@+import isEqual from 'fast-deep-equal';++import { isReplicaStorageKeyOf, replicaStorageKey } from './defineReplica';+import type { ReplicaResource, ReplicaState } from './types';+import { readReplicaRowStrict, type ReplicaWriteQueue } from './writeQueue';++/** Reserved storage key of the per-scope index of persisted rows. */+export const REPLICA_INDEX_KEY = '__replica:index';++export interface ReplicaPersistedRowsDeps<TData> {+ /** Drop evicted entries from the host view (one commit). */+ commit: (keys: string[], state: ReplicaState<TData>) => void;+ getSlot: () => ReplicaState<TData>;+ /** Whether `scope`/`key` is guarded as removed (see `createRemovalGuards`). */+ isRemoved: (scope: string, key: string) => boolean;+ /** Keys with a `loadMore` request in flight (pinned against eviction). */+ loadingMore: ReadonlySet<string>;+ resource: ReplicaResource<any, TData, any>;+ writeQueue: ReplicaWriteQueue<TData> | undefined;+}++/** Returned by a `patchRow` transform to delete the row (`null` stays a value). */+export const DROP_ROW = Symbol('replica.dropRow');++/**+ * Bookkeeping of the rows one engine persisted: the per-scope index, the latest+ * queued write per row, what each row is known to hold, and the bounded+ * (`persist.maxEntries`) eviction. Every row write and delete of the engine+ * goes through here, so the index never misses or resurrects a row.+ */+export const createPersistedRows = <TData>({+ commit,+ getSlot,+ isRemoved,+ loadingMore,+ resource,+ writeQueue,+}: ReplicaPersistedRowsDeps<TData>) => {+ // ---- persisted-row index ---------------------------------------------+ // Storage has no key listing, so each scope keeps an index row of the+ // storage keys this resource persisted. Entity changes use it to patch rows+ // whose entry is not loaded in memory (e.g. a status update for a list the+ // user navigated away from), so a later visit never hydrates a stale value.+ const indexKey = (scope: string) => ({ queryKey: REPLICA_INDEX_KEY, scope });+ /** Keys known to be in the index row, per scope (skips redundant index writes). */+ const indexed = new Map<string, Set<string>>();+ const indexedKeys = (scope: string) => indexed.get(scope);++ /**+ * Latest queued write per row (`scope` + storage key), from one monotonic+ * counter. A confirmed delete only takes its key out of the index when no+ * later write re-created the row in the meantime.+ */+ const rowWrites = new Map<string, number>();+ let writeCounter = 0;+ const writeCount = () => writeCounter;+ const rowId = (scope: string, queryKey: string) => `${scope}\u0000${queryKey}`;+ const noteWrite = (scope: string, queryKey: string) => {+ const seq = ++writeCounter;+ rowWrites.set(rowId(scope, queryKey), seq);+ return seq;+ };++ // ---- last persisted value per row ---------------------------------------+ // What this session knows a row holds in storage: the value of its latest+ // write once that write is confirmed (`ReplicaStorage.set` resolved), or the+ // value read back by a hydrate no write raced. A write still in flight, or one+ // that failed, leaves the row unknown. A persist of a+ // deep-equal value is skipped — an unchanged revalidation must not rewrite+ // the same row. Every path that may change a row behind it (a delete, a+ // patch, a clear, an eviction) forgets the row, so the next persist writes.+ const storedValues = new Map<string, Map<string, unknown>>();+ const rememberStored = (scope: string, queryKey: string, data: unknown) => {+ const rows = storedValues.get(scope) ?? new Map<string, unknown>();+ storedValues.set(scope, rows);+ rows.set(queryKey, data);+ };+ const forgetStored = (scope: string, queryKeys: Iterable<string>) => {+ const rows = storedValues.get(scope);+ if (!rows) return;+ for (const queryKey of queryKeys) rows.delete(queryKey);+ if (rows.size === 0) storedValues.delete(scope);+ };+ /** Forget every row of `scope` (memory moved to another identity, or a clear). */+ const forgetScope = (scope: string) => {+ storedValues.delete(scope);+ };+ const isStored = (scope: string, queryKey: string, data: unknown) => {+ const rows = storedValues.get(scope);+ return !!rows?.has(queryKey) && isEqual(rows.get(queryKey), data);+ };+ /**+ * A hydrate read `data` back from the row: the row holds it, unless a write+ * was queued while reading (`writesBefore` is `writeCount()` before the read).+ */+ const rememberRead = (scope: string, queryKey: string, data: unknown, writesBefore: number) => {+ if (writeCounter === writesBefore && !storedValues.get(scope)?.has(queryKey))+ rememberStored(scope, queryKey, data);+ };++ // ---- bounded persisted entries ----------------------------------------+ // With `persist.maxEntries`, the index is kept in least-recently-used order+ // (oldest first — the order an unbounded index is appended in, so rows an+ // earlier release indexed keep their place) and every use of a row moves it+ // to the end. Past the cap the oldest rows that nothing pins are evicted.+ const maxEntries = resource.maxPersistedEntries;+ /** Mounted readers per storage key and per entry key (see `retain`). */+ const retainedRows = new Map<string, number>();+ const retainedKeys = new Map<string, number>();+ /** Rows whose eviction delete is queued, per scope. */+ const evicting = new Map<string, Set<string>>();++ const bump = (counts: Map<string, number>, id: string, by: number) => {+ const next = (counts.get(id) ?? 0) + by;+ if (next > 0) counts.set(id, next);+ else counts.delete(id);+ };++ /**+ * Pin an entry (and the row of the query it asks for) while something shows+ * it: eviction never drops a retained row or the memory entry of a retained+ * key. `useSync` retains for as long as it is mounted. Returns the release.+ */+ const retain = (key: string, queryKey: string = replicaStorageKey(key)) => {+ bump(retainedKeys, key, 1);+ bump(retainedRows, queryKey, 1);+ let released = false;+ return () => {+ if (released) return;+ released = true;+ bump(retainedKeys, key, -1);+ bump(retainedRows, queryKey, -1);+ };+ };++ /** Rows the memory of `scope` holds, by storage key → entry key. */+ const loadedRows = (scope: string) => {+ const slot = getSlot();+ const rows = new Map<string, string>();+ if (slot.scope !== scope) return rows;+ for (const [key, entry] of Object.entries(slot.entries))+ rows.set(replicaStorageKey(key, entry.query), key);+ return rows;+ };++ /** A row on screen, or whose entry has writes / a page load in flight. */+ const isPinned = (queryKey: string, entryKey: string | undefined) =>+ retainedRows.has(queryKey) ||+ (entryKey !== undefined &&+ (retainedKeys.has(entryKey) ||+ (getSlot().entries[entryKey]?.pending.length ?? 0) > 0 ||+ loadingMore.has(entryKey)));++ /** The oldest unpinned rows past the cap (`keys` is oldest first). */+ const pickEvictions = (scope: string, keys: string[], touched: string): string[] => {+ const going = evicting.get(scope);+ let excess = keys.length - maxEntries! - keys.filter((key) => going?.has(key)).length;+ if (excess <= 0) return [];+ const loaded = loadedRows(scope);+ const picked: string[] = [];+ for (const queryKey of keys) {+ if (excess <= 0) break;+ if (queryKey === touched || going?.has(queryKey)) continue;+ if (isPinned(queryKey, loaded.get(queryKey))) continue;+ picked.push(queryKey);+ excess -= 1;+ }+ return picked;+ };++ /**+ * Evict rows: drop the memory entries that answer them (one commit), then+ * delete the rows. A row leaves the index only once its delete landed, so a+ * failed eviction is picked again by a later use.+ */+ const evictRows = (scope: string, queryKeys: string[]) => {+ if (resource.scope.get() !== scope || !resource.scope.canPersist()) return;+ const going = evicting.get(scope) ?? new Set<string>();+ evicting.set(scope, going);+ const loaded = loadedRows(scope);+ // Re-check: a row may have been pinned since it was picked.+ const rows = queryKeys.filter(+ (queryKey) => !going.has(queryKey) && !isPinned(queryKey, loaded.get(queryKey)),+ );+ if (rows.length === 0) return;+ for (const queryKey of rows) going.add(queryKey);+ const dropped = rows.flatMap((queryKey) => {+ const key = loaded.get(queryKey);+ return key === undefined ? [] : [key];+ });+ if (dropped.length > 0) {+ const slot = getSlot();+ const entries = { ...slot.entries };+ for (const key of dropped) delete entries[key];+ commit(dropped, { entries, scope });+ }+ void deleteRows(scope, rows).finally(() => {+ for (const queryKey of rows) going.delete(queryKey);+ if (going.size === 0 && evicting.get(scope) === going) evicting.delete(scope);+ });+ };++ /**+ * A bounded resource used a row: move it to the end of the index and evict+ * past the cap. No-op for an unbounded resource.+ */+ const touchStorageKey = (scope: string, queryKey: string) => {+ if (!writeQueue || maxEntries === undefined) return;+ const known = indexed.get(scope) ?? new Set<string>();+ indexed.set(scope, known);+ known.add(queryKey);+ let picked: string[] = [];+ void writeQueue+ .update(+ indexKey(scope),+ (current) => {+ const keys = (current?.data as unknown as string[] | undefined) ?? [];+ const next = [...keys.filter((key) => key !== queryKey), queryKey];+ picked = pickEvictions(scope, next, queryKey);+ if (keys.length === next.length && keys.at(-1) === queryKey) return undefined;+ return { data: next as unknown as TData, updatedAt: Date.now() };+ },+ { read: 'prefer-strict' },+ )+ .then((touched) => {+ // Unreadable index: leave it untouched, retry the append on the next use.+ if (!touched) return void known.delete(queryKey);+ if (picked.length > 0) evictRows(scope, picked);+ });+ };++ /** Record a persisted row in the index (queued after the row write). */+ const trackStorageKey = (scope: string, queryKey: string) => {+ if (!writeQueue) return;+ noteWrite(scope, queryKey);+ if (maxEntries !== undefined) return touchStorageKey(scope, queryKey);+ const known = indexed.get(scope) ?? new Set<string>();+ indexed.set(scope, known);+ if (known.has(queryKey)) return;+ known.add(queryKey);+ void writeQueue+ .update(+ indexKey(scope),+ (current) => {+ const keys = new Set((current?.data as unknown as string[] | undefined) ?? []);+ if (keys.has(queryKey)) return undefined;+ keys.add(queryKey);+ return { data: [...keys] as unknown as TData, updatedAt: Date.now() };+ },+ { read: 'prefer-strict' },+ )+ // An unreadable index is left untouched (never rewritten as just this+ // key); forget the key so the next write of the row retries the append.+ .then((tracked) => {+ if (!tracked) known.delete(queryKey);+ });+ };++ /**+ * Read the index for a destructive pass (remove / clear / entity patch).+ * Uses the storage's strict read when it has one, so an unreadable index+ * rejects instead of looking empty — a purge must never report success for+ * rows it could not enumerate.+ */+ const readIndex = async (scope: string): Promise<string[]> => {+ // A storage without `getStrict` rejects here: its `get` cannot tell an+ // unreadable index from an empty one.+ const row = await readReplicaRowStrict(resource.storage!, indexKey(scope));+ return (row?.data as unknown as string[] | undefined) ?? [];+ };++ /**+ * Drop storage keys from the index (both the session's view of it and the+ * persisted row, which may list keys this session never wrote).+ */+ const untrackStorageKeys = (scope: string, queryKeys: string[]) => {+ if (!writeQueue || queryKeys.length === 0) return;+ const known = indexed.get(scope);+ for (const queryKey of queryKeys) known?.delete(queryKey);+ const dropped = new Set(queryKeys);+ writeQueue.update(+ indexKey(scope),+ (current) => {+ const keys = (current?.data as unknown as string[] | undefined) ?? [];+ const next = keys.filter((queryKey) => !dropped.has(queryKey));+ if (!current || next.length === keys.length) return undefined;+ return { data: next as unknown as TData, updatedAt: Date.now() };+ },+ { read: 'prefer-strict' },+ );+ };++ /** Take rows whose delete landed out of the index, unless rewritten since. */+ const confirmDeleted = (scope: string, deleted: [queryKey: string, seq: number][]) => {+ const gone = deleted+ .filter(([queryKey, seq]) => rowWrites.get(rowId(scope, queryKey)) === seq)+ .map(([queryKey]) => queryKey);+ for (const queryKey of gone) rowWrites.delete(rowId(scope, queryKey));+ untrackStorageKeys(scope, gone);+ };++ /**+ * Queue row deletes now (ordered before any later write to the same rows).+ * A key leaves the index only once its delete is confirmed: a failed delete+ * stays indexed, so the next `remove` / `clear` finds and retries it.+ * Resolves `true` when every delete landed.+ */+ const deleteRows = (scope: string, queryKeys: string[]): Promise<boolean> => {+ const queue = writeQueue!;+ forgetStored(scope, queryKeys);+ const queued = queryKeys.map((queryKey) => {+ const seq = noteWrite(scope, queryKey);+ return queue+ .remove({ queryKey, scope })+ .then((removed): [string, number] | undefined => (removed ? [queryKey, seq] : undefined));+ });+ return Promise.all(queued).then((results) => {+ confirmDeleted(+ scope,+ results.filter((result): result is [string, number] => !!result),+ );+ return results.every(Boolean);+ });+ };++ /**+ * Delete every persisted row of entry `key` in `scope` — `current` (the row+ * memory knows about, queued right away so it orders before any later write)+ * plus every other query variant the index lists. Resolves `true` once all+ * deletes landed.+ */+ const removeStoredVariants = (scope: string, key: string, current: string) => {+ const first = deleteRows(scope, [current]);+ const rest = readIndex(scope).then(+ (persisted) => {+ // A server value that superseded the removal while the index was read+ // owns its (fresh) row: keep it, delete only the stale variants.+ const slot = getSlot();+ const live = !isRemoved(scope, key) && slot.scope === scope ? slot.entries[key] : undefined;+ const liveKey = live && replicaStorageKey(key, live.query);+ const variants = new Set(+ [...(indexed.get(scope) ?? []), ...persisted].filter(+ (queryKey) =>+ queryKey !== current && queryKey !== liveKey && isReplicaStorageKeyOf(queryKey, key),+ ),+ );+ return variants.size === 0 ? true : deleteRows(scope, [...variants]);+ },+ () => false,+ );+ return Promise.all([first, rest]).then((results) => results.every(Boolean));+ };++ /** Persist `data` to one row (the write path of a `persist` effect). */+ const writeRow = (scope: string, queryKey: string, data: TData) => {+ const queue = writeQueue!;+ // The row already holds this value: an unchanged revalidation is no write.+ if (isStored(scope, queryKey, data)) {+ touchStorageKey(scope, queryKey);+ return;+ }+ // Until this write is confirmed the row's content is unknown: forget what+ // it held, and only remember `data` once the write observably landed and+ // is still the latest queued for the row. A failed (or best-effort,+ // silently dropped) write therefore never makes a later identical persist+ // look redundant — that one writes again.+ forgetStored(scope, [queryKey]);+ trackStorageKey(scope, queryKey);+ const id = rowId(scope, queryKey);+ const seq = rowWrites.get(id);+ void queue.set({ queryKey, scope }, { data, updatedAt: Date.now() }).then((written) => {+ if (written && rowWrites.get(id) === seq) rememberStored(scope, queryKey, data);+ });+ };++ /**+ * Read-modify-write one row in the per-key write queue, so it sees every+ * earlier write; a missing row is never recreated. `transform` returns the+ * next data, `undefined` to leave the row, or `DROP_ROW` to drop it (the row+ * leaves the index once its delete landed). Resolves whether it settled.+ */+ const patchRow = (+ scope: string,+ queryKey: string,+ transform: (data: TData) => TData | typeof DROP_ROW | undefined,+ ): Promise<boolean> => {+ const seq = noteWrite(scope, queryKey);+ forgetStored(scope, [queryKey]);+ let dropped = false;+ return writeQueue!+ .update(+ { queryKey, scope },+ (current) => {+ if (!current) return undefined;+ const next = transform(current.data);+ if (next === undefined) return undefined;+ if (next === DROP_ROW) {+ dropped = true;+ return null;+ }+ return { data: next, updatedAt: Date.now() };+ },+ { read: 'strict' },+ )+ .then((written) => {+ if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);+ return written;+ });+ };++ /**+ * Read-modify-write the persisted rows memory does not hold, keyed by row+ * rather than by entity: a cached list for a folder the user is not viewing+ * gets its projection patched in the per-key write queue, so a later visit+ * hydrates the reconciled value instead of a stale page. `fn` returns the+ * next data, the same reference (or `undefined`) to skip, or `null` to drop+ * the row. Runs in the write queue, so it sees every earlier write.+ */+ const patchStoredRows = async (fn: (data: TData) => TData | null | undefined): Promise<void> => {+ if (!writeQueue || !resource.scope.canPersist()) return;+ const scope = resource.scope.get();+ const slot = getSlot();+ const loaded = new Set(+ slot.scope === scope+ ? Object.entries(slot.entries).map(([key, entry]) => replicaStorageKey(key, entry.query))+ : [],+ );+ let keys: string[];+ try {+ keys = await readIndex(scope);+ } catch (error) {+ console.error(`[replica:${resource.name}] failed to read the persisted index`, error);+ return;+ }+ // Identity changed while reading the index: those rows are not ours to touch.+ if (resource.scope.get() !== scope) return;+ const patches: Promise<boolean>[] = [];+ for (const queryKey of keys) {+ if (loaded.has(queryKey)) continue;+ patches.push(+ patchRow(scope, queryKey, (data) => {+ const next = fn(data);+ if (next === data) return undefined;+ return next === null ? DROP_ROW : next;+ }),+ );+ }+ await Promise.all(patches);+ };++ return {+ deleteRows,+ forgetScope,+ forgetStored,+ indexedKeys,+ patchRow,+ patchStoredRows,+ readIndex,+ rememberRead,+ removeStoredVariants,+ retain,+ touchStorageKey,+ writeCount,+ writeRow,+ };+};++export type ReplicaPersistedRows<TData> = ReturnType<typeof createPersistedRows<TData>>;diff --git a/packages/replica/src/core/removalGuards.ts b/packages/replica/src/core/removalGuards.tsnew file mode 100644index 00000000000..a08e553b493--- /dev/null+++ b/packages/replica/src/core/removalGuards.ts@@ -0,0 +1,134 @@+import { createTombstones, DEFAULT_REMOVAL_TOMBSTONE_LIMIT } from './tombstones';++/**+ * Removal guard of one engine.+ *+ * An explicit removal (a deleted / unauthorized aggregate, or a subject whose+ * attachment is gone) drops the entry AND its persisted row — but a read of+ * that row that started before the removal still holds the old value, and a+ * removal leaves no trace in the slots for the `hydrate` guard to see. So a+ * scope+key is remembered as removed and refuses hydration until a server+ * value supersedes it, otherwise the late read resurrects the exact value the+ * removal just dropped.+ */+export const createRemovalGuards = () => {+ const removedEntries = createTombstones();+ /**+ * Keys whose persisted row delete was actually queued. `runEffects` refuses to+ * write while the scope is untrusted, so a removal made on a cold boot can arm+ * the guard without clearing the row. The guard alone must therefore not turn+ * a later removal into a no-op, or the stale row would survive and hydrate+ * again once the scope becomes trusted.+ */+ const purgedEntries = createTombstones();+ /**+ * Bumped on every removal of a scope+key. A network response whose request+ * started before the entry was removed (deleted, access revoked, pruned by an+ * authoritative parent list) must not `replace` it back: the slice records+ * the generation a request starts under and drops a response that crossed a+ * removal. Bounded like the tombstones; an evicted key reads 0, which only+ * ever drops a response (the next revalidate refetches), never admits one.+ */+ const removalGenerations = new Map<string, number>();+ const removalId = (scope: string, key: string) => `${scope}\u0000${key}`;+ const removalGeneration = (scope: string, key: string) =>+ removalGenerations.get(removalId(scope, key)) ?? 0;+ const markRemoved = (scope: string, key: string) => {+ removedEntries.add(scope, key);+ const id = removalId(scope, key);+ const next = (removalGenerations.get(id) ?? 0) + 1;+ // Re-insert so the map's insertion order is least-recently-removed first.+ removalGenerations.delete(id);+ removalGenerations.set(id, next);+ if (removalGenerations.size > DEFAULT_REMOVAL_TOMBSTONE_LIMIT)+ removalGenerations.delete(removalGenerations.keys().next().value as string);+ };+ const clearRemoved = (scope: string, key: string) => {+ removedEntries.clear(scope, key);+ purgedEntries.clear(scope, key);+ };+ const isRemoved = (scope: string, key: string) => removedEntries.has(scope, key);+ const markPurged = (scope: string, key: string) => purgedEntries.add(scope, key);+ const isPurged = (scope: string, key: string) => purgedEntries.has(scope, key);++ return { clearRemoved, isPurged, isRemoved, markPurged, markRemoved, removalGeneration };+};++export type ReplicaRemovalGuards = ReturnType<typeof createRemovalGuards>;++/**+ * Entity removal guards of one engine.+ *+ * A hydrate that read its row before `removeEntity` patched storage still+ * holds the entity, so it is stripped from every value that hydrates while+ * such a read may be pending. A guard's lifetime follows the hydrates, not a+ * count: it is released once its storage patch landed (`releasedAt`) and is+ * dropped as soon as no hydrate that started before that point is pending.+ * So memory stays bounded by in-flight reads, and no guard a pending read+ * still needs is ever evicted. A patch that did not land is never released:+ * the unloaded row still holds the entity, so every later hydrate needs the+ * guard. A server value holding the entity again (restored) lifts it early.+ */+export const createEntityRemovalGuards = () => {+ /** Logical clock shared by hydrate starts and guard releases. */+ let guardClock = 0;+ /** Start ticks of the hydrates in flight, per scope. */+ const pendingHydrates = new Map<string, Set<number>>();+ /** Removed entity ids per scope; `releasedAt` is unset until the storage patch landed. */+ const removedEntities = new Map<string, Map<string, { releasedAt?: number }>>();+ const removedIds = (scope: string) => [...(removedEntities.get(scope)?.keys() ?? [])];++ /** Drop the guards no pending hydrate of `scope` can still need. */+ const pruneEntityGuards = (scope: string) => {+ const guards = removedEntities.get(scope);+ if (!guards) return;+ let oldestPending = Infinity;+ for (const start of pendingHydrates.get(scope) ?? [])+ oldestPending = Math.min(oldestPending, start);+ for (const [id, guard] of guards)+ if (guard.releasedAt !== undefined && guard.releasedAt <= oldestPending) guards.delete(id);+ if (guards.size === 0) removedEntities.delete(scope);+ };++ /**+ * Mark a hydrate of `scope` pending until settled: entity guards outlive every+ * read that may hold them. Returns the settle.+ */+ const startHydrate = (scope: string) => {+ const start = ++guardClock;+ const pending = pendingHydrates.get(scope) ?? new Set<number>();+ pendingHydrates.set(scope, pending);+ pending.add(start);+ return () => {+ pending.delete(start);+ if (pending.size === 0) pendingHydrates.delete(scope);+ pruneEntityGuards(scope);+ };+ };++ /** Arm the guard of entity `id` in `scope`. Returns its release (call once the patch landed). */+ const guardEntity = (scope: string, id: string) => {+ const guard: { releasedAt?: number } = {};+ const guards = removedEntities.get(scope) ?? new Map<string, { releasedAt?: number }>();+ removedEntities.set(scope, guards);+ guards.set(id, guard);+ return () => {+ // A newer removal of the same id owns the slot now.+ if (guards.get(id) !== guard) return;+ guard.releasedAt = ++guardClock;+ pruneEntityGuards(scope);+ };+ };++ /** Lift the guards of `ids` early (a server value holds them again). */+ const liftEntityGuards = (scope: string, ids: string[]) => {+ const guards = removedEntities.get(scope);+ if (!guards) return;+ for (const id of ids) guards.delete(id);+ if (guards.size === 0) removedEntities.delete(scope);+ };++ return { guardEntity, liftEntityGuards, removedIds, startHydrate };+};++export type ReplicaEntityRemovalGuards = ReturnType<typeof createEntityRemovalGuards>;diff --git a/packages/replica/src/core/settle.test.ts b/packages/replica/src/core/settle.test.tsnew file mode 100644index 00000000000..79984bda07e--- /dev/null+++ b/packages/replica/src/core/settle.test.ts@@ -0,0 +1,24 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { settleWithin } from './settle';++afterEach(() => vi.useRealTimers());++describe('settleWithin', () => {+ it('resolves as soon as the promise settles, rejection included', async () => {+ await expect(settleWithin(Promise.resolve('x'), 1000)).resolves.toBeUndefined();+ await expect(settleWithin(Promise.reject(new Error('io')), 1000)).resolves.toBeUndefined();+ });++ it('resolves at the deadline when the promise never settles', async () => {+ vi.useFakeTimers();+ const settled = vi.fn();++ void settleWithin(new Promise(() => {}), 50).then(settled);+ await vi.advanceTimersByTimeAsync(49);+ expect(settled).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(1);+ expect(settled).toHaveBeenCalledOnce();+ });+});diff --git a/packages/replica/src/core/settle.ts b/packages/replica/src/core/settle.tsnew file mode 100644index 00000000000..02fe3e596b6--- /dev/null+++ b/packages/replica/src/core/settle.ts@@ -0,0 +1,16 @@+/**+ * Resolve once `promise` settles or `ms` elapses — never rejects, never hangs.+ *+ * Bounds a pre-paint hydrate in a route loader: the persisted read is usually+ * sub-millisecond, and the deadline only fires on a pathological storage stall,+ * so a route transition never waits longer than `ms` for it.+ */+export const settleWithin = (promise: Promise<unknown>, ms: number): Promise<void> =>+ new Promise((resolve) => {+ const finish = () => {+ clearTimeout(timer);+ resolve();+ };+ const timer = setTimeout(finish, ms);+ void Promise.resolve(promise).then(finish, finish);+ });diff --git a/packages/replica/src/core/storedKeys.test.ts b/packages/replica/src/core/storedKeys.test.tsnew file mode 100644index 00000000000..14ce07a6038--- /dev/null+++ b/packages/replica/src/core/storedKeys.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';++import { staticReplicaScope } from './defineReplica';+import { REPLICA_INDEX_KEY } from './engine';+import { readReplicaStoredKeys } from './storedKeys';+import type { ReplicaRow, ReplicaStorage } from './types';++const memoryStorage = (rows: Record<string, ReplicaRow<any>>): ReplicaStorage<any> => ({+ get: async ({ queryKey, scope }) => rows[`${scope}/${queryKey}`],+ remove: async () => {},+ set: async () => {},+});++describe('readReplicaStoredKeys', () => {+ it('reads the index row of the active scope', async () => {+ const storage = memoryStorage({+ [`a/${REPLICA_INDEX_KEY}`]: { data: ['k1', 'k2?sort=asc'], updatedAt: 1 },+ [`b/${REPLICA_INDEX_KEY}`]: { data: ['other'], updatedAt: 1 },+ });++ await expect(readReplicaStoredKeys({ scope: staticReplicaScope('a'), storage })).resolves.toEqual(+ ['k1', 'k2?sort=asc'],+ );+ });++ it('reports no keys without an index row or a storage', async () => {+ const scope = staticReplicaScope('a');++ await expect(readReplicaStoredKeys({ scope, storage: memoryStorage({}) })).resolves.toEqual([]);+ await expect(readReplicaStoredKeys({ scope, storage: undefined })).resolves.toEqual([]);+ });+});diff --git a/packages/replica/src/core/storedKeys.ts b/packages/replica/src/core/storedKeys.tsnew file mode 100644index 00000000000..6b92c3a712f--- /dev/null+++ b/packages/replica/src/core/storedKeys.ts@@ -0,0 +1,26 @@+import { REPLICA_INDEX_KEY } from './engine';+import type { ReplicaResource } from './types';++/**+ * The entry storage keys this resource has a persisted row for in the active+ * scope, oldest first.+ *+ * Storage has no key listing of its own; the engine keeps one index row per+ * scope (`REPLICA_INDEX_KEY`) as it persists and drops entries, and this reads+ * it. That is how code outside the owning store reaches rows an *earlier+ * session* wrote — bounding how many survive a reload, or invalidating a row+ * whose entry is not loaded in memory.+ *+ * The keys are storage keys (`key`, plus `?query` when the resource sets one),+ * so a caller only matches them against entry keys when the resource leaves+ * `query` unset.+ */+export const readReplicaStoredKeys = async (+ resource: Pick<ReplicaResource<any, any, any>, 'scope' | 'storage'>,+): Promise<string[]> => {+ const row = await resource.storage?.get({+ queryKey: REPLICA_INDEX_KEY,+ scope: resource.scope.get(),+ });+ return (row?.data as unknown as string[] | undefined) ?? [];+};diff --git a/packages/replica/src/index.ts b/packages/replica/src/index.tsindex 340e525c05c..dca454763cc 100644--- a/packages/replica/src/index.ts+++ b/packages/replica/src/index.ts@@ -5,5 +5,8 @@ export * from './core/entityAdapters';export * from './core/keys';export * from './core/paging';export * from './core/reducer';+export * from './core/settle';+export * from './core/storedKeys';export type * from './core/types';export * from './core/writeQueue';+export * from './storage';diff --git a/packages/replica/src/storage/index.ts b/packages/replica/src/storage/index.tsnew file mode 100644index 00000000000..25b8252d50a--- /dev/null+++ b/packages/replica/src/storage/index.ts@@ -0,0 +1,2 @@+export * from './keyValue';+export * from './localStorage';diff --git a/packages/replica/src/storage/keyValue.test.ts b/packages/replica/src/storage/keyValue.test.tsnew file mode 100644index 00000000000..532f236fe7d--- /dev/null+++ b/packages/replica/src/storage/keyValue.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it, vi } from 'vitest';++import { KeyValueReplicaStorage, type ReplicaKeyValueStore } from './keyValue';++const createStore = (overrides: Partial<ReplicaKeyValueStore> = {}) => {+ const rows = new Map<string, unknown>();+ const store: ReplicaKeyValueStore = {+ delete: vi.fn(async (key: string) => {+ rows.delete(key);+ }),+ get: vi.fn(async (key: string) => rows.get(key)),+ initialize: vi.fn(async () => {}),+ set: vi.fn(async (key: string, value: unknown) => {+ rows.set(key, value);+ }),+ ...overrides,+ };+ return { rows, store };+};++describe('KeyValueReplicaStorage', () => {+ it('stores one scoped record per row, after opening the store', async () => {+ const { rows, store } = createStore();+ const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });+ const key = { queryKey: 'detail:1', scope: 'user:workspace' };++ await storage.set(key, { data: ['cached'], updatedAt: 1 });++ expect(store.initialize).toHaveBeenCalled();+ expect([...rows.keys()]).toEqual(['projects:user%3Aworkspace:detail%3A1']);+ await expect(storage.get(key)).resolves.toEqual({ data: ['cached'], updatedAt: 1 });+ await expect(storage.get({ ...key, scope: 'other' })).resolves.toBeUndefined();+ });++ it('works with a store that needs no initialization', async () => {+ const { store } = createStore({ initialize: undefined });+ const storage = new KeyValueReplicaStorage<number>({ namespace: 'n', store });+ const key = { queryKey: 'q', scope: 's' };++ await storage.set(key, { data: 1, updatedAt: 1 });+ await storage.remove(key);++ await expect(storage.getStrict(key)).resolves.toBeUndefined();+ });++ it('rejects a write that did not land, so the replica retries it', async () => {+ const { store } = createStore({ set: vi.fn().mockRejectedValue(new Error('aborted')) });+ const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });++ await expect(+ storage.set({ queryKey: 'all', scope: 'personal' }, { data: ['x'], updatedAt: 1 }),+ ).rejects.toThrow('aborted');+ });++ it('treats a store that cannot open as a cache miss', async () => {+ const { store } = createStore({+ initialize: vi.fn().mockRejectedValue(new Error('unavailable')),+ });+ const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });++ await expect(storage.get({ queryKey: 'all', scope: 'personal' })).resolves.toBeUndefined();+ });++ it('reports a failed delete so the caller can retry it', async () => {+ const { store } = createStore({ delete: vi.fn().mockRejectedValue(new Error('closed')) });+ const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });++ await expect(storage.remove({ queryKey: 'all', scope: 'personal' })).rejects.toThrow('closed');+ });++ it('rejects a strict read that failed, while get stays a cache miss', async () => {+ const { store } = createStore({ get: vi.fn().mockRejectedValue(new Error('closed')) });+ const storage = new KeyValueReplicaStorage<string[]>({ namespace: 'projects', store });+ const key = { queryKey: '__replica:index', scope: 'personal' };++ await expect(storage.getStrict(key)).rejects.toThrow('closed');+ await expect(storage.get(key)).resolves.toBeUndefined();+ });+});diff --git a/packages/replica/src/storage/keyValue.ts b/packages/replica/src/storage/keyValue.tsnew file mode 100644index 00000000000..5ac21092cdb--- /dev/null+++ b/packages/replica/src/storage/keyValue.ts@@ -0,0 +1,74 @@+import type { ReplicaRow, ReplicaRowKey, ReplicaStorage } from '../core/types';++/**+ * An async key-value store a replica can persist into: an IndexedDB object+ * store, a SQLite table behind IPC, a `Map` in tests. Values are stored as+ * given (structured clone), so the store decides what it can hold.+ */+export interface ReplicaKeyValueStore {+ /** Rejects when the delete did not land. A missing key is a success. */+ delete: (key: string) => Promise<void>;+ /** Rejects when the read failed; resolves `undefined` for a missing key. */+ get: (key: string) => Promise<unknown>;+ /** Opens the store; awaited before every operation. */+ initialize?: () => Promise<void>;+ /** Rejects when the write did not land. */+ set: (key: string, value: unknown) => Promise<void>;+}++export interface KeyValueReplicaStorageOptions {+ /** Prefix of every row of this storage, usually the resource name. */+ namespace: string;+ store: ReplicaKeyValueStore;+}++/** Store key of one row: `<namespace>:<scope>:<queryKey>`, each part URI-encoded but the namespace. */+export const replicaRowStoreKey = (namespace: string, { queryKey, scope }: ReplicaRowKey) =>+ `${namespace}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;++/** {@link ReplicaStorage} over an async key-value store, one record per row. */+export class KeyValueReplicaStorage<T> implements ReplicaStorage<T> {+ readonly #namespace: string;+ readonly #store: ReplicaKeyValueStore;++ constructor({ namespace, store }: KeyValueReplicaStorageOptions) {+ this.#namespace = namespace;+ this.#store = store;+ }++ #key = (key: ReplicaRowKey) => replicaRowStoreKey(this.#namespace, key);++ get = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => {+ try {+ return await this.getStrict(key);+ } catch {+ return undefined;+ }+ };++ /** Like `get`, but rejects when the row could not be read (see `ReplicaStorage.getStrict`). */+ getStrict = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => {+ await this.#store.initialize?.();+ return (await this.#store.get(this.#key(key))) as ReplicaRow<T> | undefined;+ };++ /**+ * Rejects when the delete did not land, unlike reads: a caller that removes a+ * row the user deleted must be able to retry it.+ */+ remove = async (key: ReplicaRowKey): Promise<void> => {+ await this.#store.initialize?.();+ await this.#store.delete(this.#key(key));+ };++ /**+ * Rejects when the write did not land (see `ReplicaStorage.set`): the replica+ * engine only treats a row as holding a value after a confirmed write, so a+ * dropped write is retried by the next persist instead of being skipped as+ * redundant.+ */+ set = async (key: ReplicaRowKey, row: ReplicaRow<T>): Promise<void> => {+ await this.#store.initialize?.();+ await this.#store.set(this.#key(key), row);+ };+}diff --git a/packages/replica/src/storage/localStorage.test.ts b/packages/replica/src/storage/localStorage.test.tsnew file mode 100644index 00000000000..a0a7ad4adb6--- /dev/null+++ b/packages/replica/src/storage/localStorage.test.ts@@ -0,0 +1,78 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { LocalStorageReplicaStorage } from './localStorage';++afterEach(() => {+ vi.restoreAllMocks();+ localStorage.clear();+});++describe('LocalStorageReplicaStorage', () => {+ it('restores a scoped row synchronously before the next paint', () => {+ const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });+ const key = { queryKey: 'display', scope: 'user-a' };++ void storage.set(key, { data: ['cached'], updatedAt: 1 });++ expect(storage.getSync(key)).toEqual({ data: ['cached'], updatedAt: 1 });+ expect(storage.getSync({ ...key, scope: 'user-b' })).toBeUndefined();+ });++ it('isolates rows by scope and query key', async () => {+ const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });++ await storage.set({ queryKey: 'limit:10', scope: 'scope-a' }, { data: ['a'], updatedAt: 1 });++ expect(localStorage.getItem('test:scope-a:limit%3A10')).toBe(+ JSON.stringify({ data: ['a'], updatedAt: 1 }),+ );+ await expect(storage.get({ queryKey: 'limit:10', scope: 'scope-b' })).resolves.toBeUndefined();+ await expect(storage.get({ queryKey: 'limit:50', scope: 'scope-a' })).resolves.toBeUndefined();+ });++ it('serializes through a custom codec', async () => {+ const codec = {+ parse: vi.fn((value: string) => ({ data: value.slice(4), updatedAt: 0 })),+ stringify: vi.fn(({ data }: { data: string }) => `raw:${data}`),+ };+ const storage = new LocalStorageReplicaStorage<string>({ codec, namespace: 'test' });+ const key = { queryKey: 'q', scope: 's' };++ await storage.set(key, { data: 'hello', updatedAt: 1 });++ await expect(storage.get(key)).resolves.toEqual({ data: 'hello', updatedAt: 0 });+ });++ it('rejects a write that did not land (quota), so the replica retries it', async () => {+ const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });+ vi.spyOn(localStorage, 'setItem').mockImplementation(() => {+ throw new Error('QuotaExceededError');+ });++ await expect(+ storage.set({ queryKey: 'q', scope: 'user-a' }, { data: ['x'], updatedAt: 1 }),+ ).rejects.toThrow('QuotaExceededError');+ });++ it('reports a failed delete so the caller can retry it', async () => {+ const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });+ vi.spyOn(localStorage, 'removeItem').mockImplementation(() => {+ throw new Error('access denied');+ });++ await expect(storage.remove({ queryKey: 'display', scope: 'user-a' })).rejects.toThrow(+ 'access denied',+ );+ });++ it('rejects a strict read that failed, while get stays a cache miss', async () => {+ const storage = new LocalStorageReplicaStorage<string[]>({ namespace: 'test' });+ const key = { queryKey: '__replica:index', scope: 'user-a' };+ vi.spyOn(localStorage, 'getItem').mockImplementation(() => {+ throw new Error('access denied');+ });++ await expect(storage.getStrict(key)).rejects.toThrow('access denied');+ await expect(storage.get(key)).resolves.toBeUndefined();+ });+});diff --git a/packages/replica/src/storage/localStorage.ts b/packages/replica/src/storage/localStorage.tsnew file mode 100644index 00000000000..6df71147923--- /dev/null+++ b/packages/replica/src/storage/localStorage.ts@@ -0,0 +1,78 @@+import type { ReplicaRow, ReplicaRowKey, ReplicaStorage } from '../core/types';+import { replicaRowStoreKey } from './keyValue';++/** Turns a row into the string `localStorage` holds, and back. */+export interface ReplicaRowCodec<T> {+ parse: (value: string) => ReplicaRow<T>;+ stringify: (row: ReplicaRow<T>) => string;+}++export interface LocalStorageReplicaStorageOptions<T> {+ /** Defaults to JSON. Pass a richer codec (e.g. superjson) for `Date`, `Map` … */+ codec?: ReplicaRowCodec<T>;+ /** Prefix of every row of this storage, usually the resource name. */+ namespace: string;+}++const jsonCodec: ReplicaRowCodec<any> = { parse: JSON.parse, stringify: JSON.stringify };++/**+ * {@link ReplicaStorage} over `window.localStorage`. Small values only (the+ * origin shares a ~5 MB quota), but the read is synchronous: `getSync` restores+ * a row inside pre-paint initialization without yielding a frame. Outside a+ * browser every operation is a no-op miss.+ */+export class LocalStorageReplicaStorage<T> implements ReplicaStorage<T> {+ readonly #codec: ReplicaRowCodec<T>;+ readonly #namespace: string;++ constructor({ codec = jsonCodec, namespace }: LocalStorageReplicaStorageOptions<T>) {+ this.#codec = codec;+ this.#namespace = namespace;+ }++ #key = (key: ReplicaRowKey) => replicaRowStoreKey(this.#namespace, key);++ get = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => this.getSync(key);++ /** Restore a row inside pre-paint initialization without yielding a frame. */+ getSync = (key: ReplicaRowKey): ReplicaRow<T> | undefined => {+ if (typeof window === 'undefined') return undefined;++ try {+ const value = localStorage.getItem(this.#key(key));+ return value ? this.#codec.parse(value) : undefined;+ } catch {+ return undefined;+ }+ };++ /** Like `get`, but rejects when the row could not be read or parsed (see `ReplicaStorage.getStrict`). */+ getStrict = async (key: ReplicaRowKey): Promise<ReplicaRow<T> | undefined> => {+ if (typeof window === 'undefined') return undefined;++ const value = localStorage.getItem(this.#key(key));+ return value ? this.#codec.parse(value) : undefined;+ };++ /**+ * Rejects when the delete did not land (e.g. storage access denied), unlike+ * reads: a caller removing a row the user deleted must be able to retry it.+ */+ remove = async (key: ReplicaRowKey): Promise<void> => {+ if (typeof window === 'undefined') return;++ localStorage.removeItem(this.#key(key));+ };++ /**+ * Rejects when the write did not land (a quota error, see `ReplicaStorage.set`):+ * the replica engine only treats a row as holding a value after a confirmed+ * write.+ */+ set = async (key: ReplicaRowKey, row: ReplicaRow<T>): Promise<void> => {+ if (typeof window === 'undefined') return;++ localStorage.setItem(this.#key(key), this.#codec.stringify(row));+ };+}diff --git a/packages/replica/src/zustand/createReplicaSlice.invalidation.test.ts b/packages/replica/src/zustand/createReplicaSlice.invalidation.test.tsnew file mode 100644index 00000000000..2d60198d2a3--- /dev/null+++ b/packages/replica/src/zustand/createReplicaSlice.invalidation.test.ts@@ -0,0 +1,494 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createStore } from 'zustand/vanilla';++import { testDriver as driver } from '../../tests/testDriver';+import { defineReplica } from '../core/defineReplica';+import { REPLICA_INDEX_KEY } from '../core/engine';+import { createReplicaState } from '../core/reducer';+import type { ReplicaRow, ReplicaStorage } from '../core/types';+import { createReplicaSlice, recordLens } from './createReplicaSlice';+import type { TestState } from './testUtils';+import { createMemoryStorage, resetScopeState, scope, scopeState, setup, wrapper } from './testUtils';++beforeEach(resetScopeState);++describe('createReplicaSlice', () => {+ describe('remove', () => {+ it('does not let an in-flight response resurrect a removed entry', async () => {+ let resolveFetch!: (value: string[]) => void;+ const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));+ const { slice, store } = setup({ fetcher });++ renderHook(() => slice.useSync({ id: 'a' }), { wrapper });+ await waitFor(() => expect(fetcher).toHaveBeenCalled());++ // The entry is invalidated while its own request is still in flight.+ act(() => {+ slice.remove('a');+ });+ await act(async () => resolveFetch(['late']));++ expect(store.getState().lists.a).toBeUndefined();+ });+ });++ describe('persisted index', () => {+ it('removes a key this instance never wrote from the stored index', async () => {+ const storage = createMemoryStorage();+ // An earlier session persisted this row and listed it in the index. This+ // instance has no memory of the key — the eviction / invalidation case+ // where the index write must still reach storage.+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });+ storage.indexRows.set('user-1:personal', { data: ['a'], updatedAt: 1 });+ const { slice } = setup({ storage });++ act(() => slice.remove('a'));++ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));+ });+ });++ describe('invalidation', () => {+ interface QueryParams {+ id: string;+ q?: string;+ }+ /** A resource whose rows are persisted per query (`a`, `a?{"q":"x"}` …). */+ const setupQueried = ({+ driver: queryDriver = driver,+ storage = createMemoryStorage(),+ }: {+ driver?: Parameters<typeof createReplicaSlice>[1]['driver'];+ storage?: ReturnType<typeof createMemoryStorage>;+ } = {}) => {+ const resource = defineReplica<QueryParams, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'queriedList',+ query: ({ q }) => ({ q }),+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, QueryParams, string[]>(resource, {+ driver: queryDriver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });+ return { resource, slice, storage, store };+ };+ const row = (resource: { storageKey: (params: QueryParams) => string }, params: QueryParams) =>+ `user-1:personal|${resource.storageKey(params)}`;++ /** Persist `a` (unfiltered + filtered) and `ab` in one session. */+ const persistVariants = async () => {+ const first = setupQueried();+ act(() => {+ first.slice.replace({ id: 'a' }, ['a-all']);+ first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);+ first.slice.replace({ id: 'ab' }, ['ab-all']);+ });+ await waitFor(() => expect(first.storage.rows.size).toBe(3));+ return first;+ };++ it('remove drops every persisted query variant of the key, not only the one in memory', async () => {+ const { resource, slice, storage } = await persistVariants();++ // Memory holds the filtered query; the unfiltered row was persisted earlier.+ act(() => slice.remove('a'));++ await waitFor(() => {+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);+ expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);+ });+ // Another key that merely shares the prefix is untouched.+ expect(storage.rows.get(row(resource, { id: 'ab' }))?.data).toEqual(['ab-all']);+ });++ it('remove drops variants persisted by an earlier session, through the index', async () => {+ const first = await persistVariants();+ // Reload: memory is empty, only the persisted index knows the variants.+ const { resource, slice, storage, store } = setupQueried({ storage: first.storage });++ act(() => slice.remove('a'));++ await waitFor(() => {+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);+ expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);+ });+ // No variant of the removed key hydrates.+ await act(async () => {+ expect(await slice.hydrate({ id: 'a', q: 'x' })).toBe(false);+ });+ expect(store.getState().lists.a).toBeUndefined();+ });++ it('an off-scope purge drops every query variant of its scope', async () => {+ const { resource, slice, storage } = await persistVariants();++ scopeState.current = 'user-2:personal';+ act(() => slice.remove('a', 'user-1:personal'));++ await waitFor(() => {+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);+ expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);+ });+ });++ /** Make storage reject the first delete of `queryKey` (a closed IndexedDB). */+ const failFirstDelete = (storage: ReturnType<typeof createMemoryStorage>, queryKey: string) => {+ const original = storage.storage.remove;+ let failed = false;+ storage.storage.remove = async (key) => {+ if (key.queryKey === queryKey && !failed) {+ failed = true;+ throw new Error('IndexedDB delete failed');+ }+ return original(key);+ };+ };++ it('keeps a variant whose delete failed indexed, so a later remove retries it', async () => {+ const { resource, slice, storage } = await persistVariants();+ const filtered = row(resource, { id: 'a', q: 'x' });+ failFirstDelete(storage, resource.storageKey({ id: 'a', q: 'x' }));+ // Memory holds another variant, so the failing row is found through the index.+ act(() => slice.replace({ id: 'a' }, ['a-all']));++ act(() => slice.remove('a'));+ await waitFor(() => expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false));+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(storage.rows.has(filtered)).toBe(true);++ // The next removal still knows about the failed row and retries it.+ act(() => slice.remove('a'));+ await waitFor(() => expect(storage.rows.has(filtered)).toBe(false));+ });++ it('keeps a row whose delete failed indexed, so a later clear retries it', async () => {+ const { resource, slice, storage } = await persistVariants();+ failFirstDelete(storage, resource.storageKey({ id: 'ab' }));++ let purge!: Promise<boolean>;+ act(() => {+ purge = slice.clear();+ });+ expect(await purge).toBe(false);+ expect([...storage.rows.keys()]).toEqual([row(resource, { id: 'ab' })]);++ act(() => {+ purge = slice.clear();+ });+ expect(await purge).toBe(true);+ expect(storage.rows.size).toBe(0);+ });++ /**+ * Storage whose index read fails the way the app adapters do: `get`+ * swallows it into a miss, only `getStrict` reports it.+ */+ const failIndexReads = (storage: ReturnType<typeof createMemoryStorage>) => {+ const state = { failing: true };+ const original = storage.storage.get;+ storage.storage.get = async (key) =>+ key.queryKey === REPLICA_INDEX_KEY && state.failing ? undefined : original(key);+ storage.storage.getStrict = async (key) => {+ if (key.queryKey === REPLICA_INDEX_KEY && state.failing)+ throw new Error('IndexedDB read failed');+ return original(key);+ };+ return state;+ };++ it('reports a clear as failed when the index cannot be read, and a later clear retries', async () => {+ const first = await persistVariants();+ // Reload: only the persisted index knows the earlier session's rows.+ const { slice, storage, store } = setupQueried({ storage: first.storage });+ const index = failIndexReads(storage);++ let purge!: Promise<boolean>;+ act(() => {+ purge = slice.clear();+ });+ expect(await purge).toBe(false);+ expect(storage.rows.size).toBe(3);+ // Hydration stays off while the wipe is incomplete.+ await act(async () => {+ expect(await slice.hydrate({ id: 'a' })).toBe(false);+ });+ expect(store.getState().lists.a).toBeUndefined();++ index.failing = false;+ act(() => {+ purge = slice.clear();+ });+ expect(await purge).toBe(true);+ expect(storage.rows.size).toBe(0);+ });++ it('keeps a removal unpurged when the index cannot be read, so it retries', async () => {+ const first = await persistVariants();+ const { resource, slice, storage } = setupQueried({ storage: first.storage });+ const filtered = row(resource, { id: 'a', q: 'x' });+ const index = failIndexReads(storage);++ // Memory is empty, so every variant is known only through the index.+ act(() => slice.remove('a'));+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(true);+ expect(storage.rows.has(filtered)).toBe(true);++ index.failing = false;+ act(() => slice.remove('a'));+ await waitFor(() => {+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);+ expect(storage.rows.has(filtered)).toBe(false);+ });+ });++ it('never mistakes a plain key containing `?` for a query variant', async () => {+ const storage = createMemoryStorage();+ const { slice } = setup({ storage });+ act(() => {+ slice.replace({ id: 'foo' }, ['foo']);+ slice.replace({ id: 'foo?bar' }, ['foo?bar']);+ });+ await waitFor(() => expect(storage.rows.size).toBe(2));++ act(() => slice.remove('foo'));++ await waitFor(() => expect(storage.rows.has('user-1:personal|foo')).toBe(false));+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(storage.rows.get('user-1:personal|foo?bar')?.data).toEqual(['foo?bar']);+ });++ it('cleans variants listed by an index written in the existing flat format', async () => {+ const storage = createMemoryStorage();+ // Rows and index as an earlier release persisted them on a device.+ for (const queryKey of ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'])+ storage.rows.set(`user-1:personal|${queryKey}`, { data: [queryKey], updatedAt: 1 });+ storage.indexRows.set('user-1:personal', {+ data: ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'],+ updatedAt: 1,+ });+ const { slice } = setupQueried({ storage });++ act(() => slice.remove('foo'));++ await waitFor(() => expect([...storage.rows.keys()]).toEqual(['user-1:personal|foo?bar?{}']));+ await waitFor(() =>+ expect(storage.indexRows.get('user-1:personal')?.data).toEqual(['foo?bar?{}']),+ );+ });++ it('calls a class-based storage with its receiver on every index pass', async () => {+ /** Prototype methods that rely on `this`, like most storage classes. */+ class ClassStorage implements ReplicaStorage<string[]> {+ rows = new Map<string, ReplicaRow<string[]>>();+ #id({ queryKey, scope }: { queryKey: string; scope: string }) {+ return `${scope}|${queryKey}`;+ }+ async get(key: { queryKey: string; scope: string }) {+ return this.rows.get(this.#id(key));+ }+ async getStrict(key: { queryKey: string; scope: string }) {+ return this.rows.get(this.#id(key));+ }+ async remove(key: { queryKey: string; scope: string }) {+ this.rows.delete(this.#id(key));+ }+ async set(key: { queryKey: string; scope: string }, row: ReplicaRow<string[]>) {+ this.rows.set(this.#id(key), row);+ }+ }+ const backing = new ClassStorage();+ const storage = { ...createMemoryStorage(), storage: backing };+ const dataRows = () =>+ [...backing.rows.keys()].filter((key) => !key.endsWith(REPLICA_INDEX_KEY));+ const first = setupQueried({ storage });+ act(() => {+ first.slice.replace({ id: 'a' }, ['a-all']);+ first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);+ first.slice.replace({ id: 'b' }, ['b-all']);+ });+ await waitFor(() => expect(dataRows()).toHaveLength(3));+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});++ // A fresh engine only finds the rows through the index.+ const { slice } = setupQueried({ storage });+ slice.updateEntity('x', (item) => item);+ act(() => slice.remove('a'));+ await waitFor(() => expect(dataRows()).toEqual(['user-1:personal|b?{}']));+ expect(await slice.clear()).toBe(true);+ expect(dataRows()).toEqual([]);+ expect(errors).not.toHaveBeenCalled();+ errors.mockRestore();+ });++ it('drops the request record of a failure even without an onError', async () => {+ const requests: { fetch: () => Promise<unknown>; onError?: (error: unknown) => void }[] = [];+ const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {+ if (key?.[0] === 'replica:sync') requests.push({ fetch, onError: options.onError });+ return { isValidating: false, mutate: vi.fn() };+ });+ const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });+ const deletes = vi.spyOn(Map.prototype, 'delete');++ const { rerender } = renderHook((props: QueryParams) => slice.useSync(props), {+ initialProps: { id: 'k1' } as QueryParams,+ });+ for (const id of ['k1', 'k2', 'k3']) {+ rerender({ id });+ const request = requests.at(-1)!;+ await request.fetch();+ act(() => request.onError!(new Error('forbidden')));+ }++ const dropped = deletes.mock.calls.map(([id]) => String(id));+ for (const id of ['k1', 'k2', 'k3'])+ expect(+ dropped.some((record) => record.includes('replica:sync') && record.includes(id)),+ ).toBe(true);+ deletes.mockRestore();+ });++ it('clear wipes memory, every persisted row and the index of the active scope', async () => {+ const first = await persistVariants();+ // A later session loads only one entry; the rest is known only to the index.+ const { slice, storage, store } = setupQueried({ storage: first.storage });+ act(() => slice.replace({ id: 'b' }, ['b-all']));+ storage.rows.set('user-2:personal|a', { data: ['other-user'], updatedAt: 1 });++ let purge!: Promise<boolean>;+ act(() => {+ purge = slice.clear();+ });+ expect(store.getState().lists).toEqual({});+ expect(store.getState().listsReplica.entries).toEqual({});++ await act(async () => {+ expect(await purge).toBe(true);+ });+ // Only the other identity's row survives; the index lists nothing.+ expect([...storage.rows.keys()]).toEqual(['user-2:personal|a']);+ await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));+ await act(async () => {+ expect(await slice.hydrate({ id: 'a' })).toBe(false);+ });+ });++ it('clear refuses a hydrate that was already reading', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['wiped'], updatedAt: 1 });+ const originalGet = storage.storage.get;+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ storage.storage.get = async (key) => {+ const value = await originalGet(key);+ if (key.queryKey === 'a') await held;+ return value;+ };+ const { slice, store } = setup({ storage });++ let hydration!: Promise<boolean>;+ await act(async () => {+ hydration = slice.hydrate({ id: 'a' });+ });+ act(() => {+ void slice.clear();+ });+ await act(async () => {+ release();+ expect(await hydration).toBe(false);+ });+ expect(store.getState().lists.a).toBeUndefined();+ });++ it('clear discards a head response that started before it, and applies one started after', () => {+ const requests: { fetch: () => Promise<unknown>; onSuccess: (data: string[]) => void }[] = [];+ const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {+ if (key?.[0] === 'replica:sync') requests.push({ fetch, onSuccess: options.onSuccess });+ return { isValidating: false, mutate: vi.fn() };+ });+ const { slice, store } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });+ renderHook(() => slice.useSync({ id: 'a' }));+ const request = requests.at(-1)!;++ // The request is issued, then the resource is wiped before it settles.+ void request.fetch();+ act(() => {+ void slice.clear();+ });+ act(() => request.onSuccess(['before-clear']));+ expect(store.getState().lists.a).toBeUndefined();++ // A request issued after the clear is ordinary.+ void request.fetch();+ act(() => request.onSuccess(['after-clear']));+ expect(store.getState().lists.a).toEqual(['after-clear']);+ });++ it('a clear whose purge could not run keeps refusing hydration', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });+ const { slice, store } = setup({ storage });++ // Identity is not resolved yet, so the row deletes are refused.+ scopeState.trusted = false;+ let purge!: Promise<boolean>;+ act(() => {+ purge = slice.clear();+ });+ expect(await purge).toBe(false);+ scopeState.trusted = true;++ await act(async () => {+ expect(await slice.hydrate({ id: 'a' })).toBe(false);+ });+ expect(store.getState().lists.a).toBeUndefined();+ });++ it('does not surface the error of a query the entry has moved past', () => {+ const requests: { onError: (error: unknown) => void; params: { q?: string } }[] = [];+ const useQuery = vi.fn((key: any, _fetch: unknown, options: any) => {+ if (key?.[0] === 'replica:sync')+ requests.push({ onError: options.onError, params: key.at(-1) });+ return { isValidating: false, mutate: vi.fn() };+ });+ const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });+ const onError = vi.fn();++ const { rerender } = renderHook((props: QueryParams) => slice.useSync(props, { onError }), {+ initialProps: { id: 'a' } as QueryParams,+ });+ rerender({ id: 'a', q: 'b' });++ const base = requests.find((request) => request.params.q === undefined)!;+ const search = requests.find((request) => request.params.q === 'b')!;++ // The superseded query fails late: the search on screen must not see it.+ act(() => base.onError(new Error('stale')));+ expect(onError).not.toHaveBeenCalled();++ const failure = new Error('search failed');+ act(() => search.onError(failure));+ expect(onError).toHaveBeenCalledWith(failure, {+ isActive: true,+ key: 'a',+ scope: 'user-1:personal',+ });+ });+ });+});diff --git a/packages/replica/src/zustand/createReplicaSlice.responses.test.ts b/packages/replica/src/zustand/createReplicaSlice.responses.test.tsnew file mode 100644index 00000000000..d54ef428de5--- /dev/null+++ b/packages/replica/src/zustand/createReplicaSlice.responses.test.ts@@ -0,0 +1,227 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createStore } from 'zustand/vanilla';++import { testDriver as driver } from '../../tests/testDriver';+import { defineReplica } from '../core/defineReplica';+import { singleEntity } from '../core/entityAdapters';+import { createReplicaState } from '../core/reducer';+import type { ReplicaState } from '../core/types';+import { createReplicaSlice, recordLens } from './createReplicaSlice';+import type { TestState } from './testUtils';+import { resetScopeState, scope, scopeState } from './testUtils';++beforeEach(resetScopeState);++describe('createReplicaSlice', () => {+ describe('missing responses', () => {+ it('applies a response the resource marks as missing as an explicit removal', () => {+ // A nullable detail (e.g. the acceptance attached to a subject): the+ // server answering "none" must clear a previously cached value, not let+ // the merge fall back to it.+ type NullableState = {+ notes: Record<string, string[] | null>;+ notesReplica: ReplicaState<string[] | null>;+ };+ const resource = defineReplica<{ id: string }, string[] | null>({+ key: ({ id }) => id,+ name: 'nullableNote',+ scope,+ version: 1,+ });+ const store = createStore<NullableState>()(() => ({+ notes: {},+ notesReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {+ driver,+ get: store.getState,+ isMissing: (note) => note === null,+ set: (partial) => store.setState(partial),+ stateKey: 'notesReplica',+ view: recordLens('notes'),+ });++ act(() => slice.replace({ id: 'a' }, ['kept']));+ expect(store.getState().notes.a).toEqual(['kept']);++ act(() => slice.replace({ id: 'a' }, null));+ expect(store.getState().notes.a).toBeUndefined();+ expect(store.getState().notesReplica.entries.a).toBeUndefined();+ });++ it('treats a repeated missing response as a no-op', () => {+ type NullableState = {+ notes: Record<string, string[] | null>;+ notesReplica: ReplicaState<string[] | null>;+ };+ const resource = defineReplica<{ id: string }, string[] | null>({+ key: ({ id }) => id,+ name: 'nullableNoteRepeat',+ scope,+ version: 1,+ });+ const store = createStore<NullableState>()(() => ({+ notes: {},+ notesReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {+ driver,+ get: store.getState,+ isMissing: (note) => note === null,+ set: (partial) => store.setState(partial),+ stateKey: 'notesReplica',+ view: recordLens('notes'),+ });++ act(() => slice.replace({ id: 'a' }, ['kept']));+ // The first "missing" drops the entry and clears stale storage…+ expect(slice.replace({ id: 'a' }, null)).toBe(true);+ // …a poll that still answers "missing" must not re-emit the removal.+ expect(slice.replace({ id: 'a' }, null)).toBe(false);+ expect(store.getState().notes.a).toBeUndefined();+ });+ });++ describe('late scoped responses', () => {+ it('does not replay a response that lands after a scope switch', () => {+ // A driver that settles each request through its own callback, so the+ // test chooses the moment the response arrives.+ let settle!: (data: string[]) => void;+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {+ if (key !== null) settle = options.onSuccess;+ return { isValidating: false, mutate: vi.fn() };+ });+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'lateScopeResponse',+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ const onSuccess = vi.fn();+ renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));++ // The identity switches while the request is in flight; the response+ // belongs to the previous scope and `replace` rejects it.+ scopeState.current = 'user-2:personal';+ act(() => settle(['late-user-1']));++ expect(store.getState().lists.a).toBeUndefined();+ expect(onSuccess).not.toHaveBeenCalled();+ });++ // An entity removed while its entry's request is in flight (deleted, pruned+ // by an authoritative parent list) must not be recreated by that response.+ // `slice.remove` drops the head-query marker, but an entity removal goes+ // straight through the engine, so the request generation must catch it.+ it('drops a response whose request started before the entity was removed', () => {+ interface Item {+ id: string;+ title: string;+ }+ interface ItemState {+ items: Record<string, Item>;+ itemsReplica: ReplicaState<Item>;+ }+ let settle!: (data: Item) => void;+ const useQuery = vi.fn((key: any, fetcher: () => unknown, options: any) => {+ if (key !== null) {+ settle = options.onSuccess;+ void fetcher();+ }+ return { isValidating: false, mutate: vi.fn() };+ });+ const resource = defineReplica<{ id: string }, Item>({+ fetcher: () => new Promise<Item>(() => {}),+ key: ({ id }) => id,+ name: 'removedEntityInFlight',+ scope,+ version: 1,+ });+ const store = createStore<ItemState>()(() => ({+ items: {},+ itemsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<ItemState, { id: string }, Item>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ entity: singleEntity<Item>((item) => item.id),+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'itemsReplica',+ view: recordLens('items'),+ });+ act(() => slice.replace({ id: 'a' }, { id: 'a', title: 'first' }));++ const onSuccess = vi.fn();+ renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));+ act(() => slice.removeEntity('a'));+ expect(store.getState().items.a).toBeUndefined();++ act(() => settle({ id: 'a', title: 'stale' }));+ expect(store.getState().items.a).toBeUndefined();+ expect(onSuccess).not.toHaveBeenCalled();+ });++ // a → b while a's request is in flight: a's late response still fills its+ // own cache entry, but its success side effects act on the CURRENT view, so+ // they must not re-adopt `a` while the hook shows `b`.+ it('does not replay a response for a key the hook has moved past', () => {+ let settle!: (data: string[]) => void;+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {+ if (key !== null) settle = options.onSuccess;+ return { isValidating: false, mutate: vi.fn() };+ });+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async ({ id }) => [id],+ key: ({ id }) => id,+ name: 'lateKeyResponse',+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ const onSuccess = vi.fn();+ const { rerender } = renderHook(({ id }) => slice.useSync({ id }, { onSuccess }), {+ initialProps: { id: 'a' },+ });+ const settleA = settle;++ rerender({ id: 'b' });+ const settleB = settle;+ act(() => settleA(['late-a']));++ expect(store.getState().lists.a).toEqual(['late-a']);+ expect(onSuccess).not.toHaveBeenCalled();++ act(() => settleB(['b']));+ expect(onSuccess).toHaveBeenCalledTimes(1);+ expect(onSuccess).toHaveBeenCalledWith(['b']);+ });+ });+});diff --git a/packages/replica/src/zustand/createReplicaSlice.scope.test.ts b/packages/replica/src/zustand/createReplicaSlice.scope.test.tsnew file mode 100644index 00000000000..2fc0bde4393--- /dev/null+++ b/packages/replica/src/zustand/createReplicaSlice.scope.test.ts@@ -0,0 +1,135 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { createMemoryStorage, resetScopeState, scopeState, setup, wrapper } from './testUtils';++beforeEach(resetScopeState);++describe('createReplicaSlice', () => {+ describe('scope isolation', () => {+ it('clears the previous identity and drops its late results', async () => {+ const { slice, store, storage } = setup();+ act(() => {+ slice.replace({ id: 'a' }, ['user-1-data']);+ });+ expect(store.getState().lists.a).toEqual(['user-1-data']);++ scopeState.current = 'user-2:personal';+ // A response that was in flight for user 1 lands after the switch.+ act(() => {+ slice.replace({ id: 'a' }, ['late-user-1'], 'user-1:personal');+ });+ expect(store.getState().lists.a).toEqual(['user-1-data']);++ // The first action under the new identity resets memory.+ act(() => {+ slice.replace({ id: 'b' }, ['user-2-data']);+ });+ expect(store.getState().lists).toEqual({ b: ['user-2-data'] });+ expect(store.getState().listsReplica.scope).toBe('user-2:personal');++ await waitFor(() => expect(storage.rows.size).toBe(2));+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['user-1-data']);+ expect(storage.rows.get('user-2:personal|b')?.data).toEqual(['user-2-data']);+ });++ it('useSync clears the previous identity even when the new scope has nothing to hydrate', async () => {+ const fetcher = vi.fn(() => new Promise<string[]>(() => {}));+ const { slice, store } = setup({ fetcher });+ act(() => {+ slice.replace({ id: 'a' }, ['user-1-data']);+ });++ scopeState.current = 'user-2:personal';+ const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ await waitFor(() => expect(result.current.isHydrated).toBe(true));+ expect(store.getState().lists).toEqual({});+ expect(store.getState().listsReplica.scope).toBe('user-2:personal');+ });++ it('hydrates only the active scope partition', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-2:personal|a', { data: ['someone-else'], updatedAt: 1 });+ const { slice, store } = setup({ storage });++ await act(async () => {+ await slice.hydrate({ id: 'a' });+ });++ expect(store.getState().lists.a).toBeUndefined();+ });++ it('does not hydrate the persisted projection when the runtime opts out', async () => {+ // An identity-less runtime (e.g. the public Workbench) can only guess the+ // scope, so it must not read another session's rows back into memory.+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['someone-elses'], updatedAt: 1 });+ scopeState.canHydrate = false;+ const { slice, store } = setup({ storage });++ await act(async () => {+ await slice.hydrate({ id: 'a' });+ });++ expect(store.getState().lists.a).toBeUndefined();+ expect(store.getState().listsReplica.entries.a).toBeUndefined();+ });++ it('never persists while the scope is untrusted', async () => {+ scopeState.trusted = false;+ const { slice, storage } = setup();+ act(() => {+ slice.replace({ id: 'a' }, ['server']);+ });+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(storage.writes).toEqual([]);+ });++ it('retries a removal whose storage delete failed, instead of treating it as purged', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });+ const { slice } = setup({ storage });++ const original = storage.storage.remove;+ let attempts = 0;+ storage.storage.remove = async (key) => {+ attempts += 1;+ if (attempts === 1) throw new Error('IndexedDB delete failed');+ return original(key);+ };++ // The first delete is rejected by storage: the guard is armed, but the row+ // is still on disk and must NOT be treated as purged.+ act(() => slice.remove('a'));+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(storage.rows.get('user-1:personal|a')).toBeDefined();++ // A later terminal answer must retry the delete rather than no-op.+ act(() => slice.remove('a'));+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ expect(attempts).toBeGreaterThanOrEqual(2);+ });++ it('retries the storage delete of a removal made while the scope was untrusted', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });+ const { slice } = setup({ storage });++ // Cold boot: identity is not resolved, so writes are refused and the+ // delete never reaches storage — the hydration guard is armed all the same.+ scopeState.trusted = false;+ act(() => slice.remove('a'));+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(storage.rows.get('user-1:personal|a')).toBeDefined();++ // Identity resolves: the next removal must clear the row, not no-op.+ scopeState.trusted = true;+ act(() => slice.remove('a'));+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ });+ });+});diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.tsdeleted file mode 100644index 58aebde33bb..00000000000--- a/packages/replica/src/zustand/createReplicaSlice.test.ts+++ /dev/null@@ -1,1940 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { act, renderHook, waitFor } from '@testing-library/react';-import type { PropsWithChildren } from 'react';-import { createElement } from 'react';-import { SWRConfig } from 'swr';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createStore } from 'zustand/vanilla';--import { testDriver as driver } from '../../tests/testDriver';-import { defineReplica } from '../core/defineReplica';-import { REPLICA_INDEX_KEY } from '../core/engine';-import { singleEntity } from '../core/entityAdapters';-import { createReplicaState } from '../core/reducer';-import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';-import { createReplicaSlice, recordLens } from './createReplicaSlice';--interface TestState {- lists: Record<string, string[]>;- listsReplica: ReplicaState<string[]>;-}--const scopeState = { canHydrate: true, current: 'user-1:personal', trusted: true };-const scope: ReplicaScope = {- canHydrate: () => scopeState.canHydrate,- canPersist: () => scopeState.trusted,- get: () => scopeState.current,- // The real `use` is `useCacheScope`; a plain getter is enough for these tests.- use: () => scopeState.current,-};--/** In-memory storage that records every write, keyed like the real ones. */-const createMemoryStorage = (delays: Record<string, number> = {}) => {- const rows = new Map<string, ReplicaRow<string[]>>();- const writes: string[] = [];- const indexRows = new Map<string, ReplicaRow<string[]>>();- const read: ReplicaStorage<string[]>['get'] = async ({ queryKey, scope }) =>- queryKey === REPLICA_INDEX_KEY- ? (indexRows.get(scope) as ReplicaRow<string[]> | undefined)- : rows.get(`${scope}|${queryKey}`);- const storage: ReplicaStorage<string[]> = {- get: read,- getStrict: read,- remove: async ({ queryKey, scope }) => {- if (queryKey === REPLICA_INDEX_KEY) return void indexRows.delete(scope);- rows.delete(`${scope}|${queryKey}`);- },- set: async ({ queryKey, scope }, projection) => {- // The per-scope index of persisted rows is bookkeeping, not a data write.- if (queryKey === REPLICA_INDEX_KEY) return void indexRows.set(scope, projection);- const delay = delays[projection.data.join(',')] ?? 0;- if (delay) await new Promise((resolve) => setTimeout(resolve, delay));- writes.push(projection.data.join(','));- rows.set(`${scope}|${queryKey}`, projection);- },- };- return { indexRows, rows, storage, writes };-};--const setup = ({- fetcher = vi.fn(async (_params: { id: string }) => ['server']),- storage = createMemoryStorage(),- version = 1,-}: {- fetcher?: (params: { id: string }) => Promise<string[]>;- storage?: ReturnType<typeof createMemoryStorage>;- version?: number;-} = {}) => {- const resource = defineReplica<{ id: string }, string[]>({- fetcher,- key: ({ id }) => id,- name: 'testList',- scope,- storage: storage.storage,- version,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });- return { fetcher, resource, slice, storage, store };-};--const wrapper = ({ children }: PropsWithChildren) =>- createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);--beforeEach(() => {- scopeState.canHydrate = true;- scopeState.current = 'user-1:personal';- scopeState.trusted = true;-});--describe('createReplicaSlice', () => {- describe('useSync', () => {- it('paints the persisted projection while the network request is in flight', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- let resolveFetch!: (value: string[]) => void;- const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));- const { slice, store } = setup({ fetcher, storage });-- const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));- // Background loading never hides the hydrated data.- expect(result.current.isHydrated).toBe(true);- expect(result.current.isValidating).toBe(true);-- await act(async () => resolveFetch(['server']));-- await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));- expect(store.getState().listsReplica.entries.a.source).toBe('server');- await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['server']));- });-- it('runs onSuccess after the response is folded in, and onError on a failed fetch', async () => {- const { slice, store } = setup();- const seen: unknown[] = [];- renderHook(- () =>- slice.useSync(- { id: 'a' },- { onSuccess: (data) => seen.push([data, store.getState().lists.a]) },- ),- { wrapper },- );- // The callback already sees the store view the response produced.- await waitFor(() => expect(seen).toEqual([[['server'], ['server']]]));-- const failure = new Error('offline');- const onError = vi.fn();- const failing = setup({- fetcher: vi.fn(async () => {- throw failure;- }),- });- renderHook(() => failing.slice.useSync({ id: 'b' }, { onError }), { wrapper });- // The callback also receives the key/scope the failing read was captured- // under, so a terminal removal can be bound to the right scope.- await waitFor(() =>- expect(onError).toHaveBeenCalledWith(failure, {- isActive: true,- key: 'b',- scope: 'user-1:personal',- }),- );- expect(failing.store.getState().lists.b).toBeUndefined();- });-- it('runs onHydrated with the hydrated value, and skips it when nothing was stored', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- let resolveFetch!: (value: string[]) => void;- const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));- const { slice, store } = setup({ fetcher, storage });- const seen: string[][] = [];- renderHook(() => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }), {- wrapper,- });-- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));- expect(seen).toEqual([['cached']]);-- await act(async () => resolveFetch(['server']));- await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));- // The network response stays `onSuccess`'s job; onHydrated does not fire for it.- expect(seen).toEqual([['cached']]);-- // An empty slot has no persisted value, so nothing is replayed.- const empty = setup();- const missed = vi.fn();- renderHook(() => empty.slice.useSync({ id: 'b' }, { onHydrated: missed }), { wrapper });- await waitFor(() => expect(empty.store.getState().lists.b).toEqual(['server']));- expect(missed).not.toHaveBeenCalled();- });-- it('drops the prior persisted projection when `toPersisted` reports a confirmed absence', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- const resource = defineReplica<{ id: string }, string[]>({- // The server confirms the id no longer exists.- fetcher: vi.fn(async () => []),- key: ({ id }) => id,- name: 'absentList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- // An empty list is a confirmed absence: drop the stored row instead of- // leaving the stale projection to be hydrated again.- toPersisted: (data) => (data.length ? data : null),- view: recordLens('lists'),- });-- renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- // The confirmed absence replaces the hydrated value in the view…- await waitFor(() => expect(store.getState().lists.a).toEqual([]));- // …and the stale persisted projection is gone, so a reload cannot paint it.- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });-- it('keeps the stored row when `toPersisted` returns undefined (skip)', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: vi.fn(async () => ['server']),- key: ({ id }) => id,- name: 'skippedList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- // `undefined` means "skip this write", not "remove".- toPersisted: () => undefined,- view: recordLens('lists'),- });-- renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']);- });-- it('hands its schedule (polling, focus revalidation …) to the driver', () => {- const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'scheduled',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- renderHook(() =>- slice.useSync({ id: 'a' }, { refreshInterval: 10_000, revalidateOnFocus: false }),- );-- expect(useQuery).toHaveBeenCalledWith(- expect.arrayContaining(['replica:sync', 'scheduled']),- expect.any(Function),- expect.objectContaining({ refreshInterval: 10_000, revalidateOnFocus: false }),- );- });-- it('discards a head response from a query the entry has moved past', () => {- // A driver that settles every request through its own callback lets two- // queries of the same key resolve out of order. One entry backs one view,- // so the query the entry no longer asks for must not repaint it.- const requests: {- onSuccess: (data: string[]) => void;- params: { q?: string };- }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) requests.push({ onSuccess: options.onSuccess, params: key.at(-1) });- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ q?: string }, string[]>({- fetcher: async () => ['server'],- key: () => 'all',- name: 'orderedHead',- query: ({ q }) => ({ q }),- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { q?: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const { rerender } = renderHook((props: { q?: string }) => slice.useSync(props), {- initialProps: {} as { q?: string },- });- rerender({ q: 'b' });-- const base = requests.find((request) => request.params.q === undefined)!;- const search = requests.find((request) => request.params.q === 'b')!;-- act(() => search.onSuccess(['b-1']));- expect(store.getState().lists.all).toEqual(['b-1']);-- // The superseded query settles late: it must not overwrite the search.- act(() => base.onSuccess(['a-1']));- expect(store.getState().lists.all).toEqual(['b-1']);- });-- it('syncs under a custom key when the resource adopts one', () => {- const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'customKeyed',- scope,- syncKey: ({ id }) => ['legacy:list', id],- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- renderHook(() => slice.useSync({ id: 'a' }));-- expect(useQuery).toHaveBeenCalledWith(- ['legacy:list', 'a'],- expect.any(Function),- expect.any(Object),- );- });-- it('does not let a slow hydration overwrite a faster server response', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });- const originalGet = storage.storage.get;- storage.storage.get = async (key) => {- await new Promise((resolve) => setTimeout(resolve, 30));- return originalGet(key);- };- const { slice, store } = setup({ storage });-- const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(result.current.isHydrated).toBe(true));- expect(store.getState().lists.a).toEqual(['server']);- });-- it('does not let a slow hydration resurrect an entry removed while it was in flight', async () => {- // A NOT_FOUND / FORBIDDEN response removes the entry (and its row) while- // the persisted read is still in flight. That read already holds the old- // row, so landing it afterwards would repaint the value just dropped.- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const originalGet = storage.storage.get;- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- storage.storage.get = async (key) => {- const row = await originalGet(key);- if (key.queryKey === 'a') await held;- return row;- };- const { slice, store } = setup({ storage });-- let hydration!: Promise<boolean>;- await act(async () => {- hydration = slice.hydrate({ id: 'a' });- });-- // The network answers first and drops the entry.- act(() => slice.remove('a'));- expect(store.getState().lists.a).toBeUndefined();-- // The slow read settles: it must not paint the row the removal dropped.- await act(async () => {- release();- await hydration;- });-- expect(store.getState().lists.a).toBeUndefined();- expect(store.getState().listsReplica.entries.a).toBeUndefined();- });-- it('refuses to hydrate a key that was explicitly removed even if its row is still on disk', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- act(() => slice.remove('a'));- // The delete may not have flushed yet — the row must not come back anyway.- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('lets a later server value supersede a removal so the key hydrates again', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- act(() => slice.remove('a'));- // Access restored: the server now answers with a value again.- act(() => slice.replace({ id: 'a' }, ['regranted']));- expect(store.getState().lists.a).toEqual(['regranted']);- // Let the confirmed value reach the persisted row before reading it back.- await waitFor(() =>- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['regranted']),- );-- // Drop memory the way a scope switch does, then come back: with the- // removal superseded, the persisted row may hydrate once more.- scopeState.current = 'user-2:personal';- act(() => slice.ensureScope('user-2:personal'));- scopeState.current = 'user-1:personal';- act(() => slice.ensureScope('user-1:personal'));-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(true);- });- expect(store.getState().lists.a).toEqual(['regranted']);- });-- it('reports a keyless (disabled) read as hydrated, so it never looks loading', () => {- const { slice } = setup();-- const { result } = renderHook(() => slice.useSync(null), { wrapper });-- expect(result.current.isHydrated).toBe(true);- expect(result.current.isValidating).toBe(false);- });-- it('keeps the removal guard when a response captured under another scope is discarded', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- // The persisted-row delete is best-effort: simulate it still being pending.- storage.storage.remove = async () => {};- const { slice, store } = setup({ storage });-- // Scope A removes the entry (and arms its guard).- act(() => slice.remove('a'));-- // A response captured under A resolves only after the user switched to B,- // so `dispatch` drops it. It must not clear A's guard on the way out.- scopeState.current = 'user-2:personal';- act(() => slice.replace({ id: 'a' }, ['stale'], 'user-1:personal'));-- // Switching back to A must still refuse to hydrate the stale row.- scopeState.current = 'user-1:personal';- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('runs the caller success side effects when the response changes nothing', () => {- // `replace` reports false both for a rejected response and for one with- // nothing to write (an unchanged revalidation, or `undefined` for an id the- // server no longer has). Callers rely on onSuccess in the latter cases —- // e.g. removing a cached detail the server answered with nothing.- const requests: { onSuccess: (data: string[] | undefined) => void }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null && options?.onSuccess) requests.push({ onSuccess: options.onSuccess });- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'noopSuccessSideEffects',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: { a: ['same'] },- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- scopeState.current = 'user-1:personal';- const onSuccess = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }), { wrapper });- const request = requests.find((entry) => entry)!;-- act(() => request.onSuccess(['same']));- act(() => request.onSuccess(['same']));- act(() => request.onSuccess(undefined));-- expect(onSuccess).toHaveBeenCalledTimes(3);- expect(onSuccess).toHaveBeenLastCalledWith(undefined);- });-- it("drops a settled request's success side effects once the store has left its scope", () => {- // A response can settle after an identity/workspace switch. The engine- // refuses the off-scope `replace`, but the caller's callbacks carry the- // previous identity's side effects, so they must not run either — and a- // switch to a scope reading the same key/query defeats both the- // moved-past-query and since-clear guards.- const requests: {- onError: (error: unknown) => void;- onSuccess: (data: string[]) => void;- }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) requests.push({ onError: options.onError, onSuccess: options.onSuccess });- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'staleScopeCallbacks',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const onSuccess = vi.fn();- const onError = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onError, onSuccess }), { wrapper });-- const captured = requests.find((request) => request)!;-- // The identity/workspace switches while the request is still in flight.- scopeState.current = 'user-2:personal';-- act(() => captured.onSuccess(['stale']));- expect(onSuccess).not.toHaveBeenCalled();- expect(store.getState().lists.a).toBeUndefined();-- // A failure is still handed over, bound to the scope it was captured- // under and flagged as no longer active, so the caller can purge that- // scope's row (see below) without repainting the current view.- act(() => captured.onError(new Error('stale')));- expect(onError).toHaveBeenCalledWith(expect.any(Error), {- isActive: false,- key: 'a',- scope: 'user-1:personal',- });- });-- it('lets a late terminal error purge its captured scope through the sync callback', async () => {- const requests: { onError: (error: unknown) => void }[] = [];- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- // The sync request carries the callbacks; the hydration read does not.- if (key !== null && options?.onError) requests.push({ onError: options.onError });- return { isValidating: false, mutate: vi.fn() };- });- const memory = createMemoryStorage();- memory.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'lateTerminalError',- scope,- storage: memory.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- scopeState.current = 'user-1:personal';- const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];- renderHook(- () =>- slice.useSync(- { id: 'a' },- {- onError: (_error, context) => {- contexts.push(context);- if (context.key) slice.remove(context.key, context.scope);- },- },- ),- { wrapper },- );- const request = requests.find((entry) => entry)!;-- // The identity switches and loads its own entry before the denial lands.- scopeState.current = 'user-2:personal';- act(() => slice.replace({ id: 'a' }, ['b-value']));-- act(() => request.onError(new Error('NOT_FOUND')));-- // The callback still runs, flagged as belonging to a scope left behind, so- // the consumer can purge that scope without repainting the current one.- expect(contexts[0]).toMatchObject({ isActive: false, key: 'a', scope: 'user-1:personal' });- // The scope on screen keeps its entry; the denied scope's row is purged.- expect(store.getState().lists.a).toEqual(['b-value']);- await waitFor(() => expect(memory.rows.get('user-1:personal|a')).toBeUndefined());- });-- // The guard lives in the engine, per scope — not in the bookkeeping slot a- // scope reset wipes — so an A → B → A round trip cannot lift it.- it('keeps the removal guard across a scope round trip', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- // The persisted-row delete is still pending: the stale row stays on disk.- storage.storage.remove = async () => {};- const { slice, store } = setup({ storage });-- act(() => slice.remove('a'));-- scopeState.current = 'user-2:personal';- act(() => slice.ensureScope('user-2:personal'));- expect(store.getState().listsReplica.scope).toBe('user-2:personal');- scopeState.current = 'user-1:personal';- act(() => slice.ensureScope('user-1:personal'));-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('purges the captured scope row for a removal that lands after a scope switch', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- // The active scope has its own entry loaded.- scopeState.current = 'user-2:personal';- act(() => slice.replace({ id: 'a' }, ['b-value']));- expect(store.getState().lists.a).toEqual(['b-value']);-- // A late NOT_FOUND from a request captured under the previous scope must- // not delete the entry that is on screen now…- act(() => slice.remove('a', 'user-1:personal'));- expect(store.getState().lists.a).toEqual(['b-value']);-- // …but that scope's own persisted row still has to go, or switching back- // to it would hydrate the value the server just denied.- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });-- it('retries an off-scope purge once the captured scope may persist again', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });- const { slice } = setup({ storage });-- // The terminal answer lands while writes are still refused.- scopeState.current = 'user-2:personal';- scopeState.trusted = false;- act(() => slice.remove('a', 'user-1:personal'));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.get('user-1:personal|a')).toBeDefined();-- // Identity resolves: the next terminal answer must clear the row, not- // report a no-op that never deletes it.- scopeState.trusted = true;- act(() => slice.remove('a', 'user-1:personal'));- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });-- it('binds the captured key and scope to the error callback', async () => {- const fetcher = vi.fn(async () => {- throw new Error('not found');- });- const { slice } = setup({ fetcher });- const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];-- scopeState.current = 'user-1:personal';- renderHook(- () => slice.useSync({ id: 'a' }, { onError: (_error, context) => contexts.push(context) }),- { wrapper },- );-- await waitFor(() => expect(contexts.length).toBeGreaterThan(0));- expect(contexts[0]).toEqual({ isActive: true, key: 'a', scope: 'user-1:personal' });- });-- it('evicts the persisted row when a response has nothing to persist', async () => {- // Two bindings share one storage, so the second one reads what the first- // one left behind — a reload of the same resource.- const storage = createMemoryStorage();- const bind = () => {- const resource = defineReplica<{ id: string }, string[]>({- key: ({ id }) => id,- name: 'evictingList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- // `['gone']` is a page state that must never be persisted.- toPersisted: (data) => (data[0] === 'gone' ? null : data),- view: recordLens('lists'),- });- return { slice, store };- };-- const first = bind();- act(() => {- first.slice.replace({ id: 'a' }, ['cached']);- });- await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));-- act(() => {- first.slice.replace({ id: 'a' }, ['gone']);- });- // The value stays in memory…- expect(first.store.getState().lists.a).toEqual(['gone']);- // …while the row persisted for it earlier is removed.- await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));-- // A reload hydrates nothing instead of resurrecting the evicted value.- const reloaded = bind();- await act(async () => {- await reloaded.slice.hydrate({ id: 'a' });- });- expect(reloaded.store.getState().lists.a).toBeUndefined();- });-- it('clears a reloaded key from the persisted index when the response has nothing to persist', async () => {- const storage = createMemoryStorage();- const indexKey = { queryKey: REPLICA_INDEX_KEY, scope: 'user-1:personal' };- const bind = () => {- const resource = defineReplica<{ id: string }, string[]>({- key: ({ id }) => id,- name: 'indexedList',- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- toPersisted: (data) => (data[0] === 'gone' ? null : data),- view: recordLens('lists'),- });- return { slice, store };- };-- const first = bind();- act(() => {- first.slice.replace({ id: 'a' }, ['cached']);- });- await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));- await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual(['a']));-- // A reload: a fresh engine whose in-memory index bookkeeping is empty, so- // only the persisted index knows the key is there.- const reloaded = bind();- await act(async () => {- await reloaded.slice.hydrate({ id: 'a' });- });- expect(reloaded.store.getState().lists.a).toEqual(['cached']);-- act(() => {- reloaded.slice.replace({ id: 'a' }, ['gone']);- });- // The row goes…- await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));- // …and so does its index entry, so later entity scans do not chase a- // missing row.- await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual([]));- });-- // The removal deletes the entry, but a storage read that started before it- // can still resolve afterwards; the replica must not let that stale read- // resurrect the removed entry (the server already confirmed it gone).- it('does not let a hydrate that resolves after a removal resurrect the entry', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const realGet = storage.storage.get.bind(storage.storage);- let releaseRead!: () => void;- const readGate = new Promise<void>((resolve) => (releaseRead = resolve));- let readStarted = false;- vi.spyOn(storage.storage, 'get').mockImplementation(async (key) => {- if (key.queryKey === 'a') {- // A storage read is a snapshot: capture the row now, resolve later.- const snapshot = await realGet(key);- readStarted = true;- await readGate;- return snapshot;- }- return realGet(key);- });-- // A network that never answers, so only the hydrate is at play.- const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });-- let hydrated = false;- const session = renderHook(- () => slice.useSync({ id: 'a' }, { onHydrated: () => (hydrated = true) }),- { wrapper },- );- await waitFor(() => expect(readStarted).toBe(true));-- // The key is removed (a server-confirmed absence) before the read lands.- act(() => slice.remove('a'));-- releaseRead();- await act(async () => {});-- expect(hydrated).toBe(false);- expect(store.getState().lists.a).toBeUndefined();- expect(store.getState().listsReplica.entries.a).toBeUndefined();- session.unmount();- });-- // a → b → a: a's hydration query already settled and is not re-run, so its- // side effects must be replayed off the cached value when `a` is active again- // — or they stay pointed at `b` until (or, offline, without) a response.- it('replays onHydrated when a hydrated key becomes active again', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached-a'], updatedAt: 1 });- storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });- // Offline: the network never answers, so only hydration can run effects.- const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });- const seen: string[][] = [];-- const session = renderHook(- ({ id }: { id: string }) =>- slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),- { initialProps: { id: 'a' }, wrapper },- );- await waitFor(() => expect(session.result.current.isHydrated).toBe(true));- // The first activation runs it once, from the hydrate itself.- expect(seen).toEqual([['cached-a']]);-- session.rerender({ id: 'b' });- await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b']]));-- session.rerender({ id: 'a' });- await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b'], ['cached-a']]));- expect(store.getState().lists.a).toEqual(['cached-a']);-- // A plain re-render of the same key does not replay again.- session.rerender({ id: 'a' });- await act(async () => {});- expect(seen).toHaveLength(3);- session.unmount();- });-- // Scope A → B → A with the same key: B's activation cleared the view and- // A's `once` hydration result is reused, so the slice must read A's- // partition again — offline, nothing else would bring the row back.- it('rehydrates an entry after returning to a prior scope', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['cached-a1'], updatedAt: 1 });- storage.rows.set('user-2:personal|a', { data: ['cached-a2'], updatedAt: 1 });- const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });- const seen: string[][] = [];-- const session = renderHook(- () => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }),- { wrapper },- );- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));-- scopeState.current = 'user-2:personal';- session.rerender();- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a2']));-- scopeState.current = 'user-1:personal';- session.rerender();- await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));- // Its side effects follow the row back too.- await waitFor(() => expect(seen.at(-1)).toEqual(['cached-a1']));- session.unmount();- });-- // A lookup that missed storage settles `true` as well; reactivating its key- // must not replay `onHydrated` off a value that never came from storage- // (a provisional seed written into the view).- it('does not replay onHydrated for a reactivated key whose lookup missed storage', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });- const { slice } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });- const seen: string[][] = [];-- const session = renderHook(- ({ id }: { id: string }) =>- slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),- { initialProps: { id: 'a' }, wrapper },- );- await waitFor(() => expect(session.result.current.isHydrated).toBe(true));- expect(seen).toEqual([]);-- session.rerender({ id: 'b' });- await waitFor(() => expect(seen).toEqual([['cached-b']]));-- // A seed lands in `a`'s view while the hook shows `b`.- act(() => {- slice.update('a', () => ['seed-a'], { persist: false, source: 'seed' });- });- session.rerender({ id: 'a' });- await act(async () => {});- expect(seen).toEqual([['cached-b']]);- session.unmount();- });-- it('a version bump ignores rows written by the previous version', async () => {- // One backing map shared by every version, keyed by the namespace the- // factory receives — like IndexedDB rows of two app releases.- const backing = new Map<string, ReplicaRow<string[]>>();- const namespaced = (namespace: string): ReplicaStorage<string[]> => ({- get: async ({ queryKey, scope }) => backing.get(`${namespace}|${scope}|${queryKey}`),- remove: async ({ queryKey, scope }) => {- backing.delete(`${namespace}|${scope}|${queryKey}`);- },- set: async ({ queryKey, scope }, row) => {- backing.set(`${namespace}|${scope}|${queryKey}`, row);- },- });- const bind = (version: number) => {- const resource = defineReplica<{ id: string }, string[]>({- key: ({ id }) => id,- name: 'versionedList',- scope,- storage: namespaced,- version,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });- return { slice, store };- };-- const v1 = bind(1);- act(() => {- v1.slice.replace({ id: 'a' }, ['v1-shape']);- });- const dataKeys = () => [...backing.keys()].filter((key) => !key.includes(REPLICA_INDEX_KEY));- await waitFor(() => expect(dataKeys()).toHaveLength(1));-- const v1Reload = bind(1);- await act(async () => {- await v1Reload.slice.hydrate({ id: 'a' });- });- expect(v1Reload.store.getState().lists.a).toEqual(['v1-shape']);-- const v2 = bind(2);- await act(async () => {- await v2.slice.hydrate({ id: 'a' });- });- expect(v2.store.getState().lists.a).toBeUndefined();- });- });-- describe('remove', () => {- it('does not let an in-flight response resurrect a removed entry', async () => {- let resolveFetch!: (value: string[]) => void;- const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));- const { slice, store } = setup({ fetcher });-- renderHook(() => slice.useSync({ id: 'a' }), { wrapper });- await waitFor(() => expect(fetcher).toHaveBeenCalled());-- // The entry is invalidated while its own request is still in flight.- act(() => {- slice.remove('a');- });- await act(async () => resolveFetch(['late']));-- expect(store.getState().lists.a).toBeUndefined();- });- });-- describe('persisted index', () => {- it('removes a key this instance never wrote from the stored index', async () => {- const storage = createMemoryStorage();- // An earlier session persisted this row and listed it in the index. This- // instance has no memory of the key — the eviction / invalidation case- // where the index write must still reach storage.- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- storage.indexRows.set('user-1:personal', { data: ['a'], updatedAt: 1 });- const { slice } = setup({ storage });-- act(() => slice.remove('a'));-- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));- });- });-- describe('scope isolation', () => {- it('clears the previous identity and drops its late results', async () => {- const { slice, store, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['user-1-data']);- });- expect(store.getState().lists.a).toEqual(['user-1-data']);-- scopeState.current = 'user-2:personal';- // A response that was in flight for user 1 lands after the switch.- act(() => {- slice.replace({ id: 'a' }, ['late-user-1'], 'user-1:personal');- });- expect(store.getState().lists.a).toEqual(['user-1-data']);-- // The first action under the new identity resets memory.- act(() => {- slice.replace({ id: 'b' }, ['user-2-data']);- });- expect(store.getState().lists).toEqual({ b: ['user-2-data'] });- expect(store.getState().listsReplica.scope).toBe('user-2:personal');-- await waitFor(() => expect(storage.rows.size).toBe(2));- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['user-1-data']);- expect(storage.rows.get('user-2:personal|b')?.data).toEqual(['user-2-data']);- });-- it('useSync clears the previous identity even when the new scope has nothing to hydrate', async () => {- const fetcher = vi.fn(() => new Promise<string[]>(() => {}));- const { slice, store } = setup({ fetcher });- act(() => {- slice.replace({ id: 'a' }, ['user-1-data']);- });-- scopeState.current = 'user-2:personal';- const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });-- await waitFor(() => expect(result.current.isHydrated).toBe(true));- expect(store.getState().lists).toEqual({});- expect(store.getState().listsReplica.scope).toBe('user-2:personal');- });-- it('hydrates only the active scope partition', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-2:personal|a', { data: ['someone-else'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- await act(async () => {- await slice.hydrate({ id: 'a' });- });-- expect(store.getState().lists.a).toBeUndefined();- });-- it('does not hydrate the persisted projection when the runtime opts out', async () => {- // An identity-less runtime (e.g. the public Workbench) can only guess the- // scope, so it must not read another session's rows back into memory.- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['someone-elses'], updatedAt: 1 });- scopeState.canHydrate = false;- const { slice, store } = setup({ storage });-- await act(async () => {- await slice.hydrate({ id: 'a' });- });-- expect(store.getState().lists.a).toBeUndefined();- expect(store.getState().listsReplica.entries.a).toBeUndefined();- });-- it('never persists while the scope is untrusted', async () => {- scopeState.trusted = false;- const { slice, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['server']);- });- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.writes).toEqual([]);- });-- it('retries a removal whose storage delete failed, instead of treating it as purged', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const { slice } = setup({ storage });-- const original = storage.storage.remove;- let attempts = 0;- storage.storage.remove = async (key) => {- attempts += 1;- if (attempts === 1) throw new Error('IndexedDB delete failed');- return original(key);- };-- // The first delete is rejected by storage: the guard is armed, but the row- // is still on disk and must NOT be treated as purged.- act(() => slice.remove('a'));- await new Promise((resolve) => setTimeout(resolve, 20));- expect(storage.rows.get('user-1:personal|a')).toBeDefined();-- // A later terminal answer must retry the delete rather than no-op.- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- expect(attempts).toBeGreaterThanOrEqual(2);- });-- it('retries the storage delete of a removal made while the scope was untrusted', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const { slice } = setup({ storage });-- // Cold boot: identity is not resolved, so writes are refused and the- // delete never reaches storage — the hydration guard is armed all the same.- scopeState.trusted = false;- act(() => slice.remove('a'));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.get('user-1:personal|a')).toBeDefined();-- // Identity resolves: the next removal must clear the row, not no-op.- scopeState.trusted = true;- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());- });- });-- describe('invalidation', () => {- interface QueryParams {- id: string;- q?: string;- }- /** A resource whose rows are persisted per query (`a`, `a?{"q":"x"}` …). */- const setupQueried = ({- driver: queryDriver = driver,- storage = createMemoryStorage(),- }: {- driver?: Parameters<typeof createReplicaSlice>[1]['driver'];- storage?: ReturnType<typeof createMemoryStorage>;- } = {}) => {- const resource = defineReplica<QueryParams, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'queriedList',- query: ({ q }) => ({ q }),- scope,- storage: storage.storage,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, QueryParams, string[]>(resource, {- driver: queryDriver,- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });- return { resource, slice, storage, store };- };- const row = (resource: { storageKey: (params: QueryParams) => string }, params: QueryParams) =>- `user-1:personal|${resource.storageKey(params)}`;-- /** Persist `a` (unfiltered + filtered) and `ab` in one session. */- const persistVariants = async () => {- const first = setupQueried();- act(() => {- first.slice.replace({ id: 'a' }, ['a-all']);- first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);- first.slice.replace({ id: 'ab' }, ['ab-all']);- });- await waitFor(() => expect(first.storage.rows.size).toBe(3));- return first;- };-- it('remove drops every persisted query variant of the key, not only the one in memory', async () => {- const { resource, slice, storage } = await persistVariants();-- // Memory holds the filtered query; the unfiltered row was persisted earlier.- act(() => slice.remove('a'));-- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);- });- // Another key that merely shares the prefix is untouched.- expect(storage.rows.get(row(resource, { id: 'ab' }))?.data).toEqual(['ab-all']);- });-- it('remove drops variants persisted by an earlier session, through the index', async () => {- const first = await persistVariants();- // Reload: memory is empty, only the persisted index knows the variants.- const { resource, slice, storage, store } = setupQueried({ storage: first.storage });-- act(() => slice.remove('a'));-- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);- });- // No variant of the removed key hydrates.- await act(async () => {- expect(await slice.hydrate({ id: 'a', q: 'x' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('an off-scope purge drops every query variant of its scope', async () => {- const { resource, slice, storage } = await persistVariants();-- scopeState.current = 'user-2:personal';- act(() => slice.remove('a', 'user-1:personal'));-- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);- });- });-- /** Make storage reject the first delete of `queryKey` (a closed IndexedDB). */- const failFirstDelete = (storage: ReturnType<typeof createMemoryStorage>, queryKey: string) => {- const original = storage.storage.remove;- let failed = false;- storage.storage.remove = async (key) => {- if (key.queryKey === queryKey && !failed) {- failed = true;- throw new Error('IndexedDB delete failed');- }- return original(key);- };- };-- it('keeps a variant whose delete failed indexed, so a later remove retries it', async () => {- const { resource, slice, storage } = await persistVariants();- const filtered = row(resource, { id: 'a', q: 'x' });- failFirstDelete(storage, resource.storageKey({ id: 'a', q: 'x' }));- // Memory holds another variant, so the failing row is found through the index.- act(() => slice.replace({ id: 'a' }, ['a-all']));-- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.has(filtered)).toBe(true);-- // The next removal still knows about the failed row and retries it.- act(() => slice.remove('a'));- await waitFor(() => expect(storage.rows.has(filtered)).toBe(false));- });-- it('keeps a row whose delete failed indexed, so a later clear retries it', async () => {- const { resource, slice, storage } = await persistVariants();- failFirstDelete(storage, resource.storageKey({ id: 'ab' }));-- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(false);- expect([...storage.rows.keys()]).toEqual([row(resource, { id: 'ab' })]);-- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(true);- expect(storage.rows.size).toBe(0);- });-- /**- * Storage whose index read fails the way the app adapters do: `get`- * swallows it into a miss, only `getStrict` reports it.- */- const failIndexReads = (storage: ReturnType<typeof createMemoryStorage>) => {- const state = { failing: true };- const original = storage.storage.get;- storage.storage.get = async (key) =>- key.queryKey === REPLICA_INDEX_KEY && state.failing ? undefined : original(key);- storage.storage.getStrict = async (key) => {- if (key.queryKey === REPLICA_INDEX_KEY && state.failing)- throw new Error('IndexedDB read failed');- return original(key);- };- return state;- };-- it('reports a clear as failed when the index cannot be read, and a later clear retries', async () => {- const first = await persistVariants();- // Reload: only the persisted index knows the earlier session's rows.- const { slice, storage, store } = setupQueried({ storage: first.storage });- const index = failIndexReads(storage);-- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(false);- expect(storage.rows.size).toBe(3);- // Hydration stays off while the wipe is incomplete.- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();-- index.failing = false;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(true);- expect(storage.rows.size).toBe(0);- });-- it('keeps a removal unpurged when the index cannot be read, so it retries', async () => {- const first = await persistVariants();- const { resource, slice, storage } = setupQueried({ storage: first.storage });- const filtered = row(resource, { id: 'a', q: 'x' });- const index = failIndexReads(storage);-- // Memory is empty, so every variant is known only through the index.- act(() => slice.remove('a'));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(true);- expect(storage.rows.has(filtered)).toBe(true);-- index.failing = false;- act(() => slice.remove('a'));- await waitFor(() => {- expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);- expect(storage.rows.has(filtered)).toBe(false);- });- });-- it('never mistakes a plain key containing `?` for a query variant', async () => {- const storage = createMemoryStorage();- const { slice } = setup({ storage });- act(() => {- slice.replace({ id: 'foo' }, ['foo']);- slice.replace({ id: 'foo?bar' }, ['foo?bar']);- });- await waitFor(() => expect(storage.rows.size).toBe(2));-- act(() => slice.remove('foo'));-- await waitFor(() => expect(storage.rows.has('user-1:personal|foo')).toBe(false));- await new Promise((resolve) => setTimeout(resolve, 10));- expect(storage.rows.get('user-1:personal|foo?bar')?.data).toEqual(['foo?bar']);- });-- it('cleans variants listed by an index written in the existing flat format', async () => {- const storage = createMemoryStorage();- // Rows and index as an earlier release persisted them on a device.- for (const queryKey of ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'])- storage.rows.set(`user-1:personal|${queryKey}`, { data: [queryKey], updatedAt: 1 });- storage.indexRows.set('user-1:personal', {- data: ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'],- updatedAt: 1,- });- const { slice } = setupQueried({ storage });-- act(() => slice.remove('foo'));-- await waitFor(() => expect([...storage.rows.keys()]).toEqual(['user-1:personal|foo?bar?{}']));- await waitFor(() =>- expect(storage.indexRows.get('user-1:personal')?.data).toEqual(['foo?bar?{}']),- );- });-- it('calls a class-based storage with its receiver on every index pass', async () => {- /** Prototype methods that rely on `this`, like most storage classes. */- class ClassStorage implements ReplicaStorage<string[]> {- rows = new Map<string, ReplicaRow<string[]>>();- #id({ queryKey, scope }: { queryKey: string; scope: string }) {- return `${scope}|${queryKey}`;- }- async get(key: { queryKey: string; scope: string }) {- return this.rows.get(this.#id(key));- }- async getStrict(key: { queryKey: string; scope: string }) {- return this.rows.get(this.#id(key));- }- async remove(key: { queryKey: string; scope: string }) {- this.rows.delete(this.#id(key));- }- async set(key: { queryKey: string; scope: string }, row: ReplicaRow<string[]>) {- this.rows.set(this.#id(key), row);- }- }- const backing = new ClassStorage();- const storage = { ...createMemoryStorage(), storage: backing };- const dataRows = () =>- [...backing.rows.keys()].filter((key) => !key.endsWith(REPLICA_INDEX_KEY));- const first = setupQueried({ storage });- act(() => {- first.slice.replace({ id: 'a' }, ['a-all']);- first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);- first.slice.replace({ id: 'b' }, ['b-all']);- });- await waitFor(() => expect(dataRows()).toHaveLength(3));- const errors = vi.spyOn(console, 'error').mockImplementation(() => {});-- // A fresh engine only finds the rows through the index.- const { slice } = setupQueried({ storage });- slice.updateEntity('x', (item) => item);- act(() => slice.remove('a'));- await waitFor(() => expect(dataRows()).toEqual(['user-1:personal|b?{}']));- expect(await slice.clear()).toBe(true);- expect(dataRows()).toEqual([]);- expect(errors).not.toHaveBeenCalled();- errors.mockRestore();- });-- it('drops the request record of a failure even without an onError', async () => {- const requests: { fetch: () => Promise<unknown>; onError?: (error: unknown) => void }[] = [];- const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {- if (key?.[0] === 'replica:sync') requests.push({ fetch, onError: options.onError });- return { isValidating: false, mutate: vi.fn() };- });- const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });- const deletes = vi.spyOn(Map.prototype, 'delete');-- const { rerender } = renderHook((props: QueryParams) => slice.useSync(props), {- initialProps: { id: 'k1' } as QueryParams,- });- for (const id of ['k1', 'k2', 'k3']) {- rerender({ id });- const request = requests.at(-1)!;- await request.fetch();- act(() => request.onError!(new Error('forbidden')));- }-- const dropped = deletes.mock.calls.map(([id]) => String(id));- for (const id of ['k1', 'k2', 'k3'])- expect(- dropped.some((record) => record.includes('replica:sync') && record.includes(id)),- ).toBe(true);- deletes.mockRestore();- });-- it('clear wipes memory, every persisted row and the index of the active scope', async () => {- const first = await persistVariants();- // A later session loads only one entry; the rest is known only to the index.- const { slice, storage, store } = setupQueried({ storage: first.storage });- act(() => slice.replace({ id: 'b' }, ['b-all']));- storage.rows.set('user-2:personal|a', { data: ['other-user'], updatedAt: 1 });-- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(store.getState().lists).toEqual({});- expect(store.getState().listsReplica.entries).toEqual({});-- await act(async () => {- expect(await purge).toBe(true);- });- // Only the other identity's row survives; the index lists nothing.- expect([...storage.rows.keys()]).toEqual(['user-2:personal|a']);- await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- });-- it('clear refuses a hydrate that was already reading', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['wiped'], updatedAt: 1 });- const originalGet = storage.storage.get;- let release!: () => void;- const held = new Promise<void>((resolve) => (release = resolve));- storage.storage.get = async (key) => {- const value = await originalGet(key);- if (key.queryKey === 'a') await held;- return value;- };- const { slice, store } = setup({ storage });-- let hydration!: Promise<boolean>;- await act(async () => {- hydration = slice.hydrate({ id: 'a' });- });- act(() => {- void slice.clear();- });- await act(async () => {- release();- expect(await hydration).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('clear discards a head response that started before it, and applies one started after', () => {- const requests: { fetch: () => Promise<unknown>; onSuccess: (data: string[]) => void }[] = [];- const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {- if (key?.[0] === 'replica:sync') requests.push({ fetch, onSuccess: options.onSuccess });- return { isValidating: false, mutate: vi.fn() };- });- const { slice, store } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });- renderHook(() => slice.useSync({ id: 'a' }));- const request = requests.at(-1)!;-- // The request is issued, then the resource is wiped before it settles.- void request.fetch();- act(() => {- void slice.clear();- });- act(() => request.onSuccess(['before-clear']));- expect(store.getState().lists.a).toBeUndefined();-- // A request issued after the clear is ordinary.- void request.fetch();- act(() => request.onSuccess(['after-clear']));- expect(store.getState().lists.a).toEqual(['after-clear']);- });-- it('a clear whose purge could not run keeps refusing hydration', async () => {- const storage = createMemoryStorage();- storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });- const { slice, store } = setup({ storage });-- // Identity is not resolved yet, so the row deletes are refused.- scopeState.trusted = false;- let purge!: Promise<boolean>;- act(() => {- purge = slice.clear();- });- expect(await purge).toBe(false);- scopeState.trusted = true;-- await act(async () => {- expect(await slice.hydrate({ id: 'a' })).toBe(false);- });- expect(store.getState().lists.a).toBeUndefined();- });-- it('does not surface the error of a query the entry has moved past', () => {- const requests: { onError: (error: unknown) => void; params: { q?: string } }[] = [];- const useQuery = vi.fn((key: any, _fetch: unknown, options: any) => {- if (key?.[0] === 'replica:sync')- requests.push({ onError: options.onError, params: key.at(-1) });- return { isValidating: false, mutate: vi.fn() };- });- const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });- const onError = vi.fn();-- const { rerender } = renderHook((props: QueryParams) => slice.useSync(props, { onError }), {- initialProps: { id: 'a' } as QueryParams,- });- rerender({ id: 'a', q: 'b' });-- const base = requests.find((request) => request.params.q === undefined)!;- const search = requests.find((request) => request.params.q === 'b')!;-- // The superseded query fails late: the search on screen must not see it.- act(() => base.onError(new Error('stale')));- expect(onError).not.toHaveBeenCalled();-- const failure = new Error('search failed');- act(() => search.onError(failure));- expect(onError).toHaveBeenCalledWith(failure, {- isActive: true,- key: 'a',- scope: 'user-1:personal',- });- });- });-- describe('missing responses', () => {- it('applies a response the resource marks as missing as an explicit removal', () => {- // A nullable detail (e.g. the acceptance attached to a subject): the- // server answering "none" must clear a previously cached value, not let- // the merge fall back to it.- type NullableState = {- notes: Record<string, string[] | null>;- notesReplica: ReplicaState<string[] | null>;- };- const resource = defineReplica<{ id: string }, string[] | null>({- key: ({ id }) => id,- name: 'nullableNote',- scope,- version: 1,- });- const store = createStore<NullableState>()(() => ({- notes: {},- notesReplica: createReplicaState(),- }));- const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {- driver,- get: store.getState,- isMissing: (note) => note === null,- set: (partial) => store.setState(partial),- stateKey: 'notesReplica',- view: recordLens('notes'),- });-- act(() => slice.replace({ id: 'a' }, ['kept']));- expect(store.getState().notes.a).toEqual(['kept']);-- act(() => slice.replace({ id: 'a' }, null));- expect(store.getState().notes.a).toBeUndefined();- expect(store.getState().notesReplica.entries.a).toBeUndefined();- });-- it('treats a repeated missing response as a no-op', () => {- type NullableState = {- notes: Record<string, string[] | null>;- notesReplica: ReplicaState<string[] | null>;- };- const resource = defineReplica<{ id: string }, string[] | null>({- key: ({ id }) => id,- name: 'nullableNoteRepeat',- scope,- version: 1,- });- const store = createStore<NullableState>()(() => ({- notes: {},- notesReplica: createReplicaState(),- }));- const slice = createReplicaSlice<NullableState, { id: string }, string[] | null>(resource, {- driver,- get: store.getState,- isMissing: (note) => note === null,- set: (partial) => store.setState(partial),- stateKey: 'notesReplica',- view: recordLens('notes'),- });-- act(() => slice.replace({ id: 'a' }, ['kept']));- // The first "missing" drops the entry and clears stale storage…- expect(slice.replace({ id: 'a' }, null)).toBe(true);- // …a poll that still answers "missing" must not re-emit the removal.- expect(slice.replace({ id: 'a' }, null)).toBe(false);- expect(store.getState().notes.a).toBeUndefined();- });- });-- describe('late scoped responses', () => {- it('does not replay a response that lands after a scope switch', () => {- // A driver that settles each request through its own callback, so the- // test chooses the moment the response arrives.- let settle!: (data: string[]) => void;- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) settle = options.onSuccess;- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'lateScopeResponse',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const onSuccess = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));-- // The identity switches while the request is in flight; the response- // belongs to the previous scope and `replace` rejects it.- scopeState.current = 'user-2:personal';- act(() => settle(['late-user-1']));-- expect(store.getState().lists.a).toBeUndefined();- expect(onSuccess).not.toHaveBeenCalled();- });-- // An entity removed while its entry's request is in flight (deleted, pruned- // by an authoritative parent list) must not be recreated by that response.- // `slice.remove` drops the head-query marker, but an entity removal goes- // straight through the engine, so the request generation must catch it.- it('drops a response whose request started before the entity was removed', () => {- interface Item {- id: string;- title: string;- }- interface ItemState {- items: Record<string, Item>;- itemsReplica: ReplicaState<Item>;- }- let settle!: (data: Item) => void;- const useQuery = vi.fn((key: any, fetcher: () => unknown, options: any) => {- if (key !== null) {- settle = options.onSuccess;- void fetcher();- }- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, Item>({- fetcher: () => new Promise<Item>(() => {}),- key: ({ id }) => id,- name: 'removedEntityInFlight',- scope,- version: 1,- });- const store = createStore<ItemState>()(() => ({- items: {},- itemsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<ItemState, { id: string }, Item>(resource, {- driver: { revalidate: vi.fn(), useQuery },- entity: singleEntity<Item>((item) => item.id),- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'itemsReplica',- view: recordLens('items'),- });- act(() => slice.replace({ id: 'a' }, { id: 'a', title: 'first' }));-- const onSuccess = vi.fn();- renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }));- act(() => slice.removeEntity('a'));- expect(store.getState().items.a).toBeUndefined();-- act(() => settle({ id: 'a', title: 'stale' }));- expect(store.getState().items.a).toBeUndefined();- expect(onSuccess).not.toHaveBeenCalled();- });-- // a → b while a's request is in flight: a's late response still fills its- // own cache entry, but its success side effects act on the CURRENT view, so- // they must not re-adopt `a` while the hook shows `b`.- it('does not replay a response for a key the hook has moved past', () => {- let settle!: (data: string[]) => void;- const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {- if (key !== null) settle = options.onSuccess;- return { isValidating: false, mutate: vi.fn() };- });- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async ({ id }) => [id],- key: ({ id }) => id,- name: 'lateKeyResponse',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: { revalidate: vi.fn(), useQuery },- get: store.getState,- set: (partial) => store.setState(partial),- stateKey: 'listsReplica',- view: recordLens('lists'),- });-- const onSuccess = vi.fn();- const { rerender } = renderHook(({ id }) => slice.useSync({ id }, { onSuccess }), {- initialProps: { id: 'a' },- });- const settleA = settle;-- rerender({ id: 'b' });- const settleB = settle;- act(() => settleA(['late-a']));-- expect(store.getState().lists.a).toEqual(['late-a']);- expect(onSuccess).not.toHaveBeenCalled();-- act(() => settleB(['b']));- expect(onSuccess).toHaveBeenCalledTimes(1);- expect(onSuccess).toHaveBeenCalledWith(['b']);- });- });-- describe('updateMany', () => {- it('applies many keys as one commit and clones the record once', () => {- const resource = defineReplica<{ id: string }, string[]>({- fetcher: async () => ['server'],- key: ({ id }) => id,- name: 'batchedSeed',- scope,- version: 1,- });- const store = createStore<TestState>()(() => ({- lists: {},- listsReplica: createReplicaState(),- }));- const lens = recordLens<TestState, string[]>('lists');- const setMany = vi.spyOn(lens, 'setMany');- const set = vi.spyOn(lens, 'set');- let commits = 0;- const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {- driver: {- revalidate: vi.fn(),- useQuery: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),- },- get: store.getState,- set: (partial) => {- commits += 1;- store.setState(partial);- },- stateKey: 'listsReplica',- view: lens,- });-- act(() => {- slice.updateMany([- { apply: () => ['a'], key: 'a' },- { apply: () => ['b'], key: 'b' },- { apply: () => ['c'], key: 'c' },- ]);- });-- expect(store.getState().lists).toEqual({ a: ['a'], b: ['b'], c: ['c'] });- // One host commit for the whole batch, and one clone of the record.- expect(commits).toBe(1);- expect(setMany).toHaveBeenCalledTimes(1);- expect(set).not.toHaveBeenCalled();-- // An empty batch commits nothing.- expect(slice.updateMany([])).toBe(false);- expect(commits).toBe(1);- });- });-- describe('optimistic', () => {- it('commits and persists the confirmed value on success', async () => {- const { slice, store, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['x']);- });-- let resolveCall!: () => void;- let promise!: Promise<unknown>;- act(() => {- promise = slice.optimistic(- 'a',- (list) => [...list, 'y'],- () => new Promise<void>((resolve) => (resolveCall = resolve)),- );- });- expect(store.getState().lists.a).toEqual(['x', 'y']);-- await act(async () => {- resolveCall();- await promise;- });- expect(store.getState().lists.a).toEqual(['x', 'y']);- await waitFor(() => expect(storage.writes.at(-1)).toBe('x,y'));- });-- it('rolls back and rethrows on failure', async () => {- const { slice, store, storage } = setup();- act(() => {- slice.replace({ id: 'a' }, ['x']);- });- await waitFor(() => expect(storage.writes).toEqual(['x']));-- await act(async () => {- await expect(- slice.optimistic(- 'a',- (list) => [...list, 'y'],- async () => {- throw new Error('boom');- },- ),- ).rejects.toThrow('boom');- });-- expect(store.getState().lists.a).toEqual(['x']);- expect(storage.writes).toEqual(['x']);- });- });-- describe('write ordering', () => {- it('serializes persistence per key so the latest snapshot wins', async () => {- // The first write is slow; without serialization it would land last.- const storage = createMemoryStorage({ first: 30 });- const { slice } = setup({ storage });-- act(() => {- slice.replace({ id: 'a' }, ['first']);- slice.replace({ id: 'a' }, ['second']);- });-- await waitFor(() => expect(storage.writes).toEqual(['first', 'second']));- expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['second']);- });- });-});diff --git a/packages/replica/src/zustand/createReplicaSlice.useSync.test.ts b/packages/replica/src/zustand/createReplicaSlice.useSync.test.tsnew file mode 100644index 00000000000..b611e1c9902--- /dev/null+++ b/packages/replica/src/zustand/createReplicaSlice.useSync.test.ts@@ -0,0 +1,403 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createStore } from 'zustand/vanilla';++import { testDriver as driver } from '../../tests/testDriver';+import { defineReplica } from '../core/defineReplica';+import { createReplicaState } from '../core/reducer';+import { createReplicaSlice, recordLens } from './createReplicaSlice';+import type { TestState } from './testUtils';+import { createMemoryStorage, resetScopeState, scope, scopeState, setup, wrapper } from './testUtils';++beforeEach(resetScopeState);++describe('createReplicaSlice', () => {+ describe('useSync', () => {+ it('paints the persisted projection while the network request is in flight', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });+ let resolveFetch!: (value: string[]) => void;+ const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));+ const { slice, store } = setup({ fetcher, storage });++ const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));+ // Background loading never hides the hydrated data.+ expect(result.current.isHydrated).toBe(true);+ expect(result.current.isValidating).toBe(true);++ await act(async () => resolveFetch(['server']));++ await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));+ expect(store.getState().listsReplica.entries.a.source).toBe('server');+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['server']));+ });++ it('runs onSuccess after the response is folded in, and onError on a failed fetch', async () => {+ const { slice, store } = setup();+ const seen: unknown[] = [];+ renderHook(+ () =>+ slice.useSync(+ { id: 'a' },+ { onSuccess: (data) => seen.push([data, store.getState().lists.a]) },+ ),+ { wrapper },+ );+ // The callback already sees the store view the response produced.+ await waitFor(() => expect(seen).toEqual([[['server'], ['server']]]));++ const failure = new Error('offline');+ const onError = vi.fn();+ const failing = setup({+ fetcher: vi.fn(async () => {+ throw failure;+ }),+ });+ renderHook(() => failing.slice.useSync({ id: 'b' }, { onError }), { wrapper });+ // The callback also receives the key/scope the failing read was captured+ // under, so a terminal removal can be bound to the right scope.+ await waitFor(() =>+ expect(onError).toHaveBeenCalledWith(failure, {+ isActive: true,+ key: 'b',+ scope: 'user-1:personal',+ }),+ );+ expect(failing.store.getState().lists.b).toBeUndefined();+ });++ it('runs onHydrated with the hydrated value, and skips it when nothing was stored', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });+ let resolveFetch!: (value: string[]) => void;+ const fetcher = vi.fn(() => new Promise<string[]>((resolve) => (resolveFetch = resolve)));+ const { slice, store } = setup({ fetcher, storage });+ const seen: string[][] = [];+ renderHook(() => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }), {+ wrapper,+ });++ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached']));+ expect(seen).toEqual([['cached']]);++ await act(async () => resolveFetch(['server']));+ await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));+ // The network response stays `onSuccess`'s job; onHydrated does not fire for it.+ expect(seen).toEqual([['cached']]);++ // An empty slot has no persisted value, so nothing is replayed.+ const empty = setup();+ const missed = vi.fn();+ renderHook(() => empty.slice.useSync({ id: 'b' }, { onHydrated: missed }), { wrapper });+ await waitFor(() => expect(empty.store.getState().lists.b).toEqual(['server']));+ expect(missed).not.toHaveBeenCalled();+ });++ it('drops the prior persisted projection when `toPersisted` reports a confirmed absence', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });+ const resource = defineReplica<{ id: string }, string[]>({+ // The server confirms the id no longer exists.+ fetcher: vi.fn(async () => []),+ key: ({ id }) => id,+ name: 'absentList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ // An empty list is a confirmed absence: drop the stored row instead of+ // leaving the stale projection to be hydrated again.+ toPersisted: (data) => (data.length ? data : null),+ view: recordLens('lists'),+ });++ renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ // The confirmed absence replaces the hydrated value in the view…+ await waitFor(() => expect(store.getState().lists.a).toEqual([]));+ // …and the stale persisted projection is gone, so a reload cannot paint it.+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ });++ it('keeps the stored row when `toPersisted` returns undefined (skip)', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: vi.fn(async () => ['server']),+ key: ({ id }) => id,+ name: 'skippedList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ // `undefined` means "skip this write", not "remove".+ toPersisted: () => undefined,+ view: recordLens('lists'),+ });++ renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ await waitFor(() => expect(store.getState().lists.a).toEqual(['server']));+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']);+ });++ it('hands its schedule (polling, focus revalidation …) to the driver', () => {+ const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'scheduled',+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ renderHook(() =>+ slice.useSync({ id: 'a' }, { refreshInterval: 10_000, revalidateOnFocus: false }),+ );++ expect(useQuery).toHaveBeenCalledWith(+ expect.arrayContaining(['replica:sync', 'scheduled']),+ expect.any(Function),+ expect.objectContaining({ refreshInterval: 10_000, revalidateOnFocus: false }),+ );+ });++ it('discards a head response from a query the entry has moved past', () => {+ // A driver that settles every request through its own callback lets two+ // queries of the same key resolve out of order. One entry backs one view,+ // so the query the entry no longer asks for must not repaint it.+ const requests: {+ onSuccess: (data: string[]) => void;+ params: { q?: string };+ }[] = [];+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {+ if (key !== null) requests.push({ onSuccess: options.onSuccess, params: key.at(-1) });+ return { isValidating: false, mutate: vi.fn() };+ });+ const resource = defineReplica<{ q?: string }, string[]>({+ fetcher: async () => ['server'],+ key: () => 'all',+ name: 'orderedHead',+ query: ({ q }) => ({ q }),+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { q?: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ const { rerender } = renderHook((props: { q?: string }) => slice.useSync(props), {+ initialProps: {} as { q?: string },+ });+ rerender({ q: 'b' });++ const base = requests.find((request) => request.params.q === undefined)!;+ const search = requests.find((request) => request.params.q === 'b')!;++ act(() => search.onSuccess(['b-1']));+ expect(store.getState().lists.all).toEqual(['b-1']);++ // The superseded query settles late: it must not overwrite the search.+ act(() => base.onSuccess(['a-1']));+ expect(store.getState().lists.all).toEqual(['b-1']);+ });++ it('syncs under a custom key when the resource adopts one', () => {+ const useQuery = vi.fn(() => ({ isValidating: false, mutate: vi.fn() }));+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'customKeyed',+ scope,+ syncKey: ({ id }) => ['legacy:list', id],+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ renderHook(() => slice.useSync({ id: 'a' }));++ expect(useQuery).toHaveBeenCalledWith(+ ['legacy:list', 'a'],+ expect.any(Function),+ expect.any(Object),+ );+ });++ it('does not let a slow hydration overwrite a faster server response', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached'], updatedAt: 1 });+ const originalGet = storage.storage.get;+ storage.storage.get = async (key) => {+ await new Promise((resolve) => setTimeout(resolve, 30));+ return originalGet(key);+ };+ const { slice, store } = setup({ storage });++ const { result } = renderHook(() => slice.useSync({ id: 'a' }), { wrapper });++ await waitFor(() => expect(result.current.isHydrated).toBe(true));+ expect(store.getState().lists.a).toEqual(['server']);+ });++ it('does not let a slow hydration resurrect an entry removed while it was in flight', async () => {+ // A NOT_FOUND / FORBIDDEN response removes the entry (and its row) while+ // the persisted read is still in flight. That read already holds the old+ // row, so landing it afterwards would repaint the value just dropped.+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ const originalGet = storage.storage.get;+ let release!: () => void;+ const held = new Promise<void>((resolve) => (release = resolve));+ storage.storage.get = async (key) => {+ const row = await originalGet(key);+ if (key.queryKey === 'a') await held;+ return row;+ };+ const { slice, store } = setup({ storage });++ let hydration!: Promise<boolean>;+ await act(async () => {+ hydration = slice.hydrate({ id: 'a' });+ });++ // The network answers first and drops the entry.+ act(() => slice.remove('a'));+ expect(store.getState().lists.a).toBeUndefined();++ // The slow read settles: it must not paint the row the removal dropped.+ await act(async () => {+ release();+ await hydration;+ });++ expect(store.getState().lists.a).toBeUndefined();+ expect(store.getState().listsReplica.entries.a).toBeUndefined();+ });++ it('refuses to hydrate a key that was explicitly removed even if its row is still on disk', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ const { slice, store } = setup({ storage });++ act(() => slice.remove('a'));+ // The delete may not have flushed yet — the row must not come back anyway.+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });++ await act(async () => {+ expect(await slice.hydrate({ id: 'a' })).toBe(false);+ });+ expect(store.getState().lists.a).toBeUndefined();+ });++ it('lets a later server value supersede a removal so the key hydrates again', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ const { slice, store } = setup({ storage });++ act(() => slice.remove('a'));+ // Access restored: the server now answers with a value again.+ act(() => slice.replace({ id: 'a' }, ['regranted']));+ expect(store.getState().lists.a).toEqual(['regranted']);+ // Let the confirmed value reach the persisted row before reading it back.+ await waitFor(() =>+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['regranted']),+ );++ // Drop memory the way a scope switch does, then come back: with the+ // removal superseded, the persisted row may hydrate once more.+ scopeState.current = 'user-2:personal';+ act(() => slice.ensureScope('user-2:personal'));+ scopeState.current = 'user-1:personal';+ act(() => slice.ensureScope('user-1:personal'));++ await act(async () => {+ expect(await slice.hydrate({ id: 'a' })).toBe(true);+ });+ expect(store.getState().lists.a).toEqual(['regranted']);+ });++ it('reports a keyless (disabled) read as hydrated, so it never looks loading', () => {+ const { slice } = setup();++ const { result } = renderHook(() => slice.useSync(null), { wrapper });++ expect(result.current.isHydrated).toBe(true);+ expect(result.current.isValidating).toBe(false);+ });++ it('keeps the removal guard when a response captured under another scope is discarded', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ // The persisted-row delete is best-effort: simulate it still being pending.+ storage.storage.remove = async () => {};+ const { slice, store } = setup({ storage });++ // Scope A removes the entry (and arms its guard).+ act(() => slice.remove('a'));++ // A response captured under A resolves only after the user switched to B,+ // so `dispatch` drops it. It must not clear A's guard on the way out.+ scopeState.current = 'user-2:personal';+ act(() => slice.replace({ id: 'a' }, ['stale'], 'user-1:personal'));++ // Switching back to A must still refuse to hydrate the stale row.+ scopeState.current = 'user-1:personal';+ await act(async () => {+ expect(await slice.hydrate({ id: 'a' })).toBe(false);+ });+ expect(store.getState().lists.a).toBeUndefined();+ });+ });+});diff --git a/packages/replica/src/zustand/createReplicaSlice.useSyncSettle.test.ts b/packages/replica/src/zustand/createReplicaSlice.useSyncSettle.test.tsnew file mode 100644index 00000000000..e4743c169ef--- /dev/null+++ b/packages/replica/src/zustand/createReplicaSlice.useSyncSettle.test.ts@@ -0,0 +1,550 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createStore } from 'zustand/vanilla';++import { testDriver as driver } from '../../tests/testDriver';+import { defineReplica } from '../core/defineReplica';+import { REPLICA_INDEX_KEY } from '../core/engine';+import { createReplicaState } from '../core/reducer';+import type { ReplicaRow, ReplicaStorage } from '../core/types';+import { createReplicaSlice, recordLens } from './createReplicaSlice';+import type { TestState } from './testUtils';+import { createMemoryStorage, resetScopeState, scope, scopeState, setup, wrapper } from './testUtils';++beforeEach(resetScopeState);++describe('createReplicaSlice', () => {+ describe('useSync', () => {+ it('runs the caller success side effects when the response changes nothing', () => {+ // `replace` reports false both for a rejected response and for one with+ // nothing to write (an unchanged revalidation, or `undefined` for an id the+ // server no longer has). Callers rely on onSuccess in the latter cases —+ // e.g. removing a cached detail the server answered with nothing.+ const requests: { onSuccess: (data: string[] | undefined) => void }[] = [];+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {+ if (key !== null && options?.onSuccess) requests.push({ onSuccess: options.onSuccess });+ return { isValidating: false, mutate: vi.fn() };+ });+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'noopSuccessSideEffects',+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: { a: ['same'] },+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ scopeState.current = 'user-1:personal';+ const onSuccess = vi.fn();+ renderHook(() => slice.useSync({ id: 'a' }, { onSuccess }), { wrapper });+ const request = requests.find((entry) => entry)!;++ act(() => request.onSuccess(['same']));+ act(() => request.onSuccess(['same']));+ act(() => request.onSuccess(undefined));++ expect(onSuccess).toHaveBeenCalledTimes(3);+ expect(onSuccess).toHaveBeenLastCalledWith(undefined);+ });++ it("drops a settled request's success side effects once the store has left its scope", () => {+ // A response can settle after an identity/workspace switch. The engine+ // refuses the off-scope `replace`, but the caller's callbacks carry the+ // previous identity's side effects, so they must not run either — and a+ // switch to a scope reading the same key/query defeats both the+ // moved-past-query and since-clear guards.+ const requests: {+ onError: (error: unknown) => void;+ onSuccess: (data: string[]) => void;+ }[] = [];+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {+ if (key !== null) requests.push({ onError: options.onError, onSuccess: options.onSuccess });+ return { isValidating: false, mutate: vi.fn() };+ });+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'staleScopeCallbacks',+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ const onSuccess = vi.fn();+ const onError = vi.fn();+ renderHook(() => slice.useSync({ id: 'a' }, { onError, onSuccess }), { wrapper });++ const captured = requests.find((request) => request)!;++ // The identity/workspace switches while the request is still in flight.+ scopeState.current = 'user-2:personal';++ act(() => captured.onSuccess(['stale']));+ expect(onSuccess).not.toHaveBeenCalled();+ expect(store.getState().lists.a).toBeUndefined();++ // A failure is still handed over, bound to the scope it was captured+ // under and flagged as no longer active, so the caller can purge that+ // scope's row (see below) without repainting the current view.+ act(() => captured.onError(new Error('stale')));+ expect(onError).toHaveBeenCalledWith(expect.any(Error), {+ isActive: false,+ key: 'a',+ scope: 'user-1:personal',+ });+ });++ it('lets a late terminal error purge its captured scope through the sync callback', async () => {+ const requests: { onError: (error: unknown) => void }[] = [];+ const useQuery = vi.fn((key: any, _fetcher: unknown, options: any) => {+ // The sync request carries the callbacks; the hydration read does not.+ if (key !== null && options?.onError) requests.push({ onError: options.onError });+ return { isValidating: false, mutate: vi.fn() };+ });+ const memory = createMemoryStorage();+ memory.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'lateTerminalError',+ scope,+ storage: memory.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: { revalidate: vi.fn(), useQuery },+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });++ scopeState.current = 'user-1:personal';+ const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];+ renderHook(+ () =>+ slice.useSync(+ { id: 'a' },+ {+ onError: (_error, context) => {+ contexts.push(context);+ if (context.key) slice.remove(context.key, context.scope);+ },+ },+ ),+ { wrapper },+ );+ const request = requests.find((entry) => entry)!;++ // The identity switches and loads its own entry before the denial lands.+ scopeState.current = 'user-2:personal';+ act(() => slice.replace({ id: 'a' }, ['b-value']));++ act(() => request.onError(new Error('NOT_FOUND')));++ // The callback still runs, flagged as belonging to a scope left behind, so+ // the consumer can purge that scope without repainting the current one.+ expect(contexts[0]).toMatchObject({ isActive: false, key: 'a', scope: 'user-1:personal' });+ // The scope on screen keeps its entry; the denied scope's row is purged.+ expect(store.getState().lists.a).toEqual(['b-value']);+ await waitFor(() => expect(memory.rows.get('user-1:personal|a')).toBeUndefined());+ });++ // The guard lives in the engine, per scope — not in the bookkeeping slot a+ // scope reset wipes — so an A → B → A round trip cannot lift it.+ it('keeps the removal guard across a scope round trip', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ // The persisted-row delete is still pending: the stale row stays on disk.+ storage.storage.remove = async () => {};+ const { slice, store } = setup({ storage });++ act(() => slice.remove('a'));++ scopeState.current = 'user-2:personal';+ act(() => slice.ensureScope('user-2:personal'));+ expect(store.getState().listsReplica.scope).toBe('user-2:personal');+ scopeState.current = 'user-1:personal';+ act(() => slice.ensureScope('user-1:personal'));++ await act(async () => {+ expect(await slice.hydrate({ id: 'a' })).toBe(false);+ });+ expect(store.getState().lists.a).toBeUndefined();+ });++ it('purges the captured scope row for a removal that lands after a scope switch', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ const { slice, store } = setup({ storage });++ // The active scope has its own entry loaded.+ scopeState.current = 'user-2:personal';+ act(() => slice.replace({ id: 'a' }, ['b-value']));+ expect(store.getState().lists.a).toEqual(['b-value']);++ // A late NOT_FOUND from a request captured under the previous scope must+ // not delete the entry that is on screen now…+ act(() => slice.remove('a', 'user-1:personal'));+ expect(store.getState().lists.a).toEqual(['b-value']);++ // …but that scope's own persisted row still has to go, or switching back+ // to it would hydrate the value the server just denied.+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ });++ it('retries an off-scope purge once the captured scope may persist again', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['revoked'], updatedAt: 1 });+ const { slice } = setup({ storage });++ // The terminal answer lands while writes are still refused.+ scopeState.current = 'user-2:personal';+ scopeState.trusted = false;+ act(() => slice.remove('a', 'user-1:personal'));+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(storage.rows.get('user-1:personal|a')).toBeDefined();++ // Identity resolves: the next terminal answer must clear the row, not+ // report a no-op that never deletes it.+ scopeState.trusted = true;+ act(() => slice.remove('a', 'user-1:personal'));+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')).toBeUndefined());+ });++ it('binds the captured key and scope to the error callback', async () => {+ const fetcher = vi.fn(async () => {+ throw new Error('not found');+ });+ const { slice } = setup({ fetcher });+ const contexts: { isActive: boolean; key: string | undefined; scope: string }[] = [];++ scopeState.current = 'user-1:personal';+ renderHook(+ () => slice.useSync({ id: 'a' }, { onError: (_error, context) => contexts.push(context) }),+ { wrapper },+ );++ await waitFor(() => expect(contexts.length).toBeGreaterThan(0));+ expect(contexts[0]).toEqual({ isActive: true, key: 'a', scope: 'user-1:personal' });+ });++ it('evicts the persisted row when a response has nothing to persist', async () => {+ // Two bindings share one storage, so the second one reads what the first+ // one left behind — a reload of the same resource.+ const storage = createMemoryStorage();+ const bind = () => {+ const resource = defineReplica<{ id: string }, string[]>({+ key: ({ id }) => id,+ name: 'evictingList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ // `['gone']` is a page state that must never be persisted.+ toPersisted: (data) => (data[0] === 'gone' ? null : data),+ view: recordLens('lists'),+ });+ return { slice, store };+ };++ const first = bind();+ act(() => {+ first.slice.replace({ id: 'a' }, ['cached']);+ });+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));++ act(() => {+ first.slice.replace({ id: 'a' }, ['gone']);+ });+ // The value stays in memory…+ expect(first.store.getState().lists.a).toEqual(['gone']);+ // …while the row persisted for it earlier is removed.+ await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));++ // A reload hydrates nothing instead of resurrecting the evicted value.+ const reloaded = bind();+ await act(async () => {+ await reloaded.slice.hydrate({ id: 'a' });+ });+ expect(reloaded.store.getState().lists.a).toBeUndefined();+ });++ it('clears a reloaded key from the persisted index when the response has nothing to persist', async () => {+ const storage = createMemoryStorage();+ const indexKey = { queryKey: REPLICA_INDEX_KEY, scope: 'user-1:personal' };+ const bind = () => {+ const resource = defineReplica<{ id: string }, string[]>({+ key: ({ id }) => id,+ name: 'indexedList',+ scope,+ storage: storage.storage,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ toPersisted: (data) => (data[0] === 'gone' ? null : data),+ view: recordLens('lists'),+ });+ return { slice, store };+ };++ const first = bind();+ act(() => {+ first.slice.replace({ id: 'a' }, ['cached']);+ });+ await waitFor(() => expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['cached']));+ await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual(['a']));++ // A reload: a fresh engine whose in-memory index bookkeeping is empty, so+ // only the persisted index knows the key is there.+ const reloaded = bind();+ await act(async () => {+ await reloaded.slice.hydrate({ id: 'a' });+ });+ expect(reloaded.store.getState().lists.a).toEqual(['cached']);++ act(() => {+ reloaded.slice.replace({ id: 'a' }, ['gone']);+ });+ // The row goes…+ await waitFor(() => expect(storage.rows.has('user-1:personal|a')).toBe(false));+ // …and so does its index entry, so later entity scans do not chase a+ // missing row.+ await waitFor(async () => expect((await storage.storage.get(indexKey))?.data).toEqual([]));+ });++ // The removal deletes the entry, but a storage read that started before it+ // can still resolve afterwards; the replica must not let that stale read+ // resurrect the removed entry (the server already confirmed it gone).+ it('does not let a hydrate that resolves after a removal resurrect the entry', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });+ const realGet = storage.storage.get.bind(storage.storage);+ let releaseRead!: () => void;+ const readGate = new Promise<void>((resolve) => (releaseRead = resolve));+ let readStarted = false;+ vi.spyOn(storage.storage, 'get').mockImplementation(async (key) => {+ if (key.queryKey === 'a') {+ // A storage read is a snapshot: capture the row now, resolve later.+ const snapshot = await realGet(key);+ readStarted = true;+ await readGate;+ return snapshot;+ }+ return realGet(key);+ });++ // A network that never answers, so only the hydrate is at play.+ const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });++ let hydrated = false;+ const session = renderHook(+ () => slice.useSync({ id: 'a' }, { onHydrated: () => (hydrated = true) }),+ { wrapper },+ );+ await waitFor(() => expect(readStarted).toBe(true));++ // The key is removed (a server-confirmed absence) before the read lands.+ act(() => slice.remove('a'));++ releaseRead();+ await act(async () => {});++ expect(hydrated).toBe(false);+ expect(store.getState().lists.a).toBeUndefined();+ expect(store.getState().listsReplica.entries.a).toBeUndefined();+ session.unmount();+ });++ // a → b → a: a's hydration query already settled and is not re-run, so its+ // side effects must be replayed off the cached value when `a` is active again+ // — or they stay pointed at `b` until (or, offline, without) a response.+ it('replays onHydrated when a hydrated key becomes active again', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached-a'], updatedAt: 1 });+ storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });+ // Offline: the network never answers, so only hydration can run effects.+ const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });+ const seen: string[][] = [];++ const session = renderHook(+ ({ id }: { id: string }) =>+ slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),+ { initialProps: { id: 'a' }, wrapper },+ );+ await waitFor(() => expect(session.result.current.isHydrated).toBe(true));+ // The first activation runs it once, from the hydrate itself.+ expect(seen).toEqual([['cached-a']]);++ session.rerender({ id: 'b' });+ await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b']]));++ session.rerender({ id: 'a' });+ await waitFor(() => expect(seen).toEqual([['cached-a'], ['cached-b'], ['cached-a']]));+ expect(store.getState().lists.a).toEqual(['cached-a']);++ // A plain re-render of the same key does not replay again.+ session.rerender({ id: 'a' });+ await act(async () => {});+ expect(seen).toHaveLength(3);+ session.unmount();+ });++ // Scope A → B → A with the same key: B's activation cleared the view and+ // A's `once` hydration result is reused, so the slice must read A's+ // partition again — offline, nothing else would bring the row back.+ it('rehydrates an entry after returning to a prior scope', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|a', { data: ['cached-a1'], updatedAt: 1 });+ storage.rows.set('user-2:personal|a', { data: ['cached-a2'], updatedAt: 1 });+ const { slice, store } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });+ const seen: string[][] = [];++ const session = renderHook(+ () => slice.useSync({ id: 'a' }, { onHydrated: (data) => seen.push(data) }),+ { wrapper },+ );+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));++ scopeState.current = 'user-2:personal';+ session.rerender();+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a2']));++ scopeState.current = 'user-1:personal';+ session.rerender();+ await waitFor(() => expect(store.getState().lists.a).toEqual(['cached-a1']));+ // Its side effects follow the row back too.+ await waitFor(() => expect(seen.at(-1)).toEqual(['cached-a1']));+ session.unmount();+ });++ // A lookup that missed storage settles `true` as well; reactivating its key+ // must not replay `onHydrated` off a value that never came from storage+ // (a provisional seed written into the view).+ it('does not replay onHydrated for a reactivated key whose lookup missed storage', async () => {+ const storage = createMemoryStorage();+ storage.rows.set('user-1:personal|b', { data: ['cached-b'], updatedAt: 1 });+ const { slice } = setup({ fetcher: () => new Promise<string[]>(() => {}), storage });+ const seen: string[][] = [];++ const session = renderHook(+ ({ id }: { id: string }) =>+ slice.useSync({ id }, { onHydrated: (data) => seen.push(data) }),+ { initialProps: { id: 'a' }, wrapper },+ );+ await waitFor(() => expect(session.result.current.isHydrated).toBe(true));+ expect(seen).toEqual([]);++ session.rerender({ id: 'b' });+ await waitFor(() => expect(seen).toEqual([['cached-b']]));++ // A seed lands in `a`'s view while the hook shows `b`.+ act(() => {+ slice.update('a', () => ['seed-a'], { persist: false, source: 'seed' });+ });+ session.rerender({ id: 'a' });+ await act(async () => {});+ expect(seen).toEqual([['cached-b']]);+ session.unmount();+ });++ it('a version bump ignores rows written by the previous version', async () => {+ // One backing map shared by every version, keyed by the namespace the+ // factory receives — like IndexedDB rows of two app releases.+ const backing = new Map<string, ReplicaRow<string[]>>();+ const namespaced = (namespace: string): ReplicaStorage<string[]> => ({+ get: async ({ queryKey, scope }) => backing.get(`${namespace}|${scope}|${queryKey}`),+ remove: async ({ queryKey, scope }) => {+ backing.delete(`${namespace}|${scope}|${queryKey}`);+ },+ set: async ({ queryKey, scope }, row) => {+ backing.set(`${namespace}|${scope}|${queryKey}`, row);+ },+ });+ const bind = (version: number) => {+ const resource = defineReplica<{ id: string }, string[]>({+ key: ({ id }) => id,+ name: 'versionedList',+ scope,+ storage: namespaced,+ version,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });+ return { slice, store };+ };++ const v1 = bind(1);+ act(() => {+ v1.slice.replace({ id: 'a' }, ['v1-shape']);+ });+ const dataKeys = () => [...backing.keys()].filter((key) => !key.includes(REPLICA_INDEX_KEY));+ await waitFor(() => expect(dataKeys()).toHaveLength(1));++ const v1Reload = bind(1);+ await act(async () => {+ await v1Reload.slice.hydrate({ id: 'a' });+ });+ expect(v1Reload.store.getState().lists.a).toEqual(['v1-shape']);++ const v2 = bind(2);+ await act(async () => {+ await v2.slice.hydrate({ id: 'a' });+ });+ expect(v2.store.getState().lists.a).toBeUndefined();+ });+ });+});diff --git a/packages/replica/src/zustand/createReplicaSlice.writes.test.ts b/packages/replica/src/zustand/createReplicaSlice.writes.test.tsnew file mode 100644index 00000000000..1b4dbc015a1--- /dev/null+++ b/packages/replica/src/zustand/createReplicaSlice.writes.test.ts@@ -0,0 +1,133 @@+/**+ * @vitest-environment happy-dom+ */+import { act, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createStore } from 'zustand/vanilla';++import { defineReplica } from '../core/defineReplica';+import { createReplicaState } from '../core/reducer';+import { createReplicaSlice, recordLens } from './createReplicaSlice';+import type { TestState } from './testUtils';+import { createMemoryStorage, resetScopeState, scope, setup } from './testUtils';++beforeEach(resetScopeState);++describe('createReplicaSlice', () => {+ describe('updateMany', () => {+ it('applies many keys as one commit and clones the record once', () => {+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher: async () => ['server'],+ key: ({ id }) => id,+ name: 'batchedSeed',+ scope,+ version: 1,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const lens = recordLens<TestState, string[]>('lists');+ const setMany = vi.spyOn(lens, 'setMany');+ const set = vi.spyOn(lens, 'set');+ let commits = 0;+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver: {+ revalidate: vi.fn(),+ useQuery: vi.fn(() => ({ isValidating: false, mutate: vi.fn() })),+ },+ get: store.getState,+ set: (partial) => {+ commits += 1;+ store.setState(partial);+ },+ stateKey: 'listsReplica',+ view: lens,+ });++ act(() => {+ slice.updateMany([+ { apply: () => ['a'], key: 'a' },+ { apply: () => ['b'], key: 'b' },+ { apply: () => ['c'], key: 'c' },+ ]);+ });++ expect(store.getState().lists).toEqual({ a: ['a'], b: ['b'], c: ['c'] });+ // One host commit for the whole batch, and one clone of the record.+ expect(commits).toBe(1);+ expect(setMany).toHaveBeenCalledTimes(1);+ expect(set).not.toHaveBeenCalled();++ // An empty batch commits nothing.+ expect(slice.updateMany([])).toBe(false);+ expect(commits).toBe(1);+ });+ });++ describe('optimistic', () => {+ it('commits and persists the confirmed value on success', async () => {+ const { slice, store, storage } = setup();+ act(() => {+ slice.replace({ id: 'a' }, ['x']);+ });++ let resolveCall!: () => void;+ let promise!: Promise<unknown>;+ act(() => {+ promise = slice.optimistic(+ 'a',+ (list) => [...list, 'y'],+ () => new Promise<void>((resolve) => (resolveCall = resolve)),+ );+ });+ expect(store.getState().lists.a).toEqual(['x', 'y']);++ await act(async () => {+ resolveCall();+ await promise;+ });+ expect(store.getState().lists.a).toEqual(['x', 'y']);+ await waitFor(() => expect(storage.writes.at(-1)).toBe('x,y'));+ });++ it('rolls back and rethrows on failure', async () => {+ const { slice, store, storage } = setup();+ act(() => {+ slice.replace({ id: 'a' }, ['x']);+ });+ await waitFor(() => expect(storage.writes).toEqual(['x']));++ await act(async () => {+ await expect(+ slice.optimistic(+ 'a',+ (list) => [...list, 'y'],+ async () => {+ throw new Error('boom');+ },+ ),+ ).rejects.toThrow('boom');+ });++ expect(store.getState().lists.a).toEqual(['x']);+ expect(storage.writes).toEqual(['x']);+ });+ });++ describe('write ordering', () => {+ it('serializes persistence per key so the latest snapshot wins', async () => {+ // The first write is slow; without serialization it would land last.+ const storage = createMemoryStorage({ first: 30 });+ const { slice } = setup({ storage });++ act(() => {+ slice.replace({ id: 'a' }, ['first']);+ slice.replace({ id: 'a' }, ['second']);+ });++ await waitFor(() => expect(storage.writes).toEqual(['first', 'second']));+ expect(storage.rows.get('user-1:personal|a')?.data).toEqual(['second']);+ });+ });+});diff --git a/packages/replica/src/zustand/testUtils.ts b/packages/replica/src/zustand/testUtils.tsnew file mode 100644index 00000000000..04f136da815--- /dev/null+++ b/packages/replica/src/zustand/testUtils.ts@@ -0,0 +1,95 @@+import type { PropsWithChildren } from 'react';+import { createElement } from 'react';+import { SWRConfig } from 'swr';+import { vi } from 'vitest';+import { createStore } from 'zustand/vanilla';++import { testDriver as driver } from '../../tests/testDriver';+import { defineReplica } from '../core/defineReplica';+import { REPLICA_INDEX_KEY } from '../core/engine';+import { createReplicaState } from '../core/reducer';+import type { ReplicaRow, ReplicaScope, ReplicaState, ReplicaStorage } from '../core/types';+import { createReplicaSlice, recordLens } from './createReplicaSlice';++export interface TestState {+ lists: Record<string, string[]>;+ listsReplica: ReplicaState<string[]>;+}++export const scopeState = { canHydrate: true, current: 'user-1:personal', trusted: true };+export const scope: ReplicaScope = {+ canHydrate: () => scopeState.canHydrate,+ canPersist: () => scopeState.trusted,+ get: () => scopeState.current,+ // The real `use` is `useCacheScope`; a plain getter is enough for these tests.+ use: () => scopeState.current,+};++/** In-memory storage that records every write, keyed like the real ones. */+export const createMemoryStorage = (delays: Record<string, number> = {}) => {+ const rows = new Map<string, ReplicaRow<string[]>>();+ const writes: string[] = [];+ const indexRows = new Map<string, ReplicaRow<string[]>>();+ const read: ReplicaStorage<string[]>['get'] = async ({ queryKey, scope }) =>+ queryKey === REPLICA_INDEX_KEY+ ? (indexRows.get(scope) as ReplicaRow<string[]> | undefined)+ : rows.get(`${scope}|${queryKey}`);+ const storage: ReplicaStorage<string[]> = {+ get: read,+ getStrict: read,+ remove: async ({ queryKey, scope }) => {+ if (queryKey === REPLICA_INDEX_KEY) return void indexRows.delete(scope);+ rows.delete(`${scope}|${queryKey}`);+ },+ set: async ({ queryKey, scope }, projection) => {+ // The per-scope index of persisted rows is bookkeeping, not a data write.+ if (queryKey === REPLICA_INDEX_KEY) return void indexRows.set(scope, projection);+ const delay = delays[projection.data.join(',')] ?? 0;+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));+ writes.push(projection.data.join(','));+ rows.set(`${scope}|${queryKey}`, projection);+ },+ };+ return { indexRows, rows, storage, writes };+};++export const setup = ({+ fetcher = vi.fn(async (_params: { id: string }) => ['server']),+ storage = createMemoryStorage(),+ version = 1,+}: {+ fetcher?: (params: { id: string }) => Promise<string[]>;+ storage?: ReturnType<typeof createMemoryStorage>;+ version?: number;+} = {}) => {+ const resource = defineReplica<{ id: string }, string[]>({+ fetcher,+ key: ({ id }) => id,+ name: 'testList',+ scope,+ storage: storage.storage,+ version,+ });+ const store = createStore<TestState>()(() => ({+ lists: {},+ listsReplica: createReplicaState(),+ }));+ const slice = createReplicaSlice<TestState, { id: string }, string[]>(resource, {+ driver,+ get: store.getState,+ set: (partial) => store.setState(partial),+ stateKey: 'listsReplica',+ view: recordLens('lists'),+ });+ return { fetcher, resource, slice, storage, store };+};++export const wrapper = ({ children }: PropsWithChildren) =>+ createElement(SWRConfig, { value: { dedupingInterval: 0, provider: () => new Map() } }, children);++/** Reset the shared scope to a trusted, hydratable `user-1:personal`. */+export const resetScopeState = () => {+ scopeState.canHydrate = true;+ scopeState.current = 'user-1:personal';+ scopeState.trusted = true;+};diff --git a/src/libs/queryProjectionStorage/index.ts b/src/libs/queryProjectionStorage/index.tsindex 9526da1afe8..b423278e44e 100644--- a/src/libs/queryProjectionStorage/index.ts+++ b/src/libs/queryProjectionStorage/index.ts@@ -1,4 +1,3 @@export * from './indexedDB';export * from './localStorage';export type * from './types';-export * from './writeQueue';diff --git a/src/libs/queryProjectionStorage/indexedDB.ts b/src/libs/queryProjectionStorage/indexedDB.tsindex aff09c2d3fa..47f4d4e99c1 100644--- a/src/libs/queryProjectionStorage/indexedDB.ts+++ b/src/libs/queryProjectionStorage/indexedDB.ts@@ -1,6 +1,6 @@-import { localDatabase } from '@/libs/localDatabase';+import { KeyValueReplicaStorage } from '@lobechat/replica';-import type { QueryProjection, QueryProjectionKey, QueryProjectionStorage } from './types';+import { localDatabase } from '@/libs/localDatabase';interface IndexedDBQueryProjectionStorageOptions {namespace: string;@@ -8,47 +8,18 @@ interface IndexedDBQueryProjectionStorageOptions {const COLLECTION = 'query-projections';-export class IndexedDBQueryProjectionStorage<T> implements QueryProjectionStorage<T> {- readonly #namespace: string;-+/** Replica rows in the app's local database (IndexedDB on the web, SQLite in Electron). */+export class IndexedDBQueryProjectionStorage<T> extends KeyValueReplicaStorage<T> {constructor({ namespace }: IndexedDBQueryProjectionStorageOptions) {- this.#namespace = namespace;+ super({+ namespace,+ // Resolve `localDatabase` per call: the active adapter can be swapped at boot.+ store: {+ delete: (key) => localDatabase.delete(COLLECTION, key),+ get: (key) => localDatabase.get(COLLECTION, key),+ initialize: () => localDatabase.initialize(),+ set: (key, value) => localDatabase.set(COLLECTION, key, value),+ },+ });}-- #key = ({ queryKey, scope }: QueryProjectionKey) =>- `${this.#namespace}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;-- get = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {- try {- return await this.getStrict(key);- } catch {- return undefined;- }- };-- /** Like `get`, but rejects when the row could not be read (see `ReplicaStorage.getStrict`). */- getStrict = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {- await localDatabase.initialize();- return localDatabase.get<QueryProjection<T>>(COLLECTION, this.#key(key));- };-- /**- * Rejects when the delete did not land, unlike reads: a caller that removes a- * row the user deleted must be able to retry it.- */- remove = async (key: QueryProjectionKey): Promise<void> => {- await localDatabase.initialize();- await localDatabase.delete(COLLECTION, this.#key(key));- };-- /**- * Rejects when the write did not land (see `ReplicaStorage.set`): the replica- * engine only treats a row as holding a value after a confirmed write, so a- * dropped write is retried by the next persist instead of being skipped as- * redundant. Callers that persist best-effort catch it.- */- set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {- await localDatabase.initialize();- await localDatabase.set(COLLECTION, this.#key(key), projection);- };}diff --git a/src/libs/queryProjectionStorage/localStorage.ts b/src/libs/queryProjectionStorage/localStorage.tsindex aeaf8bbf341..369298b014d 100644--- a/src/libs/queryProjectionStorage/localStorage.ts+++ b/src/libs/queryProjectionStorage/localStorage.ts@@ -1,74 +1,22 @@+import { LocalStorageReplicaStorage } from '@lobechat/replica';import superjson from 'superjson';-import type {- QueryProjection,- QueryProjectionCodec,- QueryProjectionKey,- QueryProjectionStorage,-} from './types';+import type { QueryProjection, QueryProjectionCodec } from './types';interface LocalStorageQueryProjectionStorageOptions<T> {codec?: QueryProjectionCodec<T>;namespace: string;}-export class LocalStorageQueryProjectionStorage<T> implements QueryProjectionStorage<T> {- readonly #codec: QueryProjectionCodec<T>;- readonly #namespace: string;-- constructor(options: LocalStorageQueryProjectionStorageOptions<T>) {- this.#namespace = options.namespace;- this.#codec = options.codec ?? {- parse: superjson.parse<QueryProjection<T>>,- stringify: superjson.stringify,- };+/** Replica rows in `localStorage`, serialized with superjson so `Date` and friends survive. */+export class LocalStorageQueryProjectionStorage<T> extends LocalStorageReplicaStorage<T> {+ constructor({ codec, namespace }: LocalStorageQueryProjectionStorageOptions<T>) {+ super({+ codec: codec ?? {+ parse: superjson.parse<QueryProjection<T>>,+ stringify: superjson.stringify,+ },+ namespace,+ });}-- #key = ({ queryKey, scope }: QueryProjectionKey) =>- `${this.#namespace}:${encodeURIComponent(scope)}:${encodeURIComponent(queryKey)}`;-- get = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> =>- this.getSync(key);-- /** Restore a local projection inside pre-paint initialization without yielding a frame. */- getSync = (key: QueryProjectionKey): QueryProjection<T> | undefined => {- if (typeof window === 'undefined') return undefined;-- try {- const value = localStorage.getItem(this.#key(key));- return value ? this.#codec.parse(value) : undefined;- } catch {- return undefined;- }- };-- /** Like `get`, but rejects when the row could not be read or parsed (see `ReplicaStorage.getStrict`). */- getStrict = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {- if (typeof window === 'undefined') return undefined;-- const value = localStorage.getItem(this.#key(key));- return value ? this.#codec.parse(value) : undefined;- };-- /**- * Rejects when the delete did not land (e.g. storage access denied), unlike- * reads and writes: a caller removing a row the user deleted must be able to- * retry it.- */- remove = async (key: QueryProjectionKey): Promise<void> => {- if (typeof window === 'undefined') return;-- localStorage.removeItem(this.#key(key));- };-- /**- * Rejects when the write did not land (a quota error, see `ReplicaStorage.set`):- * the replica engine only treats a row as holding a value after a confirmed- * write. Callers that persist best-effort catch it.- */- set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {- if (typeof window === 'undefined') return;-- localStorage.setItem(this.#key(key), this.#codec.stringify(projection));- };}diff --git a/src/libs/queryProjectionStorage/types.ts b/src/libs/queryProjectionStorage/types.tsindex a0206cf8c0e..b13a7b2172d 100644--- a/src/libs/queryProjectionStorage/types.ts+++ b/src/libs/queryProjectionStorage/types.ts@@ -1,28 +1,10 @@-export interface QueryProjectionKey {- queryKey: string;- scope: string;-}+import type { ReplicaRow, ReplicaRowCodec, ReplicaRowKey, ReplicaStorage } from '@lobechat/replica';-export interface QueryProjection<T> {- data: T;- updatedAt: number;-}+export type QueryProjectionKey = ReplicaRowKey;-export interface QueryProjectionStorage<T> {- get: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;- /**- * Like `get`, but rejects when the row could not be read. Required: a replica- * refuses destructive passes (remove / clear / entity patch / eviction) on a- * storage without it.- */- getStrict: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;- /** Rejects when the delete did not land (reads and writes stay best-effort). */- remove: (key: QueryProjectionKey) => Promise<void>;- /** Rejects when the write did not land (see `ReplicaStorage.set`). */- set: (key: QueryProjectionKey, projection: QueryProjection<T>) => Promise<void>;-}+export type QueryProjection<T> = ReplicaRow<T>;-export interface QueryProjectionCodec<T> {- parse: (value: string) => QueryProjection<T>;- stringify: (projection: QueryProjection<T>) => string;-}+/** A replica storage whose strict read is required: replicas refuse destructive passes without it. */+export type QueryProjectionStorage<T> = Required<ReplicaStorage<T>>;++export type QueryProjectionCodec<T> = ReplicaRowCodec<T>;diff --git a/src/libs/queryProjectionStorage/writeQueue.test.ts b/src/libs/queryProjectionStorage/writeQueue.test.tsdeleted file mode 100644index f65fca3d41c..00000000000--- a/src/libs/queryProjectionStorage/writeQueue.test.ts+++ /dev/null@@ -1,30 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import type { QueryProjectionStorage } from './types';-import { QueryProjectionWriteQueue } from './writeQueue';--describe('QueryProjectionWriteQueue', () => {- it('serializes writes for the same projection key', async () => {- let releaseFirst!: () => void;- const first = new Promise<void>((resolve) => (releaseFirst = resolve));- const calls: number[] = [];- const storage: QueryProjectionStorage<number> = {- get: vi.fn(),- getStrict: vi.fn(),- remove: vi.fn(),- set: vi.fn(async (_key, projection) => {- calls.push(projection.data);- if (projection.data === 1) await first;- }),- };- const queue = new QueryProjectionWriteQueue(storage);- const key = { queryKey: 'list', scope: 'scope' };-- queue.set(key, { data: 1, updatedAt: 1 });- queue.set(key, { data: 2, updatedAt: 2 });- await vi.waitFor(() => expect(calls).toEqual([1]));-- releaseFirst();- await vi.waitFor(() => expect(calls).toEqual([1, 2]));- });-});diff --git a/src/libs/queryProjectionStorage/writeQueue.ts b/src/libs/queryProjectionStorage/writeQueue.tsdeleted file mode 100644index 8481e275aa2..00000000000--- a/src/libs/queryProjectionStorage/writeQueue.ts+++ /dev/null@@ -1,36 +0,0 @@-import type { QueryProjection, QueryProjectionKey, QueryProjectionStorage } from './types';--/**- * Serializes writes for one projection key. A later snapshot can never be overwritten by an- * earlier, slower IndexedDB write.- */-export class QueryProjectionWriteQueue<T> {- readonly #pending = new Map<string, Promise<void>>();- readonly #storage: QueryProjectionStorage<T>;-- constructor(storage: QueryProjectionStorage<T>) {- this.#storage = storage;- }-- #id = ({ queryKey, scope }: QueryProjectionKey) => `${scope}:${queryKey}`;-- remove = (key: QueryProjectionKey): void => {- this.#enqueue(key, () => this.#storage.remove(key));- };-- set = (key: QueryProjectionKey, value: QueryProjection<T>): void => {- this.#enqueue(key, () => this.#storage.set(key, value));- };-- #enqueue = (key: QueryProjectionKey, operation: () => Promise<void>): void => {- const id = this.#id(key);- const previous = this.#pending.get(id) ?? Promise.resolve();- const current = previous.catch(() => undefined).then(operation);- this.#pending.set(id, current);- void current- .catch(() => undefined)- .finally(() => {- if (this.#pending.get(id) === current) this.#pending.delete(id);- });- };-}diff --git a/src/libs/replica/index.ts b/src/libs/replica/index.tsindex 5c913a24531..d15f4654461 100644--- a/src/libs/replica/index.ts+++ b/src/libs/replica/index.ts@@ -4,7 +4,6 @@ import {defineReplica as defineCoreReplica,type DefineReplicaOptions,isReplicaSyncKey,- REPLICA_INDEX_KEY,type ReplicaPagedData,type ReplicaResource,type ReplicaScope,@@ -153,30 +152,6 @@ export const revalidateReplica = (isReplicaSyncKey(queryKey, resource.name, { key, scope: resource.scope.get() }),);-/**- * The entry storage keys this resource has a persisted row for in the active- * scope, oldest first.- *- * Storage has no key listing of its own; the engine keeps one index row per- * scope (`REPLICA_INDEX_KEY`) as it persists and drops entries, and this reads- * it. That is how code outside the owning store reaches rows an *earlier- * session* wrote — bounding how many survive a reload, or invalidating a row- * whose entry is not loaded in memory.- *- * The keys are storage keys (`key`, plus `?query` when the resource sets one),- * so a caller only matches them against entry keys when the resource leaves- * `query` unset.- */-export const readReplicaStoredKeys = async (- resource: Pick<ReplicaResource<any, any, any>, 'scope' | 'storage'>,-): Promise<string[]> => {- const row = await resource.storage?.get({- queryKey: REPLICA_INDEX_KEY,- scope: resource.scope.get(),- });- return (row?.data as unknown as string[] | undefined) ?? [];-};-/** `createReplicaSlice` bound to the app's SWR driver. */export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(resource: ReplicaResource<TParams, TData, TFetched>,diff --git a/src/libs/replica/prePaint.ts b/src/libs/replica/prePaint.tsindex 05b91f96471..03e9fc0ddb3 100644--- a/src/libs/replica/prePaint.ts+++ b/src/libs/replica/prePaint.ts@@ -1,3 +1,5 @@+export { settleWithin } from '@lobechat/replica';+/*** Upper bound for a route loader's pre-paint hydrate.*@@ -8,14 +10,3 @@* stall, so a route transition never waits longer than this for it.*/export const PRE_PAINT_HYDRATE_TIMEOUT = 50;--/** Resolve once `promise` settles or `ms` elapses — never rejects, never hangs. */-export const settleWithin = (promise: Promise<unknown>, ms: number): Promise<void> =>- new Promise((resolve) => {- const finish = () => {- clearTimeout(timer);- resolve();- };- const timer = setTimeout(finish, ms);- void Promise.resolve(promise).then(finish, finish);- });