tsdf 16.0.3 → 17.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,180 @@
1
+ # Optimistic List Updates
2
+
3
+ Optimistic list updates automatically keep list queries in sync when item state changes. When you update an item, the configured rules determine whether items should be added to, removed from, or re-sorted within queries — all without waiting for a server response.
4
+
5
+ **Store**: [List Query Store](./list-query-store.md) only.
6
+
7
+ ## How It Works
8
+
9
+ When you call `updateItemState` or `addItemToState`, TSDF applies optimistic list update rules to the affected queries. These rules can:
10
+
11
+ 1. **Filter items in/out of queries** based on item data
12
+ 2. **Re-sort queries** based on updated item values
13
+ 3. **Trigger background revalidation** of affected queries
14
+
15
+ ## Configuration
16
+
17
+ Define rules when creating the store:
18
+
19
+ ```ts
20
+ const taskStore = createListQueryStore<Task, TaskFilter, string>({
21
+ // ...other options
22
+
23
+ optimisticListUpdates: [
24
+ {
25
+ // Which queries this rule applies to
26
+ queries: (query) => query.projectId != null,
27
+
28
+ // Decide if an item should be in the query
29
+ filterItem: (item) => item.status === 'active',
30
+
31
+ // Where to add new items
32
+ appendNewTo: 'start',
33
+
34
+ // Trigger background revalidation when items are moved
35
+ invalidateQueries: true,
36
+ },
37
+ {
38
+ // Sort a specific query by priority
39
+ queries: { projectId: 'proj-1', status: 'active' },
40
+ sort: { sortBy: (item) => item.priority, order: 'desc' },
41
+ },
42
+ ],
43
+ });
44
+ ```
45
+
46
+ ## Rule Options
47
+
48
+ ### queries
49
+
50
+ Specifies which queries this rule applies to:
51
+
52
+ ```ts
53
+ // Single query
54
+ queries: {
55
+ projectId: 'proj-1';
56
+ }
57
+
58
+ // Multiple queries
59
+ queries: [{ projectId: 'proj-1' }, { projectId: 'proj-2' }];
60
+
61
+ // Filter function
62
+ queries: (queryPayload) => queryPayload.status === 'active';
63
+ ```
64
+
65
+ ### filterItem
66
+
67
+ Decides whether an item should be included in matching queries:
68
+
69
+ ```ts
70
+ filterItem: (item) => {
71
+ // true → item should be in the query (add if missing)
72
+ // false → item should NOT be in the query (remove if present)
73
+ // null → skip this rule for this item (no change)
74
+ return item.status === 'active';
75
+ };
76
+ ```
77
+
78
+ - When `filterItem` returns `true` and the item is not in the query, it's added at the position specified by `appendNewTo`
79
+ - When `filterItem` returns `false` and the item is in the query, it's removed
80
+ - When `filterItem` returns `null`, the rule is skipped for that item
81
+
82
+ ### appendNewTo
83
+
84
+ Where to insert items when `filterItem` adds them to a query:
85
+
86
+ ```ts
87
+ appendNewTo: 'start'; // prepend to the beginning
88
+ appendNewTo: 'end'; // append to the end (default)
89
+ ```
90
+
91
+ ### sort
92
+
93
+ Re-sorts the query's items after an update:
94
+
95
+ ```ts
96
+ sort: {
97
+ sortBy: (item, itemPayload) => item.priority,
98
+ order: 'desc', // 'asc' | 'desc'
99
+ }
100
+ ```
101
+
102
+ For multi-key sorting:
103
+
104
+ ```ts
105
+ sort: {
106
+ sortBy: (item) => [item.category, item.priority],
107
+ order: ['asc', 'desc'],
108
+ }
109
+ ```
110
+
111
+ Sorting is applied only to queries that contain the updated item.
112
+
113
+ ### invalidateQueries
114
+
115
+ When `true`, queries affected by the optimistic update are invalidated in the background. This ensures the server's actual ordering/filtering is fetched eventually.
116
+
117
+ ```ts
118
+ invalidateQueries: true;
119
+ ```
120
+
121
+ ## When Rules Are Applied
122
+
123
+ Optimistic list updates are triggered by:
124
+
125
+ 1. **`updateItemState`** — After updating item data, all rules are evaluated for the updated items
126
+ 2. **`addItemToState`** — After adding a new item, rules determine which queries should include it
127
+
128
+ They are **not** triggered by:
129
+
130
+ - `deleteItemState` (items are simply removed from all queries)
131
+ - Direct store mutations
132
+ - Fetch completions
133
+
134
+ ## Example: Task Board
135
+
136
+ ```ts
137
+ const storeManager = createStoreManager({
138
+ getSessionKey: () => currentTenantId ?? false,
139
+ errorNormalizer: normalizeError,
140
+ lowPriorityThrottleMs: 5,
141
+ baseCoalescingWindowMs: 10,
142
+ blockWindowClose: null,
143
+ });
144
+
145
+ const taskStore = createListQueryStore<Task, { status: string }, string>({
146
+ id: 'tasks',
147
+ storeManager,
148
+ fetchListFn: (filter, size, { signal }) => api.getTasks(filter, size, signal),
149
+ fetchItemFn: (id, { signal }) => api.getTask(id, signal),
150
+
151
+ optimisticListUpdates: [
152
+ {
153
+ // Move tasks between status columns
154
+ queries: (q) => true,
155
+ filterItem: (item) => item.status === 'todo',
156
+ // Only applies to queries where status matches
157
+ },
158
+ {
159
+ queries: { status: 'todo' },
160
+ filterItem: (item) => item.status === 'todo',
161
+ appendNewTo: 'start',
162
+ invalidateQueries: true,
163
+ },
164
+ {
165
+ queries: { status: 'done' },
166
+ filterItem: (item) => item.status === 'done',
167
+ appendNewTo: 'end',
168
+ invalidateQueries: true,
169
+ },
170
+ ],
171
+ });
172
+
173
+ // When a task is moved to "done", it's automatically:
174
+ // 1. Removed from the "todo" query
175
+ // 2. Added to the "done" query
176
+ // 3. Both queries are revalidated in the background
177
+ taskStore.updateItemState('task-1', (draft) => {
178
+ draft.status = 'done';
179
+ });
180
+ ```
@@ -0,0 +1,168 @@
1
+ # Partial Resources
2
+
3
+ Partial resources allow you to fetch only specific fields of an item, reducing payload size and improving performance. Different hooks can request different fields, and TSDF tracks which fields have been loaded per item.
4
+
5
+ **Store**: [List Query Store](./list-query-store.md) only.
6
+
7
+ ## Enabling Partial Resources
8
+
9
+ Enable by setting the `TPartialResources` type parameter to `true` and providing a `partialResources` config:
10
+
11
+ ```ts
12
+ type User = {
13
+ id: string;
14
+ name: string;
15
+ email: string;
16
+ avatar: string;
17
+ bio: string;
18
+ };
19
+
20
+ const storeManager = createStoreManager({
21
+ getSessionKey: () => currentTenantId ?? false,
22
+ errorNormalizer: normalizeError,
23
+ });
24
+
25
+ const userStore = createListQueryStore<User, UserFilter, string, true>({
26
+ // ^^^^ enables partial resources
27
+ storeManager,
28
+
29
+ fetchListFn: (filter, size, { signal, fields }) => {
30
+ // `fields` is string[] | undefined
31
+ // undefined means fetch all fields
32
+ return api.getUsers(filter, size, { signal, fields });
33
+ },
34
+
35
+ fetchItemFn: (userId, { signal, fields }) => {
36
+ return api.getUser(userId, { signal, fields });
37
+ },
38
+
39
+ partialResources: {
40
+ // Merge newly fetched fields with previously loaded ones
41
+ mergeItems: (prev, fetched) => ({ ...(prev ?? {}), ...fetched }),
42
+
43
+ // Select only the requested fields from a full item
44
+ selectFields: (fields, item) => {
45
+ const result: Partial<User> = {};
46
+ for (const field of fields) {
47
+ result[field] = item[field];
48
+ }
49
+ return result as User;
50
+ },
51
+ },
52
+
53
+ // ...other options
54
+ });
55
+ ```
56
+
57
+ ## How It Works
58
+
59
+ 1. Each hook specifies which `fields` it needs
60
+ 2. TSDF tracks `itemLoadedFields` — the set of fields already loaded for each item
61
+ 3. When a hook requests fields that haven't been loaded yet, a fetch is triggered requesting only the missing fields
62
+ 4. The `mergeItems` function combines the newly fetched data with previously loaded data
63
+ 5. The `selectFields` function extracts the requested fields for the hook's return value
64
+
65
+ ## Using Fields in Hooks
66
+
67
+ When partial resources is enabled, the `fields` option becomes **required** in hooks:
68
+
69
+ ```tsx
70
+ // Fetch only name and email
71
+ function UserCard({ userId }: { userId: string }) {
72
+ const { data } = userStore.useItem(userId, { fields: ['name', 'email'] });
73
+
74
+ return (
75
+ <div>
76
+ {data?.name} ({data?.email})
77
+ </div>
78
+ );
79
+ }
80
+
81
+ // Fetch all fields
82
+ function UserProfile({ userId }: { userId: string }) {
83
+ const { data } = userStore.useItem(userId, {
84
+ fields: '*', // '*' means all fields
85
+ });
86
+
87
+ return <div>{data?.bio}</div>;
88
+ }
89
+ ```
90
+
91
+ For list queries:
92
+
93
+ ```tsx
94
+ function UserList() {
95
+ const { items } = userStore.useListQuery(
96
+ { active: true },
97
+ { fields: ['name', 'avatar'] },
98
+ );
99
+
100
+ return items.map((user) => (
101
+ <UserRow
102
+ key={user.id}
103
+ name={user.name}
104
+ avatar={user.avatar}
105
+ />
106
+ ));
107
+ }
108
+ ```
109
+
110
+ ## Per-Field Invalidation
111
+
112
+ You can invalidate specific fields without refetching everything:
113
+
114
+ ```ts
115
+ userStore.invalidateQueryAndItems({
116
+ queryPayload: false,
117
+ itemPayload: 'user-1',
118
+ fields: ['name', 'email'], // only these fields are refetched
119
+ });
120
+ ```
121
+
122
+ This removes the specified fields from `itemLoadedFields`, causing hooks that request those fields to trigger a refetch — but only for those fields.
123
+
124
+ ## Loading Behavior
125
+
126
+ When a hook requests fields that are partially loaded:
127
+
128
+ - During the field fetch, the hook returns `null` data to prevent displaying stale partial data
129
+ - Once the missing fields are loaded and merged, the complete data is returned
130
+
131
+ If you enable `showPartialAsRefetching`, the hook exposes `loadingFields` with the requested fields that are still pending. When cached partial data already exists, TSDF keeps it visible during the follow-up fetch.
132
+
133
+ ## Fields in Scheduling and Fetching
134
+
135
+ Fields propagate through the scheduling and fetching APIs:
136
+
137
+ ```ts
138
+ // Schedule a fetch for specific fields
139
+ store.scheduleItemFetch('highPriority', 'user-1', {
140
+ fields: ['name', 'email'],
141
+ });
142
+
143
+ // Await a fetch for specific fields
144
+ const result = await store.awaitItemFetch('user-1', { fields: ['name'] });
145
+
146
+ // Schedule a list query fetch
147
+ store.scheduleListQueryFetch('highPriority', filter, undefined, {
148
+ fields: ['name', 'avatar'],
149
+ });
150
+ ```
151
+
152
+ ## partialResources Config
153
+
154
+ ### mergeItems
155
+
156
+ ```ts
157
+ mergeItems: (prev: ItemState | undefined, fetched: ItemState) => ItemState;
158
+ ```
159
+
160
+ Called when new fields arrive. `prev` is `undefined` if the item has never been fetched before. Should return the merged item with all known fields.
161
+
162
+ ### selectFields
163
+
164
+ ```ts
165
+ selectFields: (fields: string[], item: ItemState) => ItemState;
166
+ ```
167
+
168
+ Called when a hook requests specific fields. Should return an item containing only the requested fields.
@@ -0,0 +1,282 @@
1
+ # Persistent Storage
2
+
3
+ TSDF can persist cached data across page reloads and browser sessions through the optional `persistentStorage` option on each store type.
4
+
5
+ See also: [Document Store](./document-store.md) | [Collection Store](./collection-store.md) | [List Query Store](./list-query-store.md) | [Offline](./offline.md)
6
+
7
+ ## What it does
8
+
9
+ - Loads cached entries before network fetches when available.
10
+ - Persists successful fetch results back to local storage.
11
+ - Invalidates and drops cache entries when schema or version checks fail.
12
+ - Uses session scoped keys, so data is isolated per tenant/account.
13
+
14
+ ## Public API
15
+
16
+ Exported from `tsdf`:
17
+
18
+ | Export | Description |
19
+ | ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- |
20
+ | `PersistentStorageSchema` | Schema type supported by cache validation |
21
+ | `PersistentStorageDataSchema` / `ConvertedPersistentStorageDataSchema` | Direct or converted persisted data schema config |
22
+ | `StorageAdapter` | `'local-sync'` or a managed async storage adapter |
23
+ | `DocumentPersistentStorageConfig` / `CollectionPersistentStorageConfig` / `ListQueryPersistentStorageConfig` | Store-level persistence config types |
24
+ | `createStoreManager(options)` | Creates the shared store manager used by all stores |
25
+ | `PersistentStoragePreloadResult<Payload>` | Return shape for preload methods |
26
+ | `clearSessionStorage(sessionKey, adapter)` | Clears all TSDF entries for one session/adapter |
27
+ | `clearAllSessionStorage(sessionKey)` | Clears all TSDF entries for one session across built-in adapters |
28
+ | `localPersistentStorage` | Built-in localStorage helper used by the `'local-sync'` adapter |
29
+ | `opfsPersistentStorage` / `indexedDbPersistentStorage` | Built-in async storage adapters |
30
+ | `createIndexedDbPersistentStorage(options?)` | Creates an IndexedDB adapter, optionally with a database name |
31
+ | `createAsyncStorageAdapter(driver)` | Wraps a custom async storage driver |
32
+
33
+ ## Configuration
34
+
35
+ Each store accepts `persistentStorage` in options:
36
+
37
+ | Store | Config Type |
38
+ | ---------------- | ------------------------------------------------------------------------ |
39
+ | Document Store | `DocumentPersistentStorageConfig<State>` |
40
+ | Collection Store | `CollectionPersistentStorageConfig<ItemState, ItemPayload>` |
41
+ | List Query Store | `ListQueryPersistentStorageConfig<ItemState, QueryPayload, ItemPayload>` |
42
+
43
+ Common options (applies to all store configs):
44
+
45
+ | Option | Required | Description |
46
+ | --------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- |
47
+ | `schema` | Yes | Schema used to validate restored data. |
48
+ | `adapter` | Yes | `'local-sync'`, `opfsPersistentStorage`, `indexedDbPersistentStorage`, or a custom async adapter. |
49
+ | `version` | No | Cache version; bump to invalidate old entries. |
50
+ | `onPersistentStorageError(error)` | No | Store-specific callback for write/read failures (quota, decode, etc.). Overrides the manager fallback; use `null` to disable it. |
51
+
52
+ Store-specific options:
53
+
54
+ | Store | Additional options |
55
+ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
56
+ | Collection Store | `payloadSchema`, `maxBytes`, `pinnedItems`, `ignoreItems` |
57
+ | List Query Store | `itemPayloadSchema`, `queryPayloadSchema`, `maxItemBytes`, `maxQueryBytes`, `maxQuerySize`, `pinnedItems`, `pinnedQueries`, `ignoreItems` |
58
+
59
+ > `persistentStorage` automatically reuses the store's existing `id` for its storage namespace and the store manager's `getSessionKey` for session scoping. When `getSessionKey` returns `false`, no persistence operations run.
60
+
61
+ ## Converted Data Schemas
62
+
63
+ Use `ConvertedPersistentStorageDataSchema<TStore, TStorage>` when the in-memory store shape should differ from the data saved in persistent storage. This is useful for compact cache formats, migration-friendly storage shapes, or persisted data that should omit derived fields.
64
+
65
+ ```ts
66
+ import { rc_number, rc_object, rc_string } from 'runcheck';
67
+ import type { ConvertedPersistentStorageDataSchema } from 'tsdf';
68
+
69
+ type User = { profile: { name: string; score: number } };
70
+
71
+ type StoredUser = { n: string; s: number };
72
+
73
+ const userPersistenceSchema: ConvertedPersistentStorageDataSchema<
74
+ User,
75
+ StoredUser
76
+ > = {
77
+ storeSchema: rc_object({
78
+ profile: rc_object({ name: rc_string(), score: rc_number() }),
79
+ }),
80
+ storageSchema: rc_object({ n: rc_string(), s: rc_number() }),
81
+ convertToStorage: (user) => ({ n: user.profile.name, s: user.profile.score }),
82
+ convertFromStorage: (stored) => ({
83
+ profile: { name: stored.n, score: stored.s },
84
+ }),
85
+ };
86
+
87
+ const userStore = createDocumentStore<User>({
88
+ id: 'document-user',
89
+ storeManager,
90
+ fetchFn: (signal) => api.getUser(signal),
91
+ lowPriorityThrottleMs: 2000,
92
+ baseCoalescingWindowMs: 100,
93
+ blockWindowClose: null,
94
+ persistentStorage: { adapter: 'local-sync', schema: userPersistenceSchema },
95
+ });
96
+ ```
97
+
98
+ Validation runs on both sides of the conversion:
99
+
100
+ - Loaded cache data must pass `storageSchema`.
101
+ - `convertFromStorage(...)` maps it to the store shape.
102
+ - The converted result must pass `storeSchema`.
103
+ - Successful fetch data passes through `convertToStorage(...)` before being saved.
104
+
105
+ If `convertFromStorage(...)`, `convertToStorage(...)`, or either schema fails, TSDF reports the error through `onPersistentStorageError` when available and removes or skips the invalid cache entry.
106
+
107
+ If `persistentStorage.offline` is configured, pass one shared offline session config to `createStoreManager(...)` and keep store-local offline behavior in `persistentStorage.offline.operations`. `createStoreManager(...)` owns that session internally and expects config, not an existing `OfflineSession` object.
108
+
109
+ Each offline operation now requires a `kind`:
110
+
111
+ - `create` for temp-entity or create-style mutations
112
+ - `update` for in-place edits
113
+ - `delete` for destructive mutations
114
+
115
+ TSDF reduces those operation kinds into a derived `GlobalOfflineEntity.kind`
116
+ value (`create`, `createAndUpdate`, `update`, or `delete`) so queue-aware UI
117
+ can read one stable lifecycle field instead of inferring it from store
118
+ snapshots.
119
+
120
+ Session-level `mutationQueueing` can allow or disallow durable offline mutation queueing separately for `network` and `outage` causes. This only affects mutations using the `offline` option and does not change offline reads.
121
+
122
+ ## Adapter behavior
123
+
124
+ TSDF does not choose a persistence adapter automatically. Pass one of the built-in adapters or a custom async adapter in every `persistentStorage` config.
125
+
126
+ ### `local-sync`
127
+
128
+ - Uses managed `localStorage` entries.
129
+ - Can hydrate synchronously during initial state creation for `DocumentStore`.
130
+ - `CollectionStore` and `ListQueryStore` use lazy hydration for unknown entries from initial keys scan.
131
+ - Writes are debounced and may be dropped if serialization or quota errors occur.
132
+
133
+ Use it with:
134
+
135
+ ```ts
136
+ persistentStorage: {
137
+ adapter: 'local-sync',
138
+ schema: settingsSchema,
139
+ }
140
+ ```
141
+
142
+ ### `opfsPersistentStorage`
143
+
144
+ - Uses `FileSystemAccess`-backed persistent storage.
145
+ - Hydration is asynchronous, and can be triggered explicitly with preload APIs.
146
+
147
+ ### `indexedDbPersistentStorage`
148
+
149
+ - Alternative built-in async adapter for browsers where IndexedDB is preferred.
150
+ - Stores one logical row per entry and uses native indexes for recency ordering, group lookups, and protected-key scans.
151
+ - Hydration is asynchronous, and can be triggered explicitly with preload APIs.
152
+
153
+ Use `createIndexedDbPersistentStorage({ databaseName })` when an app needs an isolated IndexedDB database.
154
+
155
+ ### Custom async adapters
156
+
157
+ Use `createAsyncStorageAdapter(driver)` only when the built-in OPFS and IndexedDB adapters are not a fit. It wraps an `AsyncStorageDriver`, which is the low-level async backend contract used by TSDF persistence internals.
158
+
159
+ A driver is responsible for storing raw records by logical namespace:
160
+
161
+ ```ts
162
+ import { createAsyncStorageAdapter } from 'tsdf';
163
+ import type { AsyncStorageDriver } from 'tsdf';
164
+
165
+ const driver: AsyncStorageDriver = {
166
+ get: (scope, key) => customStore.get(scope, key),
167
+ set: (scope, key, value) => customStore.set(scope, key, value),
168
+ remove: (scope, key) => customStore.remove(scope, key),
169
+ listKeys: (scope) => customStore.listKeys(scope),
170
+ clear: (scope) => customStore.clear(scope),
171
+ listScopes: (sessionKey) => customStore.listScopes(sessionKey),
172
+ listScopesWithKnownRecordKeys: (sessionKey) =>
173
+ customStore.listScopesWithKnownRecordKeys(sessionKey),
174
+ getMany: (scope, keys) => customStore.getMany(scope, keys),
175
+ setMany: (scope, entries) => customStore.setMany(scope, entries),
176
+ removeMany: (scope, keys) => customStore.removeMany(scope, keys),
177
+ };
178
+
179
+ const customPersistentStorage = createAsyncStorageAdapter(driver);
180
+ ```
181
+
182
+ Driver methods should preserve the JSON-compatible values TSDF gives them, isolate data by the full namespace scope, and implement bulk methods consistently with their single-record equivalents. `listScopes(...)` and `listScopesWithKnownRecordKeys(...)` are required for cleanup, session clearing, and offline protected-key restoration.
183
+
184
+ ## Example configuration
185
+
186
+ ```ts
187
+ import { rc_object, rc_string } from 'runcheck';
188
+ import { createDocumentStore, createStoreManager } from 'tsdf';
189
+
190
+ type Settings = { id: string; theme: string };
191
+
192
+ const getSessionKey = () => (userId ? `tenant:${userId}` : false);
193
+
194
+ const storeManager = createStoreManager({
195
+ getSessionKey,
196
+ errorNormalizer: normalizeError,
197
+ lowPriorityThrottleMs: 5,
198
+ baseCoalescingWindowMs: 10,
199
+ blockWindowClose: null,
200
+ onPersistentStorageError: (error) => {
201
+ console.error('TSDF persistence failed', error);
202
+ },
203
+ offlineSession: {
204
+ network: { enabled: true },
205
+ mutationQueueing: { network: 'allow', outage: 'allow' },
206
+ },
207
+ });
208
+
209
+ const settingsStore = createDocumentStore<Settings>({
210
+ id: 'document-settings',
211
+ storeManager,
212
+ fetchFn: (signal) => api.getSettings(signal),
213
+ persistentStorage: {
214
+ adapter: 'local-sync',
215
+ version: 2,
216
+ schema: rc_object({ id: rc_string(), theme: rc_string() }),
217
+ onPersistentStorageError: (error) => {
218
+ console.error('Settings persistence failed', error);
219
+ },
220
+ offline: {},
221
+ },
222
+ });
223
+ ```
224
+
225
+ ## Lifecycle behavior
226
+
227
+ - On successful fetch, stores save to persistence after debounce (approximately 1s).
228
+ - On startup/reload, stores attempt restore and set `refetchOnMount: 'lowPriority'` so stale data is revalidated.
229
+ - When a store instance is permanently discarded, call `store.dispose()` to release listeners, browser-tab coordination, and store-manager registration.
230
+ - Invalid or incompatible cache entries are removed automatically.
231
+ - Expired entries are removed by a periodic scan:
232
+ - `local-sync`: ~1 week old entries
233
+ - `opfsPersistentStorage`: ~2 weeks old entries
234
+ - `indexedDbPersistentStorage`: ~2 weeks old entries
235
+
236
+ ## Preload APIs
237
+
238
+ These are useful in components that need control over when async hydration should happen.
239
+
240
+ ### Document store
241
+
242
+ - `preloadPersistentStorage(): Promise<void>`
243
+
244
+ ### Collection store
245
+
246
+ - `preloadItemFromStorage(params): Promise<PersistentStoragePreloadResult<ItemPayload>[]>`
247
+ - `params`: single payload or payload array.
248
+
249
+ ### List query store
250
+
251
+ - `preloadQueryFromStorage(payloads): Promise<PersistentStoragePreloadResult<QueryPayload>[]>`
252
+ - `preloadItemFromStorage(params): Promise<PersistentStoragePreloadResult<ItemPayload>[]>`
253
+ - `params`: single payload or payload array.
254
+
255
+ When list-query offline persistence is enabled, `usePendingOfflineItems()` can
256
+ also restore pending offline item state from persistence without mounting
257
+ `useListQuery()`. This is especially useful for offline-first screens that boot
258
+ directly into queued work.
259
+
260
+ `preload*` returns `preloaded` boolean for each payload.
261
+
262
+ When the selected adapter does not support async preload, preload methods report errors to `onPersistentStorageError` and return `preloaded: false`.
263
+
264
+ ## Cache retention controls
265
+
266
+ - `maxBytes` limits the serialized storage budget for collection items.
267
+ - `maxItemBytes` limits the serialized storage budget for list-query items.
268
+ - `maxQueryBytes` limits the serialized storage budget for list-query query entries.
269
+ - `maxQuerySize` limits how many items each cached query can keep.
270
+ - Pinned entries are never evicted.
271
+ - `ignoreItems` removes/blocks entries from being persisted or hydrated.
272
+ - Can be an explicit list or predicate.
273
+ - Takes precedence over pinned lists.
274
+
275
+ ## Clearing stored data
276
+
277
+ - `clearSessionStorage(sessionKey, adapter)`:
278
+ remove all TSDF entries for one session and adapter.
279
+ - `clearAllSessionStorage(sessionKey)`:
280
+ remove TSDF entries for one session across the built-in `local-sync`, OPFS, and IndexedDB adapters.
281
+
282
+ Use these on logout, user switch, or explicit privacy actions.