tsdf 16.0.2 → 17.0.0-alpha.1

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,261 @@
1
+ # Mutations
2
+
3
+ TSDF provides a structured mutation lifecycle that coordinates with the fetch scheduler to prevent conflicts, supports optimistic updates, and handles error recovery with automatic revalidation.
4
+
5
+ See also: [Offline](./offline.md) for durable offline queueing and replay.
6
+
7
+ ## performMutation
8
+
9
+ The primary way to perform mutations. Available on all store types.
10
+
11
+ ### Document Store
12
+
13
+ ```ts
14
+ const result = await store.performMutation({
15
+ // Optional: update state optimistically before the mutation executes
16
+ optimisticUpdate: (currentState) => {
17
+ if (!currentState) return;
18
+ currentState.name = 'New Name'; // immer-style draft mutation
19
+ },
20
+
21
+ // The actual mutation
22
+ mutation: ({ updateState, currentState }) => {
23
+ return api.updateUser({ name: 'New Name' });
24
+ },
25
+
26
+ // After success, invalidate data to refetch from the server
27
+ revalidateOnSuccess: true,
28
+ });
29
+
30
+ if (result.ok) {
31
+ console.log('Success:', result.value);
32
+ } else {
33
+ console.log('Error:', result.error);
34
+ }
35
+ ```
36
+
37
+ The `mutation` callback receives:
38
+
39
+ - `updateState` - An immer-based function to update state during the mutation
40
+ - `currentState` - The current data at the time the mutation executes
41
+
42
+ ### Collection Store
43
+
44
+ ```ts
45
+ const result = await store.performMutation('item-id', {
46
+ optimisticUpdate: (payload) => {
47
+ store.updateItemState(payload, (draft) => {
48
+ draft.name = 'Updated';
49
+ });
50
+ },
51
+ mutation: (payload) => api.updateItem(payload, { name: 'Updated' }),
52
+ revalidateOnSuccess: true,
53
+ });
54
+ ```
55
+
56
+ ### List Query Store
57
+
58
+ ```ts
59
+ const result = await store.performMutation('item-id', {
60
+ optimisticUpdate: (payload) => {
61
+ store.updateItemState(payload, (draft) => {
62
+ draft.status = 'done';
63
+ });
64
+ },
65
+ mutation: (payload) => api.updateTask(payload, { status: 'done' }),
66
+ revalidateOnSuccess: true,
67
+ });
68
+ ```
69
+
70
+ The payload can be:
71
+
72
+ - A single item payload
73
+ - An array of item payloads
74
+ - A filter function `(payload, data) => boolean`
75
+ - `null` or `undefined` (matches all items)
76
+
77
+ ## Mutation Lifecycle
78
+
79
+ 1. **Lock**: The scheduler is locked for the affected items/queries, preventing concurrent fetches
80
+ 2. **Optimistic update**: If provided, runs immediately. If it returns `false`, the mutation is cancelled
81
+ 3. **Debounce** (optional): Waits for `ms` milliseconds. During debounce, the window close is blocked
82
+ 4. **Execute mutation**: The async mutation function runs
83
+ 5. **On success**: Calls `onSuccess`, optionally invalidates data
84
+ 6. **On error**: Reverts to server state by invalidating, normalizes the error, calls `onMutationError`
85
+ 7. **Unlock**: The scheduler is unlocked, pending fetches resume
86
+
87
+ ## Return Value
88
+
89
+ `performMutation` returns a `Result<T, StoreMutationError | MutationSkipped>`:
90
+
91
+ ```ts
92
+ const result = await store.performMutation(/* ... */);
93
+
94
+ if (result.ok) {
95
+ // result.value is the mutation return value
96
+ } else {
97
+ if (result.error.kind === 'skipped') {
98
+ // optimisticUpdate returned false, or this call was skipped by debounce
99
+ } else {
100
+ // result.error is a StoreMutationError with code/id/message and cause
101
+ }
102
+ }
103
+ ```
104
+
105
+ When a mutation uses the `offline` option, the success value is `OfflineMutationResult<T>`:
106
+
107
+ - `{ kind: 'online', data }` when the direct mutation completed.
108
+ - `{ kind: 'queued' }` when TSDF persisted the mutation for offline replay.
109
+
110
+ ## Optimistic Updates
111
+
112
+ Optimistic updates let you update the UI immediately before the server responds.
113
+
114
+ ```ts
115
+ await store.performMutation('item-id', {
116
+ optimisticUpdate: () => {
117
+ // Update the store directly — the UI updates immediately
118
+ store.updateItemState('item-id', (draft) => {
119
+ draft.completed = true;
120
+ });
121
+ },
122
+ mutation: () => api.completeItem('item-id'),
123
+ });
124
+ ```
125
+
126
+ If the mutation **fails**, TSDF automatically invalidates the data, causing a refetch that reverts the optimistic update to the server's actual state.
127
+
128
+ ### Cancelling a Mutation
129
+
130
+ Return `false` from `optimisticUpdate` to cancel the mutation entirely.
131
+ The returned `Result` will be `Err({ kind: 'skipped' })` rather than a thrown or normalized error:
132
+
133
+ ```ts
134
+ optimisticUpdate: (currentState) => {
135
+ if (currentState?.locked) return false; // cancel mutation
136
+ currentState.name = 'Updated';
137
+ };
138
+ ```
139
+
140
+ ## Debouncing
141
+
142
+ For frequent mutations (e.g., typing), use debounce to batch them:
143
+
144
+ ```ts
145
+ await store.performMutation({
146
+ debounce: {
147
+ context: 'update-name', // debounce key
148
+ payload: newName, // only the latest payload is used
149
+ ms: 500, // wait 500ms of inactivity
150
+ },
151
+ mutation: () => api.updateName(newName),
152
+ });
153
+ ```
154
+
155
+ During the debounce period, the window close is blocked to prevent data loss.
156
+
157
+ ## Revalidation on Success
158
+
159
+ | Option | Behavior |
160
+ | ------------------------------------------------ | ----------------------------------------------------------------- |
161
+ | `revalidateOnSuccess: true` | Invalidates all affected items and queries |
162
+ | `revalidateOnSuccess: 'queries'` | (List Query only) Invalidates only queries, not individual items |
163
+ | `revalidateOnSuccess: (query) => ...` | (List Query only) Invalidates affected items and matching queries |
164
+ | `revalidateOnSuccess: { queries, items: false }` | (List Query only) Invalidates matching queries only |
165
+ | `revalidateOnSuccess: false` (default) | No automatic revalidation |
166
+
167
+ ### Error Handling
168
+
169
+ On error, TSDF **rolls back** optimistic updates to their pre-mutation state. Non-optimistic mutations leave state untouched on error.
170
+
171
+ ## List Query Store Specific Options
172
+
173
+ ```ts
174
+ await store.performMutation(payload, {
175
+ // Revalidate only active queries, without invalidating individual items
176
+ revalidateOnSuccess: {
177
+ queries: (queryPayload) => queryPayload.status === 'active',
178
+ items: false,
179
+ },
180
+
181
+ // Suppress the global onMutationError handler
182
+ silentErrors: true,
183
+
184
+ // Callbacks
185
+ onSuccess: (response, payload) => {
186
+ /* ... */
187
+ },
188
+ onError: (error) => {
189
+ /* ... */
190
+ },
191
+ });
192
+ ```
193
+
194
+ ## Manual Mutation Control
195
+
196
+ For cases where `performMutation` doesn't fit, you can manually control the mutation lock:
197
+
198
+ ```ts
199
+ // Document Store
200
+ const endMutation = store.startMutation();
201
+ try {
202
+ await doSomething();
203
+ } finally {
204
+ endMutation();
205
+ }
206
+
207
+ // Collection Store — locks a specific item
208
+ const endMutation = store.startMutation('item-id');
209
+
210
+ // List Query Store — locks an item and all queries containing it
211
+ const endMutation = store.startItemMutation('item-id');
212
+ ```
213
+
214
+ While a mutation lock is held, the scheduler defers any fetch requests for the locked items/queries.
215
+
216
+ ## Window Close Blocking
217
+
218
+ The manager-level `blockWindowClose` option prevents the user from accidentally closing the browser during a mutation:
219
+
220
+ ```ts
221
+ const storeManager = createStoreManager({
222
+ getSessionKey: () => currentTenantId ?? false,
223
+ errorNormalizer: normalizeError,
224
+ blockWindowClose: () => {
225
+ const handler = (e: BeforeUnloadEvent) => {
226
+ e.preventDefault();
227
+ e.returnValue = '';
228
+ };
229
+ window.addEventListener('beforeunload', handler);
230
+ return {
231
+ unblock: () => window.removeEventListener('beforeunload', handler),
232
+ };
233
+ },
234
+ });
235
+
236
+ const store = createDocumentStore({
237
+ id: 'document-store',
238
+ storeManager,
239
+ // ...
240
+ });
241
+ ```
242
+
243
+ Pass `null` to disable this behavior.
244
+
245
+ ## Mutation Events
246
+
247
+ All stores emit events for mutation lifecycle tracking:
248
+
249
+ ```ts
250
+ store.storeEvents.on('mutationStart', ({ mutationId }) => {
251
+ console.log('Mutation started:', mutationId);
252
+ });
253
+
254
+ store.storeEvents.on('mutationEnd', ({ mutationId, status }) => {
255
+ console.log('Mutation ended:', mutationId, status);
256
+ });
257
+ ```
258
+
259
+ `status` is `'success' | 'error' | 'skipped'`. A mutation is `'skipped'` when its `optimisticUpdate` callback returns `false` or when a debounced mutation is superseded by a newer one with the same debounce key — these are not failures and should usually not trigger error handling.
260
+
261
+ Collection and List Query stores also include the affected `payload`/`items` in the event.
@@ -0,0 +1,207 @@
1
+ # Offline
2
+
3
+ TSDF's offline support is built on top of [Persistent Storage](./persistent-storage.md). It lets offline-enabled mutations fall back to a durable queue, keeps optimistic local state visible, replays queued work when the session recovers, and exposes queue/status data for UI.
4
+
5
+ See also: [Store Manager](./store-manager.md) | [Persistent Storage](./persistent-storage.md) | [Mutations](./mutations.md) | [Hooks](./hooks.md#usependingofflineitems)
6
+
7
+ ## Enabling Offline
8
+
9
+ Offline has two pieces:
10
+
11
+ 1. A shared `offlineSession` on `createStoreManager(...)`.
12
+ 2. Store-local `persistentStorage.offline` config, optionally with operation definitions.
13
+
14
+ ```ts
15
+ import {
16
+ createListQueryStore,
17
+ createStoreManager,
18
+ type DefineListQueryOfflineOperations,
19
+ type DefineOfflineOperation,
20
+ } from 'tsdf';
21
+
22
+ type User = { id: number; name: string };
23
+ type UserPayload = { id: number };
24
+ type RenameInput = { id: number; name: string };
25
+ type UsersQuery = { teamId: string };
26
+
27
+ type UserOfflineOperations = DefineListQueryOfflineOperations<
28
+ User,
29
+ UsersQuery,
30
+ UserPayload,
31
+ { renameUser: DefineOfflineOperation<RenameInput> }
32
+ >;
33
+
34
+ const storeManager = createStoreManager({
35
+ getSessionKey: () => currentTenantId ?? false,
36
+ errorNormalizer: normalizeError,
37
+ lowPriorityThrottleMs: 5,
38
+ baseCoalescingWindowMs: 10,
39
+ blockWindowClose: null,
40
+ offlineSession: {
41
+ network: { enabled: true },
42
+ mutationQueueing: { network: 'allow', outage: 'allow' },
43
+ },
44
+ });
45
+
46
+ const userStore = createListQueryStore<
47
+ User,
48
+ UsersQuery,
49
+ UserPayload,
50
+ false,
51
+ false,
52
+ UserOfflineOperations
53
+ >({
54
+ id: 'users',
55
+ storeManager,
56
+ fetchListFn: (query, size, { signal }) => api.listUsers(query, size, signal),
57
+ fetchItemFn: (payload, { signal }) => api.getUser(payload, signal),
58
+ getItemKey: (payload) => payload.id,
59
+ persistentStorage: {
60
+ adapter: 'local-sync',
61
+ schema: userSchema,
62
+ itemPayloadSchema: userPayloadSchema,
63
+ queryPayloadSchema: usersQuerySchema,
64
+ offline: {
65
+ operations: {
66
+ renameUser: {
67
+ inputSchema: renameUserSchema,
68
+ kind: 'update',
69
+ getEntityRefs: ({ input }) => [{ id: input.id }],
70
+ execute: ({ input }) => api.renameUser(input),
71
+ onSuccessExecute: ({ input }) => {
72
+ userStore.updateItemState({ id: input.id }, (user) => ({
73
+ ...user,
74
+ name: input.name,
75
+ }));
76
+ },
77
+ },
78
+ },
79
+ },
80
+ },
81
+ });
82
+ ```
83
+
84
+ `persistentStorage.offline: {}` is valid when a store only needs session-level offline read/status behavior and has no store-local queued mutation operations.
85
+
86
+ ## Queuing Mutations
87
+
88
+ Use the normal `performMutation(...)` API and add an `offline` descriptor:
89
+
90
+ ```ts
91
+ await userStore.performMutation(
92
+ { id: 1 },
93
+ {
94
+ optimisticUpdate: () => {
95
+ userStore.updateItemState({ id: 1 }, (user) => ({
96
+ ...user,
97
+ name: 'Ada',
98
+ }));
99
+ },
100
+ mutation: () => api.renameUser({ id: 1, name: 'Ada' }),
101
+ offline: { operation: 'renameUser', input: { id: 1, name: 'Ada' } },
102
+ },
103
+ );
104
+ ```
105
+
106
+ When the online mutation succeeds, the result value is `{ kind: 'online', data }`. When TSDF queues the mutation for offline replay, the result value is `{ kind: 'queued' }`.
107
+
108
+ ## Operation Definitions
109
+
110
+ All offline operations define:
111
+
112
+ - `inputSchema` - Validates mutation input before it enters the queue and again when restored.
113
+ - `kind` - `create`, `update`, or `delete`; TSDF derives each affected entity's lifecycle from this.
114
+ - `execute(ctx)` - Sends queued work to the server during replay.
115
+
116
+ Collection and list-query operations also define:
117
+
118
+ - `getEntityRefs({ input })` - Returns affected item/entity refs.
119
+ - `dependsOn({ input })` - Optional dependencies on other offline entities.
120
+
121
+ Optional replay behavior:
122
+
123
+ - `onSuccessExecute(ctx)` - Updates live store state after replay succeeds.
124
+ - `getServerSnapshot(ctx)` - Loads fresh server state before replay checks.
125
+ - `shouldSkipSync(ctx)` - Drops queued work when the server already reflects it.
126
+ - `conflictHandling` - Detects conflicts and creates manual resolution records.
127
+ - `accumulation` - Merges newer queued inputs into an existing queued mutation.
128
+ - `supersedes` - Prunes older queued work for the same entity.
129
+
130
+ Create flows for collection and list-query stores can use `tempEntity` or `tempEntities` to insert optimistic entities with temporary payloads and reconcile them to final server payloads after replay. Document stores do not support temp entities.
131
+
132
+ ## Conflict Resolution
133
+
134
+ Stores expose resolution APIs:
135
+
136
+ ```ts
137
+ const resolutions = userStore.getOfflineResolutions();
138
+
139
+ await userStore.resolveOfflineResolution(resolutions[0].id, 'renameUser', {
140
+ action: 'requeue',
141
+ input: { id: 1, name: 'Ada resolved' },
142
+ });
143
+ ```
144
+
145
+ Supported resolution actions include:
146
+
147
+ - `discard` - Drop the resolution record.
148
+ - `requeue` - Queue replacement input for an operation conflict.
149
+ - `commit` - Accept an externally completed resolution result.
150
+ - `retry` - Retry a retry-exhausted record.
151
+
152
+ Use `parseOfflineResolutionConflict(resolution)` to narrow a persisted resolution back to the operation-specific conflict/input type before rendering a manual resolution UI.
153
+
154
+ ## Reading Offline State
155
+
156
+ Use manager-level APIs for session-wide UI:
157
+
158
+ ```tsx
159
+ const status = storeManager.useOfflineStatus();
160
+ const entities = storeManager.useOfflineEntities();
161
+ const resolutions = storeManager.useOfflineResolutions();
162
+ ```
163
+
164
+ Equivalent global helpers are exported for code that only has a session key:
165
+
166
+ ```ts
167
+ import {
168
+ getGlobalOfflineStatus,
169
+ useGlobalOfflineEntities,
170
+ useGlobalOfflineResolutions,
171
+ } from 'tsdf';
172
+ ```
173
+
174
+ Each store also exposes scoped APIs:
175
+
176
+ - `getOfflineEntities()` / `useOfflineEntities()`
177
+ - `getOfflineResolutions()` / `useOfflineResolutions()`
178
+ - `resolveOfflineResolution(...)`
179
+ - `parseOfflineResolutionConflict(...)`
180
+
181
+ List-query stores additionally expose `usePendingOfflineItems(...)`, which returns pending creates/updates and pending deletes without mounting or fetching a query.
182
+
183
+ ## Runtime Controls
184
+
185
+ The store manager owns runtime controls for the shared session:
186
+
187
+ ```ts
188
+ storeManager.setOfflineRuntimeConfig({ network: { enabled: false } });
189
+
190
+ storeManager.resetOfflineRuntimeConfig();
191
+ ```
192
+
193
+ `getOfflineRuntimeConfig()` returns the current effective controls. Runtime updates are useful for explicit "work offline" toggles, diagnostics, or temporarily disabling queueing modes.
194
+
195
+ ## Uploads
196
+
197
+ Configure uploads on `offlineSession.uploads` when queued mutations depend on local files. The manager exposes upload helpers:
198
+
199
+ - `saveOfflineUpload({ id, file })`
200
+ - `replaceOfflineUpload({ id, file })`
201
+ - `loadOfflineUpload(id)`
202
+ - `deleteOfflineUpload(id)`
203
+ - `resolveOfflineUpload(id)`
204
+ - `resolveOfflineUploads(ids)`
205
+ - `useOfflineUploads()`
206
+
207
+ Operations can declare `dependsOnUploads({ input })` and then read resolved upload refs from `execute({ uploads })`. `opfsOfflineUploadAdapter` is exported as a built-in OPFS-backed upload adapter.
@@ -0,0 +1,111 @@
1
+ # Offset Pagination
2
+
3
+ By default, List Query Store uses "size mode" pagination where the entire result set is re-fetched when loading more items. Offset pagination mode uses actual offset/limit-based pagination, which is more efficient for large datasets.
4
+
5
+ **Store**: [List Query Store](./list-query-store.md) only.
6
+
7
+ ## Enabling Offset Pagination
8
+
9
+ Enable by setting the `TOffsetPagination` type parameter to `true` and providing an `offsetPagination` config:
10
+
11
+ ```ts
12
+ const store = createListQueryStore<Task, TaskFilter, string, false, true>({
13
+ // ^^^^ enables offset pagination
14
+
15
+ // In offset mode, fetchListFn receives { offset, limit } instead of size
16
+ fetchListFn: (filter, { offset, limit }, { signal }) => {
17
+ return api.getTasks(filter, { offset, limit, signal });
18
+ },
19
+
20
+ offsetPagination: {
21
+ maxInvalidationLimit: 200,
22
+ maxParallel: 3,
23
+ },
24
+
25
+ // ...other options
26
+ });
27
+ ```
28
+
29
+ ## How It Works
30
+
31
+ ### Size Mode (Default)
32
+
33
+ In size mode, `loadMore` re-fetches the entire range from 0 to the new total size:
34
+
35
+ ```
36
+ Initial load: fetchListFn(filter, 50) → items 0-49
37
+ Load more: fetchListFn(filter, 100) → items 0-99 (re-fetches everything)
38
+ Load more: fetchListFn(filter, 150) → items 0-149 (re-fetches everything)
39
+ ```
40
+
41
+ ### Offset Mode
42
+
43
+ In offset mode, `loadMore` fetches only the new items:
44
+
45
+ ```
46
+ Initial load: fetchListFn(filter, { offset: 0, limit: 50 }) → items 0-49
47
+ Load more: fetchListFn(filter, { offset: 50, limit: 50 }) → items 50-99 (new items only)
48
+ Load more: fetchListFn(filter, { offset: 100, limit: 50 }) → items 100-149 (new items only)
49
+ ```
50
+
51
+ New items are appended to the existing list.
52
+
53
+ ## Chunked Invalidation
54
+
55
+ When a query with many loaded items is invalidated, fetching all items in a single request could be slow or hit API limits. Offset pagination handles this by splitting the invalidation into parallel chunks:
56
+
57
+ ```
58
+ Query has 500 items loaded, maxInvalidationLimit = 200, maxParallel = 3
59
+
60
+ Chunk 1: fetchListFn(filter, { offset: 0, limit: 200 })
61
+ Chunk 2: fetchListFn(filter, { offset: 200, limit: 200 })
62
+ Chunk 3: fetchListFn(filter, { offset: 400, limit: 100 })
63
+
64
+ Chunks 1-3 run in parallel (up to maxParallel concurrent)
65
+ ```
66
+
67
+ Results are deduplicated (in case of overlapping items) and combined into the final query state.
68
+
69
+ ## Configuration
70
+
71
+ ### maxInvalidationLimit
72
+
73
+ The maximum number of items to fetch in a single request during invalidation. When the loaded size exceeds this, the fetch is split into chunks.
74
+
75
+ ### maxParallel
76
+
77
+ Maximum number of parallel chunk requests during chunked invalidation. Defaults to `3`.
78
+
79
+ ## Loading More
80
+
81
+ ```tsx
82
+ function TaskList() {
83
+ const { items, hasMore, isLoadingMore } = store.useListQuery(filter);
84
+
85
+ return (
86
+ <div>
87
+ {items.map((task) => (
88
+ <TaskRow
89
+ key={task.id}
90
+ task={task}
91
+ />
92
+ ))}
93
+
94
+ {hasMore && (
95
+ <button
96
+ onClick={() => store.loadMore(filter)}
97
+ disabled={isLoadingMore}
98
+ >
99
+ {isLoadingMore ? 'Loading...' : 'Load More'}
100
+ </button>
101
+ )}
102
+ </div>
103
+ );
104
+ }
105
+ ```
106
+
107
+ You can specify a custom size for `loadMore`:
108
+
109
+ ```ts
110
+ store.loadMore(filter, 25); // load 25 more items (instead of defaultQuerySize)
111
+ ```