tsdf 17.0.0-alpha.7 → 17.0.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.d.ts CHANGED
@@ -1,1411 +1,10 @@
1
+ import { $ as OfflineResolutionRecord, A as DefineListQueryOfflineOperations, At as PayloadDebounce, B as OfflineEntityMutationKind, Bt as mutationSkipped, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as TSDFStatus, G as OfflineMutationQueueingPolicy, Gt as ScheduleFetchResults, H as OfflineMutationInput, Ht as RequestSchedulerEventData, I as ListQueryOfflineOperationDefinition, It as UnwrapTSDFResult, J as OfflineReplayRetryConfig, Jt as TSDFDebugLogLevel, K as OfflineOperationKind, Kt as TSDFDebugLogArea, L as OfflineAccumulationConfig, Lt as ValidPayload, M as DocumentOfflineOperationDefinition, Mt as StoreFetchError, N as GlobalOfflineEntity, Nt as StoreMutationError, O as DefineCollectionOfflineOperations, Ot as MaybeTSDFResult, P as GlobalOfflineStatus, Pt as StoreMutationErrorOptions, Q as OfflineResolutionConflictParseErrorCode, R as OfflineAccumulationMergeContext, Rt as ValidStoreState, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as RequestSchedulerEvents, V as OfflineMutationDescriptor, Vt as FetchType, W as OfflineMutationQueueingConfig, Wt as ScheduleFetchOptions, X as OfflineResolutionActionForOperation, Xt as TSDFDebugOptions, Y as OfflineResolutionAction, Yt as TSDFDebugLogger, Z as OfflineResolutionConflictParseError, _ as ListQueryOfflineOperationsConfig, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dt as OfflineTempEntityConfig, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as StoreError, k as DefineDocumentOfflineOperations, kt as MutationSkipped, l as AsyncStorageNamespaceGetResult, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mt as OperationResult, n as AsyncStorageDiscoveredScope, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pt as OperationConflict, q as OfflineQueueEntry, qt as TSDFDebugLogEntry, r as AsyncStorageDriver, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as fetchTypePriority } from "./types-2zQlbxtw.js";
1
2
  import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
2
3
  import { Emitter } from "evtmitter";
3
4
  import { Context } from "react";
4
5
  import { Result } from "t-result";
5
6
  import { Store } from "t-state";
6
- import { RcType } from "runcheck";
7
- import { StandardSchemaV1 } from "@standard-schema/spec";
8
7
 
9
- //#region src/requestScheduler.d.ts
10
- type RequestSchedulerEvents = 'scheduled-fetch-started' | 'rt-fetch-scheduled' | 'rt-fetch-cancelled' | 'scheduled-rt-fetch-started' | 'medium-priority-scheduled' | 'medium-priority-fetch-started' | 'medium-priority-cancelled' | 'batch-size-triggered';
11
- type RequestSchedulerEventData = {
12
- /** Delay in ms for scheduled events (medium-priority-scheduled, rt-fetch-scheduled) */delayMs?: number;
13
- };
14
- type ScheduleFetchResults = 'skipped' | 'started' | 'scheduled' | 'rt-scheduled' | 'triggered' | 'coalesced' | 'medium-scheduled' | 'added-to-batch' | 'batch-triggered';
15
- type FetchType = 'lowPriority' | 'mediumPriority' | 'highPriority' | 'realtimeUpdate';
16
- type ScheduleFetchOptions = {
17
- mediumPriorityDelayMs?: number;
18
- };
19
- //#endregion
20
- //#region src/utils/storeShared.d.ts
21
- type TSDFStatus = 'loading' | 'error' | 'refetching' | 'success';
22
- type ValidPayload = number | string | Record<string, unknown>;
23
- type ValidStoreState = Record<string, unknown> | unknown[];
24
- /**
25
- * Debounce settings for payload-driven automatic fetches in store hooks.
26
- *
27
- * The hook still reads data from state using the latest payload immediately.
28
- * Only the automatic fetch side is delayed. Single hooks do not support
29
- * combining this with `ensureIsLoaded`.
30
- */
31
- type PayloadDebounce = {
32
- /** Debounce window in milliseconds before the latest payload is fetched. */ms: number;
33
- /**
34
- * Maximum time a burst may stay deferred before the latest payload is
35
- * fetched, even if changes keep happening within the debounce window.
36
- */
37
- maxWait?: number;
38
- /**
39
- * When true, the first payload in a burst may fetch immediately, and later
40
- * changes within the same burst stay debounced until the wait window ends.
41
- */
42
- leading?: boolean;
43
- };
44
- type StoreError = {
45
- code: number;
46
- id: string;
47
- message: string;
48
- path?: string;
49
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
50
- };
51
- declare const fetchTypePriority: Record<FetchType, number>;
52
- type MutationSkipped = {
53
- kind: 'skipped';
54
- };
55
- declare const mutationSkipped: MutationSkipped;
56
- /** Options passed to mutation error handlers. */
57
- type StoreMutationErrorOptions = {
58
- /**
59
- * True when the mutation caller asked the shared error handler to stay quiet.
60
- *
61
- * Handlers are still called so apps can keep centralized logging, metrics, or
62
- * custom recovery behavior while suppressing user-facing noise such as toast
63
- * notifications.
64
- */
65
- silentErrors?: boolean;
66
- };
67
- declare class StoreMutationError extends Error {
68
- readonly kind = "error";
69
- code: number;
70
- id: string;
71
- path?: string;
72
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
73
- constructor(error: StoreError, options?: ErrorOptions);
74
- }
75
- declare class StoreFetchError extends Error {
76
- code: number;
77
- id: string;
78
- type: 'fetch' | 'aborted' | 'timeout';
79
- path?: string;
80
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
81
- constructor(error: StoreError, type: 'fetch' | 'aborted' | 'timeout');
82
- }
83
- //#endregion
84
- //#region src/persistentStorage/offlineUploadTypes.d.ts
85
- type OfflineUploadState = 'pending' | 'uploading' | 'uploaded' | 'failed';
86
- type OfflineUploadSource = 'manual' | 'mutation';
87
- type OfflineUploadProgress = {
88
- progress: number;
89
- loadedBytes?: number;
90
- totalBytes?: number;
91
- };
92
- type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
93
- id: string;
94
- sessionKey: string;
95
- source: OfflineUploadSource;
96
- state: OfflineUploadState;
97
- fileName: string;
98
- mimeType: string;
99
- sizeBytes: number;
100
- createdAt: number;
101
- updatedAt: number;
102
- resolvedRef?: TResolvedRef;
103
- progress?: OfflineUploadProgress;
104
- lastError?: {
105
- message: string;
106
- };
107
- };
108
- type OfflineStoredUploadRecord<TResolvedRef extends ValidPayload = ValidPayload> = OfflineUpload<TResolvedRef> & {
109
- file: File;
110
- lastOnlineSessionStartedAt?: number;
111
- lastModified: number;
112
- };
113
- type OfflineUploadAdapter = {
114
- save<TResolvedRef extends ValidPayload>(sessionKey: string, id: string, record: OfflineStoredUploadRecord<TResolvedRef>): Promise<void>;
115
- load<TResolvedRef extends ValidPayload>(sessionKey: string, id: string): Promise<OfflineStoredUploadRecord<TResolvedRef> | null>;
116
- list<TResolvedRef extends ValidPayload>(sessionKey: string): Promise<OfflineStoredUploadRecord<TResolvedRef>[]>;
117
- remove(sessionKey: string, id: string): Promise<void>;
118
- clearSession(sessionKey: string): Promise<void>;
119
- resetForTests?(): void;
120
- };
121
- type OfflineUploadTransportContext = {
122
- id: string;
123
- sessionKey: string;
124
- file: File;
125
- onProgress: (progress: OfflineUploadProgress) => void;
126
- };
127
- type OfflineSessionUploadsConfig<TResolvedRef extends ValidPayload = ValidPayload> = {
128
- adapter: OfflineUploadAdapter;
129
- upload: (ctx: OfflineUploadTransportContext) => Promise<TResolvedRef>;
130
- concurrency?: number;
131
- };
132
- type OfflineMutationUploadsInput = Record<string, Blob | File>;
133
- type OfflineAttachedUploadIds = Record<string, string>;
134
- type OfflineOperationUploadsContext<TResolvedRef extends ValidPayload = ValidPayload> = {
135
- filesById: Record<string, File>;
136
- resolvedRefsById: Record<string, TResolvedRef>;
137
- };
138
- //#endregion
139
- //#region src/persistentStorage/types.d.ts
140
- type AsyncStorageNamespaceKind = 'document' | 'collection.item' | 'listQuery.item' | 'listQuery.query' | 'offline.queue' | 'offline.conflict' | 'offline.entity' | '__internal.protected';
141
- type AsyncStorageNamespaceScope = {
142
- sessionKey: string;
143
- storeName: string;
144
- kind: AsyncStorageNamespaceKind;
145
- };
146
- type AsyncStorageTouchMode = 'never' | 'coarse' | 'force';
147
- type AsyncStorageReadOptions = {
148
- touch?: AsyncStorageTouchMode;
149
- };
150
- type AsyncStorageMetadataOrder = 'key' | 'lru-asc' | 'lru-desc';
151
- type AsyncStorageEntryMetadataBase = {
152
- key: string;
153
- payloadRef: string;
154
- writtenAt: number;
155
- lastAccessAt: number; /** Serialized JSON size used for persistence budgeting for this entry. */
156
- sizeBytes?: number;
157
- version: number;
158
- };
159
- type AsyncStorageEntryMetadata<TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = AsyncStorageEntryMetadataBase & {
160
- customMetadata: TCustomMetadata;
161
- };
162
- type AsyncStorageNamespaceGetResult<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
163
- value: TValue;
164
- metadata: AsyncStorageEntryMetadata<TCustomMetadata>;
165
- };
166
- type AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
167
- key: string;
168
- value: TValue;
169
- serializedValue?: string;
170
- sizeBytes?: number;
171
- version: number;
172
- metadata?: TCustomMetadata;
173
- };
174
- type AsyncStorageNamespaceCommitTouch = {
175
- key: string;
176
- lastAccessAt?: number;
177
- };
178
- type AsyncStorageNamespaceStaticPolicy = {
179
- maxBytes?: number;
180
- pinnedKeys?: string[];
181
- };
182
- type AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
183
- upserts?: AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata>[];
184
- removes?: string[];
185
- staticPolicy?: AsyncStorageNamespaceStaticPolicy | null;
186
- touches?: AsyncStorageNamespaceCommitTouch[];
187
- };
188
- type AsyncStorageDriverSetEntry = {
189
- key: string;
190
- value: unknown;
191
- serializedValue?: string;
192
- sizeBytes?: number;
193
- };
194
- type AsyncStorageDiscoveredScope = {
195
- /** Known raw record keys for this scope. `null` if keys were not enumerated during discovery. */knownRecordKeys: string[] | null;
196
- scope: AsyncStorageNamespaceScope;
197
- };
198
- /** Low-level async backend contract implemented by custom storage drivers. */
199
- type AsyncStorageDriver = {
200
- /** Read a single raw record from a logical namespace. */get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
201
- set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
202
- remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
203
- listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
204
- clear(scope: AsyncStorageNamespaceScope): Promise<void>; /** Namespace discovery used for cold cleanup, protected-key restore, and session clearing. */
205
- listScopes(sessionKey?: string): Promise<AsyncStorageNamespaceScope[]>; /** Returns discovered scopes together with known raw record keys. Used for cleanup. */
206
- listScopesWithKnownRecordKeys(sessionKey?: string): Promise<AsyncStorageDiscoveredScope[]>; /** Bulk read for multiple keys in a single call. */
207
- getMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<unknown[]>; /** Bulk write for multiple entries in a single call. */
208
- setMany(scope: AsyncStorageNamespaceScope, entries: AsyncStorageDriverSetEntry[]): Promise<void>; /** Bulk remove for multiple keys in a single call. */
209
- removeMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<void>;
210
- };
211
- type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
212
- get(key: string, options?: AsyncStorageReadOptions): Promise<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>;
213
- getMany(keys: string[], options?: AsyncStorageReadOptions): Promise<Array<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>>;
214
- listKeys(): Promise<string[]>;
215
- commit(args: AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata>): Promise<void>;
216
- listMetadata(args?: {
217
- order?: AsyncStorageMetadataOrder;
218
- }): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>;
219
- listMetadataByFilter?(args: {
220
- filter: {
221
- equals: unknown;
222
- key: string;
223
- };
224
- order?: AsyncStorageMetadataOrder;
225
- }): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>;
226
- clear(): Promise<void>;
227
- };
228
- /** Managed async adapter consumed by TSDF persistence internals. */
229
- type AsyncStorageAdapter = {
230
- /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Open a logical namespace with managed batching and touch guarantees. */
231
- openNamespace<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>>(scope: AsyncStorageNamespaceScope): AsyncStorageNamespaceHandle<TValue, TCustomMetadata>; /** Reconstruct offline-protected entry refs for a session from persisted metadata. */
232
- readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
233
- syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
234
- clearSession(sessionKey: string): Promise<void>; /** Test-only reset hook used by TSDF internals. */
235
- resetForTests?(): void;
236
- };
237
- /** Injected persistent storage adapter. */
238
- type StorageAdapter = 'local-sync' | AsyncStorageAdapter;
239
- /** Standard Schema v1 (zod, valibot, arktype, etc.). */
240
- type StandardSchemaLike<T> = StandardSchemaV1<unknown, T>;
241
- /** Union of supported schema types for persistent storage validation. */
242
- type PersistentStorageSchema<T> = RcType<T> | StandardSchemaLike<T>;
243
- /**
244
- * Converts between the in-memory store data shape and the persisted storage shape.
245
- * Use this when the cached representation should differ from the API store format.
246
- */
247
- type ConvertedPersistentStorageDataSchema<TFinal, TStorage> = {
248
- /** Schema for the final in-memory store data after hydration. */storeSchema: PersistentStorageSchema<TFinal>; /** Schema for the raw persisted storage representation. */
249
- storageSchema: PersistentStorageSchema<TStorage>; /** Converts in-memory store data into the persisted storage representation. */
250
- convertToStorage: (value: TFinal) => TStorage; /** Converts persisted storage data into the final in-memory store representation. */
251
- convertFromStorage: (value: TStorage) => TFinal;
252
- };
253
- /**
254
- * Schema configuration for persisted store data.
255
- * Accept either the final store schema directly or a converted storage format.
256
- */
257
- type PersistentStorageDataSchema<TFinal, TStorage = unknown> = PersistentStorageSchema<TFinal> | ConvertedPersistentStorageDataSchema<TFinal, TStorage>;
258
- /** Result entry returned by explicit persistent-storage preload APIs. */
259
- type PersistentStoragePreloadResult<Payload extends ValidPayload = ValidPayload> = {
260
- /** Payload loaded from storage or fresh store initialization result. */payload: Payload; /** `true` when payload came from storage cache, `false` when loaded from source. */
261
- preloaded: boolean;
262
- };
263
- type PersistentStorageErrorHandler = (error: unknown) => void;
264
- /** Base config shared by all store types. */
265
- type PersistentStorageBaseConfig<TFinal, TStorage = unknown> = {
266
- /** Unique storage namespace used internally for this store's persisted entries. Must not contain `.`. */storeName: string; /** Injected adapter used to save and restore persistent data. Use `'local-sync'` for built-in localStorage or provide a custom async adapter. */
267
- adapter: StorageAdapter; /** Schema used to validate cached data on load and optionally convert persisted data. */
268
- schema: PersistentStorageDataSchema<TFinal, TStorage>; /** Optional version number for cache invalidation. When omitted, no version is persisted or checked. */
269
- version?: number;
270
- /**
271
- * Returns a session key scoping storage per org/tenant.
272
- * Return `false` to indicate the session is not ready — all storage
273
- * operations (load, save, clear) will be skipped until it returns a string.
274
- */
275
- getSessionKey: () => string | false;
276
- /**
277
- * Called when a storage write operation fails (e.g. quota exceeded, OPFS write error).
278
- * Use this to log or report persistence failures to your error tracking service.
279
- */
280
- onPersistentStorageError?: PersistentStorageErrorHandler | null;
281
- };
282
- /** Store-level persistent storage config. Session scoping comes from the parent store. */
283
- type StorePersistentStorageBaseConfig<TFinal, TStorage = unknown> = Omit<PersistentStorageBaseConfig<TFinal, TStorage>, 'getSessionKey' | 'storeName'>;
284
- type InternalDocumentOfflineOperations$1<State extends ValidStoreState> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> & ([State] extends [never] ? never : unknown);
285
- type DocumentOfflineOperationsConfig$1<State extends ValidStoreState> = InternalDocumentOfflineOperations$1<State> | null;
286
- type PublicStoreOfflineConfig<TOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> = Record<never, never>> = {
287
- /** Store-local offline operation definitions. Optional when only session-level offline controls are used. */operations?: TOperations;
288
- };
289
- type PublicStoreOfflineConfigField<TOfflineOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> | null> = {
290
- /** Optional offline sync/replay configuration for mutations. */offline?: TOfflineOperations extends null ? PublicStoreOfflineConfig : PublicStoreOfflineConfig<Exclude<TOfflineOperations, null>>;
291
- };
292
- /** Persistent storage config for DocumentStore. */
293
- type DocumentPersistentStorageConfig<State extends ValidStoreState, StorageState = unknown, TOfflineOperations extends DocumentOfflineOperationsConfig$1<State> = null> = StorePersistentStorageBaseConfig<State, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations>;
294
- type InternalCollectionOfflineOperations$1<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
295
- getEntityRefs: (ctx: {
296
- input: __LEGIT_ANY__;
297
- }) => CollectionOfflineEntityRef<ItemPayload>[];
298
- dependsOn?: (ctx: {
299
- input: __LEGIT_ANY__;
300
- }) => CollectionOfflineEntityRef<ItemPayload>[];
301
- }> & ([ItemState | ItemPayload] extends [never] ? never : unknown);
302
- type CollectionOfflineOperationsConfig$1<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = InternalCollectionOfflineOperations$1<ItemState, ItemPayload> | null;
303
- type CollectionPersistentStorageFields<ItemPayload extends ValidPayload> = {
304
- /** Schema used to validate cached item payloads on load. */payloadSchema: PersistentStorageSchema<ItemPayload>;
305
- /**
306
- * Maximum serialized JSON size to persist for collection items. Budgeting
307
- * uses the serialized string length, not browser quota bytes. Items are
308
- * evicted via LRU. Defaults to 64 KB in `local-sync` and 128 KB in async
309
- * adapters.
310
- */
311
- maxBytes?: number; /** Item payloads that should never be evicted from storage. */
312
- pinnedItems?: ItemPayload[];
313
- /**
314
- * Item payloads that should never be persisted or restored.
315
- * Accepts either an explicit payload list or a predicate function.
316
- * Takes precedence over `pinnedItems`.
317
- */
318
- ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
319
- };
320
- /** Persistent storage config for CollectionStore. */
321
- type CollectionPersistentStorageConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends CollectionOfflineOperationsConfig$1<ItemState, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & CollectionPersistentStorageFields<ItemPayload>;
322
- type InternalListQueryOfflineOperations<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
323
- getEntityRefs: (ctx: {
324
- input: __LEGIT_ANY__;
325
- }) => ListQueryOfflineEntityRef<ItemPayload>[];
326
- dependsOn?: (ctx: {
327
- input: __LEGIT_ANY__;
328
- }) => ListQueryOfflineEntityRef<ItemPayload>[];
329
- }> & ([ItemState | QueryPayload | ItemPayload] extends [never] ? never : unknown);
330
- type ListQueryOfflineOperationsConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = InternalListQueryOfflineOperations<ItemState, QueryPayload, ItemPayload> | null;
331
- type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
332
- /** Schema used to validate cached item payloads on load. */itemPayloadSchema: PersistentStorageSchema<ItemPayload>; /** Schema used to validate cached query payloads on load. */
333
- queryPayloadSchema: PersistentStorageSchema<QueryPayload>;
334
- /**
335
- * Maximum serialized JSON size to persist for list items. Budgeting uses the
336
- * serialized string length, not browser quota bytes. Defaults to 64 KB in
337
- * `local-sync` and 128 KB in async adapters.
338
- */
339
- maxItemBytes?: number;
340
- /**
341
- * Maximum serialized JSON size to persist for list queries. Budgeting uses
342
- * the serialized string length, not browser quota bytes. Defaults to 32 KB
343
- * in `local-sync` and 64 KB in async adapters.
344
- */
345
- maxQueryBytes?: number; /** Maximum number of items per query to persist. Defaults to 100. */
346
- maxQuerySize?: number; /** Item payloads that should never be evicted from storage. */
347
- pinnedItems?: ItemPayload[]; /** Query payloads that should never be evicted from storage. */
348
- pinnedQueries?: QueryPayload[];
349
- /**
350
- * Item payloads that should never be persisted or restored.
351
- * Accepts either an explicit payload list or a predicate function.
352
- * Takes precedence over `pinnedItems`.
353
- */
354
- ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
355
- };
356
- /** Persistent storage config for ListQueryStore. */
357
- type ListQueryPersistentStorageConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload = ValidPayload, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & ListQueryPersistentStorageFields<QueryPayload, ItemPayload>;
358
- //#endregion
359
- //#region src/persistentStorage/validateWithSchema.d.ts
360
- type SchemaValidationError = readonly string[] | StandardSchemaV1.FailureResult['issues'];
361
- //#endregion
362
- //#region src/persistentStorage/offline/types.d.ts
363
- /** Store kinds supported by offline replay and sync state tracking. */
364
- type OfflineStoreType = 'document' | 'collection' | 'listQuery';
365
- /** Phase where a failure occurred during offline-enabled operation flow. */
366
- type OfflineFailurePhase = 'fetch' | 'mutation' | 'sync';
367
- /** High-level classification used by outage detection. */
368
- type OfflineFailureClassification = 'outage' | 'network' | 'ignore';
369
- /** Kinds of entities participating in offline conflict/sync tracking. */
370
- type OfflineEntityKind = 'document' | 'item' | 'query';
371
- /** Lifecycle declared per offline operation definition. */
372
- type OfflineOperationKind = 'create' | 'update' | 'delete';
373
- /** Effective lifecycle derived for an offline entity across queued work. */
374
- type OfflineEntityMutationKind = 'create' | 'createAndUpdate' | 'update' | 'delete';
375
- /** Connectivity cause currently governing offline mutation queueing. */
376
- type OfflineMutationQueueingCause = 'network' | 'outage';
377
- /** Root policy value for whether offline-enabled mutations may queue. */
378
- type OfflineMutationQueueingPolicy = 'allow' | 'disallow';
379
- /** Root mutation queueing policy shared by all configured offline operations. */
380
- type OfflineMutationQueueingConfig = {
381
- /**
382
- * Controls whether offline-enabled mutations may queue while network mode is
383
- * active, including browser-detected offline and classified network failures.
384
- * @default 'allow'
385
- */
386
- network?: OfflineMutationQueueingPolicy;
387
- /**
388
- * Controls whether offline-enabled mutations may queue while outage mode is
389
- * active.
390
- * @default 'allow'
391
- */
392
- outage?: OfflineMutationQueueingPolicy;
393
- };
394
- /**
395
- * Effective runtime offline controls exposed through an offline session.
396
- *
397
- * All fields are session-scoped and affect every store attached to the same
398
- * offline session.
399
- */
400
- type OfflineRuntimeConfig = {
401
- /** Whether future operations may enter network offline handling. */network: {
402
- enabled: boolean;
403
- }; /** Whether future operations may enter outage offline handling. */
404
- outage: {
405
- enabled: boolean;
406
- }; /** Effective queue admission policy for offline-enabled mutations. */
407
- mutationQueueing: {
408
- network: OfflineMutationQueueingPolicy;
409
- outage: OfflineMutationQueueingPolicy;
410
- };
411
- };
412
- /** Default runtime config when offline is not configured or no session exists. */
413
- declare const defaultOfflineRuntimeConfig: OfflineRuntimeConfig;
414
- /**
415
- * Partial runtime offline control update accepted by an offline session.
416
- *
417
- * Provided fields shallow-merge into the current runtime config.
418
- */
419
- type OfflineRuntimeConfigUpdate = {
420
- /** Optional session-scoped update for network mode enablement. */network?: {
421
- enabled?: boolean;
422
- }; /** Optional session-scoped update for outage mode enablement. */
423
- outage?: {
424
- enabled?: boolean;
425
- }; /** Optional session-scoped update for offline mutation queue admission policy. */
426
- mutationQueueing?: {
427
- network?: OfflineMutationQueueingPolicy;
428
- outage?: OfflineMutationQueueingPolicy;
429
- };
430
- };
431
- /** Context passed into offline failure classification hooks. */
432
- type OfflineFailureContext = {
433
- /** Phase in which the failure was detected. */phase: OfflineFailurePhase; /** Store type affected by the failure. */
434
- storeType: OfflineStoreType; /** Optional operation name associated with the failure. */
435
- operationName?: string; /** Session key used by browser tab and persistence scoping. */
436
- sessionKey: string;
437
- };
438
- /** Re-check strategy for recovery probing. Omitted fields use built-in defaults (which differ between network and outage modes). */
439
- type OfflineRecoveryProbeConfig = {
440
- /**
441
- * Initial recovery check delay, in milliseconds.
442
- * @default 5_000 (network) / 30_000 (outage)
443
- */
444
- initialIntervalMs?: number;
445
- /**
446
- * Maximum recovery check delay, in milliseconds.
447
- * @default 60_000 (network) / 300_000 (outage)
448
- */
449
- maxIntervalMs?: number;
450
- /**
451
- * Multiplicative backoff between recovery probes.
452
- * @default 2
453
- */
454
- backoffMultiplier?: number;
455
- /**
456
- * Jitter ratio (0-1) applied to the recovery probe delay.
457
- * @default 0.2
458
- */
459
- jitterRatio?: number;
460
- };
461
- /** Network availability mode configuration for offline controls. */
462
- type OfflineNetworkModeConfig = {
463
- /** Enable network connectivity detection and tracking. */enabled: boolean;
464
- /**
465
- * If true, subscribe to browser `online` / `offline` events.
466
- * @default true
467
- */
468
- listenToBrowserEvents?: boolean;
469
- /**
470
- * Optional override for network connectivity checks.
471
- * Return `true` when network should be considered offline.
472
- */
473
- getIsOffline?: () => boolean | Promise<boolean>;
474
- /**
475
- * Probe whether classified network recovery has completed.
476
- * Return `true` when the session should leave network offline mode.
477
- */
478
- recoveryCheck?: (ctx: {
479
- sessionKey: string;
480
- }) => Promise<boolean> | boolean; /** Optional probe config to tune classified network recovery behavior. */
481
- recoveryProbe?: OfflineRecoveryProbeConfig;
482
- };
483
- /** Server outage detection and recovery configuration. */
484
- type OfflineOutageModeConfig = {
485
- /** Enable outage mode logic and confirmation retry flow. */enabled: boolean; /** Probe the remote service to confirm outage recovery. */
486
- recoveryCheck: (ctx: {
487
- sessionKey: string;
488
- }) => Promise<boolean> | boolean; /** Optional probe config to tune recovery behavior. */
489
- recoveryProbe?: OfflineRecoveryProbeConfig;
490
- };
491
- /** Fixed replay retry policy for healthy online replay failures. Omitted fields use built-in defaults. */
492
- type OfflineReplayRetryConfig = {
493
- /**
494
- * Max counted failures before manual resolution is required.
495
- * @default 3
496
- */
497
- maxFailures?: number;
498
- /**
499
- * Fixed delay between replay retries, in milliseconds.
500
- * @default 5000
501
- */
502
- intervalMs?: number;
503
- };
504
- /** Shared offline/session policy reused by every store in the same session. */
505
- type OfflineSessionConfig<TUploadRef extends ValidPayload = ValidPayload> = {
506
- /**
507
- * Classify a remote failure as `outage`, `network`, or `ignore`.
508
- * `outage` activates outage recovery behavior.
509
- * `network` activates network offline handling for future operations only
510
- * when `network.enabled` is true. Existing offline recovery may keep using
511
- * classifications until already-active work finishes recovering.
512
- */
513
- classifyFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<OfflineFailureClassification> | OfflineFailureClassification;
514
- /**
515
- * Optional replay-only classifier for ambiguous sync failures that stayed
516
- * online (`classifyFailure(...) === 'ignore'`).
517
- *
518
- * Return `true` only when automatically re-sending the replayed mutation is
519
- * known to be safe. Return `false` to avoid auto-replay retries; in that
520
- * case the entry still enters `needs-confirmation` so `shouldSkipSync` /
521
- * conflict checks can run before the mutation is promoted to manual
522
- * resolution.
523
- */
524
- classifyRetryableFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<boolean> | boolean; /** Network detection strategy and browser integration. */
525
- network?: OfflineNetworkModeConfig; /** Outage detection and recovery strategy for remote failures. */
526
- outage?: OfflineOutageModeConfig; /** Fixed retry policy for healthy online replay failures. */
527
- replayRetry?: OfflineReplayRetryConfig;
528
- /**
529
- * Root policy controlling whether offline-enabled mutations may enter the
530
- * durable offline queue for each active offline cause.
531
- * @default undefined
532
- */
533
- mutationQueueing?: OfflineMutationQueueingConfig; /** Optional upload transport/storage config shared by the whole session. */
534
- uploads?: OfflineSessionUploadsConfig<TUploadRef>;
535
- };
536
- /** Per-session offline status snapshot shared across tabs. */
537
- type GlobalOfflineStatus = {
538
- /** Session key for this status bucket. */sessionKey: string;
539
- /**
540
- * Network mode admission enablement plus the last observed network-offline
541
- * state for this session. `active` is preserved even while new admission is
542
- * disabled so existing offline work can recover and sync safely.
543
- */
544
- network: {
545
- enabled: boolean;
546
- active: boolean;
547
- };
548
- /**
549
- * Outage mode admission enablement plus the last observed outage-active
550
- * state for this session. `active` is preserved even while new admission is
551
- * disabled so existing offline work can recover and sync safely.
552
- */
553
- outage: {
554
- enabled: boolean;
555
- active: boolean;
556
- }; /** Whether the session currently has any active offline cause. */
557
- isOfflineMode: boolean; /** Whether this tab currently acts as leader for this session. */
558
- isLeader: boolean; /** Timestamp when this status entry was last updated. */
559
- updatedAt: number; /** Timestamp of the last failure, if any. */
560
- lastFailureAt: number | null; /** Timestamp of last recovery probe execution, if any. */
561
- lastRecoveryCheckAt: number | null;
562
- };
563
- /** Queue state of an offline mutation entry. */
564
- type OfflineSyncState = 'pending' | 'syncing' | 'needs-confirmation';
565
- /** Aggregated offline status for a tracked document/item/query entity. */
566
- type GlobalOfflineEntity = {
567
- /** Internal entity identifier tracked by offline machinery. */id: string; /** Session key for this offline entity. */
568
- sessionKey: string; /** Store name where the entity is defined. */
569
- storeName: string; /** Store type this entity belongs to. */
570
- storeType: OfflineStoreType; /** Entity key used for deduping and conflict scoping. */
571
- entityKey: string; /** Entity kind used in queue partitioning. */
572
- entityKind: OfflineEntityKind; /** Effective lifecycle derived from queued operations targeting this entity. */
573
- kind: OfflineEntityMutationKind; /** Number of pending mutations waiting for sync. */
574
- pendingMutations: number; /** Current sync state for the entity. */
575
- syncState: OfflineSyncState | 'resolution-required'; /** Whether the entity currently requires manual resolution. */
576
- requiresResolution: boolean; /** Resolution ids currently blocking this entity from being resolved/applied. */
577
- blockedByResolutionIds: string[]; /** Child resolution ids currently derived from this entity's dependency chain. */
578
- childResolutionIds: string[]; /** Number of blocking parent resolutions currently affecting this entity. */
579
- blockedResolutionCount: number; /** Number of child resolutions currently derived from this entity's dependency chain. */
580
- childResolutionCount: number; /** Creation timestamp for lifecycle bookkeeping. */
581
- createdAt: number; /** Last mutation/update timestamp. */
582
- updatedAt: number; /** Optional temporary ID for optimistic create flows. */
583
- tempId?: ValidPayload;
584
- };
585
- /** Reference to an entity participating in offline sync tracking. */
586
- type OfflineEntityRef = {
587
- entityKey: string;
588
- entityKind: OfflineEntityKind;
589
- };
590
- /**
591
- * Persisted offline conflict payload.
592
- *
593
- * @typeParam TConflict - Conflict payload stored for later resolution.
594
- * @typeParam TInput - Original mutation input associated with the conflict.
595
- */
596
- type OfflineConflictResolutionRecordBase<TConflict = unknown, TInput = unknown> = {
597
- /** Resolution record identifier. */id: string; /** Resolution kind. */
598
- kind: 'conflict'; /** Queue entry identifier that produced this conflict. */
599
- entryId: string; /** Session key that owns this conflict record. */
600
- sessionKey: string; /** Store name associated with the conflict. */
601
- storeName: string; /** Store type associated with the conflict. */
602
- storeType: OfflineStoreType; /** Operation name linked to the conflict. */
603
- operation: string; /** Input value that triggered the conflict. */
604
- input: TInput; /** Conflict payload returned by the resolver. */
605
- conflict: TConflict; /** Timestamp when the original queued mutation was enqueued. */
606
- enqueuedAt: number; /** Entity references involved in the conflict. */
607
- entityRefs: OfflineEntityRef[]; /** Conflict creation timestamp. */
608
- createdAt: number; /** Conflict update timestamp. */
609
- updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
610
- tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
611
- attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
612
- dependencyUploadIds?: string[];
613
- };
614
- /** Derived dependency metadata exposed for offline manual resolutions. */
615
- type OfflineResolutionDependencyMetadata = {
616
- /** Parent resolution ids that must be cleared before this resolution can be retried or discarded. */blockedByResolutionIds: string[]; /** Child manual resolutions currently derived from this resolution's dependency chain. */
617
- childResolutionIds: string[]; /** Number of blocking parent resolutions affecting this resolution. */
618
- blockedResolutionCount: number; /** Number of child manual resolutions currently derived from this resolution. */
619
- childResolutionCount: number;
620
- };
621
- /**
622
- * Persisted offline conflict payload with derived dependency metadata.
623
- *
624
- * @typeParam TConflict - Conflict payload stored for later resolution.
625
- * @typeParam TInput - Original mutation input associated with the conflict.
626
- */
627
- type OfflineConflictResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecordBase<TConflict, TInput> & OfflineResolutionDependencyMetadata;
628
- /**
629
- * Persisted resolution record created when replay retries are exhausted.
630
- *
631
- * @typeParam TInput - Original mutation input associated with the replay failure.
632
- */
633
- type OfflineRetryExhaustedResolutionRecordBase<TInput = unknown> = {
634
- /** Resolution record identifier. */id: string; /** Resolution kind. */
635
- kind: 'retry-exhausted'; /** Queue entry identifier that exhausted replay retries. */
636
- entryId: string; /** Session key that owns this resolution record. */
637
- sessionKey: string; /** Store name associated with the resolution. */
638
- storeName: string; /** Store type associated with the resolution. */
639
- storeType: OfflineStoreType; /** Operation name linked to the replay failure. */
640
- operation: string; /** Input value that exhausted replay retries. */
641
- input: TInput; /** Timestamp when the original queued mutation was enqueued. */
642
- enqueuedAt: number; /** Entity references involved in the resolution. */
643
- entityRefs: OfflineEntityRef[]; /** Last replay error snapshot captured before exhaustion. */
644
- lastReplayError: {
645
- message: string;
646
- }; /** Resolution creation timestamp. */
647
- createdAt: number; /** Resolution update timestamp. */
648
- updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
649
- tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
650
- attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
651
- dependencyUploadIds?: string[];
652
- };
653
- /**
654
- * Persisted resolution record created when replay retries are exhausted, plus
655
- * derived dependency metadata.
656
- *
657
- * @typeParam TInput - Original mutation input associated with the replay failure.
658
- */
659
- type OfflineRetryExhaustedResolutionRecord<TInput = unknown> = OfflineRetryExhaustedResolutionRecordBase<TInput> & OfflineResolutionDependencyMetadata;
660
- /**
661
- * Persisted offline resolution payload.
662
- *
663
- * @typeParam TConflict - Conflict payload stored for later resolution.
664
- * @typeParam TInput - Original mutation input associated with the resolution.
665
- */
666
- type OfflineResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecord<TConflict, TInput> | OfflineRetryExhaustedResolutionRecord<TInput>;
667
- /** Session-scoped offline controller shared across stores in the same session. */
668
- type OfflineSession<TUploadRef extends ValidPayload = ValidPayload> = {
669
- /** Returns the active session key used to scope shared offline state. */getSessionKey: () => string | false; /** Shared static session configuration used by attached stores. */
670
- getConfig: () => OfflineSessionConfig<TUploadRef>; /** Latest effective runtime config for this session. */
671
- getOfflineRuntimeConfig: () => OfflineRuntimeConfig; /** Updates runtime controls for this session. */
672
- setOfflineRuntimeConfig: (update: OfflineRuntimeConfigUpdate) => void; /** Resets runtime controls back to the static session config. */
673
- resetOfflineRuntimeConfig: () => void; /** Returns the latest global offline status for the session. */
674
- getOfflineStatus: () => GlobalOfflineStatus; /** Returns the latest aggregated offline entities for the session. */
675
- getOfflineEntities: () => readonly GlobalOfflineEntity[]; /** Returns the latest aggregated conflict/retry resolutions for the session. */
676
- getOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns the latest session-scoped offline uploads for the session. */
677
- getOfflineUploads: () => readonly OfflineUpload<TUploadRef>[]; /** Resolves a staged upload id to its latest final ref, uploading first if needed. */
678
- resolveOfflineUpload: (id: string) => Promise<TUploadRef>; /** Resolves multiple staged upload ids to their latest final refs. */
679
- resolveOfflineUploads: (ids: readonly string[]) => Promise<Record<string, TUploadRef>>; /** Saves a session-scoped upload locally for later dependency resolution or ref usage. */
680
- saveOfflineUpload: (args: {
681
- id: string;
682
- file: Blob | File;
683
- }) => Promise<void>; /** Replaces a previously stored session-scoped upload. */
684
- replaceOfflineUpload: (args: {
685
- id: string;
686
- file: Blob | File;
687
- }) => Promise<void>; /** Loads a previously stored session-scoped upload. */
688
- loadOfflineUpload: (id: string) => Promise<File | null>; /** Deletes a stored upload when it is no longer referenced. */
689
- deleteOfflineUpload: (id: string) => Promise<void>; /** React hook subscribing to the session's global offline status. */
690
- useOfflineStatus: () => GlobalOfflineStatus; /** React hook subscribing to the session's aggregated offline entities. */
691
- useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to the session's aggregated conflict/retry resolutions. */
692
- useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** React hook subscribing to the session's upload list. */
693
- useOfflineUploads: () => readonly OfflineUpload<TUploadRef>[];
694
- };
695
- /**
696
- * Persisted offline mutation queue entry.
697
- *
698
- * @typeParam TInput - Serialized input payload for the queued mutation.
699
- * @typeParam TConflict - Conflict payload that may be attached while waiting for confirmation or resolution.
700
- */
701
- type OfflineQueueEntry<TInput = unknown, TConflict = unknown> = {
702
- /** Queue entry identifier. */id: string; /** Session key for queue scoping. */
703
- sessionKey: string; /** Store name where operation is defined. */
704
- storeName: string; /** Store type for this queued operation. */
705
- storeType: OfflineStoreType; /** Operation name registered in offline configuration. */
706
- operation: string; /** Operation input payload persisted with the entry. */
707
- input: TInput; /** Stable ordering key used to replay queued operations deterministically. */
708
- queueOrder: number; /** Entity references tied to this mutation. */
709
- entityRefs: OfflineEntityRef[]; /** Number of execution attempts so far. */
710
- attempts: number; /** Queue entry creation timestamp. */
711
- createdAt: number; /** Last entry update timestamp. */
712
- updatedAt: number; /** Timestamp of last execution attempt, if any. */
713
- lastAttemptAt: number | null; /** Synchronization state for this entry. */
714
- syncState: OfflineSyncState; /** Optional temporary IDs for optimistic create operations. */
715
- tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
716
- attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
717
- dependencyUploadIds?: string[]; /** Last recorded sync error if replay failed. */
718
- lastError?: {
719
- message: string;
720
- };
721
- /**
722
- * Whether a `needs-confirmation` entry may auto-resend during healthy replay
723
- * retries after confirmation checks finish.
724
- */
725
- allowReplayRetry?: boolean; /** Pending conflict payload when confirmation or resolution is required. */
726
- pendingConflict?: TConflict;
727
- };
728
- /** Built-in resolution actions for retry exhaustion records. */
729
- type OfflineRetryExhaustedResolutionAction = {
730
- action: 'retry';
731
- /**
732
- * Controls whether retrying a resolution should also requeue retryable
733
- * descendants from the same temp-lifecycle dependency chain.
734
- * @default 'self-and-descendants'
735
- */
736
- scope?: 'self' | 'self-and-descendants';
737
- } | {
738
- action: 'discard';
739
- };
740
- /**
741
- * Built-in resolution actions for persisted conflict records.
742
- *
743
- * `commit` is intended for flows where the final API call has already been made
744
- * externally and the store only needs to clear bookkeeping plus reconcile any
745
- * temp-entity lifecycle using the accepted server result.
746
- *
747
- * @typeParam TInput - Input type expected when requeueing a replacement mutation.
748
- * @typeParam TResult - Result shape returned by the external conflict resolution call.
749
- */
750
- type OfflineConflictResolutionAction<TInput = unknown, TResult = unknown> = {
751
- action: 'discard';
752
- } | {
753
- action: 'requeue';
754
- input: TInput;
755
- } | {
756
- action: 'commit';
757
- result?: TResult;
758
- };
759
- /**
760
- * Built-in resolution actions accepted by `resolveOfflineResolution(...)`.
761
- *
762
- * @typeParam TInput - Input type expected when requeueing a replacement mutation.
763
- * @typeParam TResult - Result shape returned by an externally completed conflict resolution call.
764
- */
765
- type OfflineResolutionAction<TInput = unknown, TResult = unknown> = OfflineRetryExhaustedResolutionAction | OfflineConflictResolutionAction<TInput, TResult>;
766
- /**
767
- * Extracts operation input type from a schema map.
768
- *
769
- * @typeParam TOperations - Operation registry to inspect.
770
- * @typeParam TName - Operation name whose input type should be extracted.
771
- */
772
- type OperationInput<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
773
- inputSchema: PersistentStorageSchema<infer TInput>;
774
- } ? TInput : never;
775
- /**
776
- * A typed operation descriptor for an offline mutation queue entry.
777
- *
778
- * @typeParam TOperations - Operation registry that defines valid operation names and input schemas.
779
- * @typeParam TName - Operation name to describe. Defaults to all operation names in the registry.
780
- */
781
- type OfflineMutationDescriptor<TOperations extends Record<string, {
782
- inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
783
- }>, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: {
784
- /** Operation key from the offline operations registry. */operation: K; /** Input resolved from the registered operation schema. */
785
- input: OperationInput<TOperations, K>;
786
- } }[TName];
787
- /**
788
- * Public offline mutation input accepted by store mutation APIs.
789
- *
790
- * Callers queue exactly one descriptor per mutation fallback.
791
- */
792
- type OfflineMutationInput<TOperations extends Record<string, {
793
- inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
794
- }>, TName extends keyof TOperations & string = keyof TOperations & string> = OfflineMutationDescriptor<TOperations, TName>;
795
- /**
796
- * Extracts operation result type from a registered operation map.
797
- *
798
- * @typeParam TOperations - Operation registry to inspect.
799
- * @typeParam TName - Operation name whose result type should be extracted.
800
- */
801
- type OperationResult<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
802
- execute: (...args: __LEGIT_ANY__[]) => infer TResult;
803
- } ? Awaited<TResult> : never;
804
- /**
805
- * Resolution action accepted for a specific registered offline operation.
806
- *
807
- * @typeParam TOperations - Operation registry to inspect.
808
- * @typeParam TName - Operation name whose resolution payload should be extracted.
809
- */
810
- type OfflineResolutionActionForOperation<TOperations, TName extends keyof TOperations> = OfflineResolutionAction<OperationInput<TOperations, TName>, OperationResult<TOperations, TName>>;
811
- /**
812
- * Context passed into offline mutation accumulation hooks.
813
- *
814
- * @typeParam TInput - Input type shared by the existing and incoming queued mutations.
815
- */
816
- type OfflineAccumulationMergeContext<TInput> = {
817
- /** Session key used to isolate queued mutations. */sessionKey: string; /** Existing input already present in queue. */
818
- existingInput: TInput; /** Incoming input for merge attempt. */
819
- incomingInput: TInput;
820
- };
821
- /**
822
- * Optional in-memory accumulation strategy for queued offline mutations.
823
- *
824
- * @typeParam TInput - Input type that will be merged and revalidated before persisting.
825
- */
826
- type OfflineAccumulationConfig<TInput> = {
827
- /** Merge function for combining existing and incoming mutation inputs. */mergeInput: (ctx: OfflineAccumulationMergeContext<TInput>) => Promise<TInput> | TInput;
828
- };
829
- /**
830
- * Optional queue-pruning strategy for queued offline mutations.
831
- *
832
- * `same-entity` only applies to operations that resolve exactly one entity ref.
833
- * When enabled, the new operation may remove earlier unattempted pending entries
834
- * targeting that same single entity before the new entry is persisted.
835
- */
836
- type OfflineSupersedeConfig = {
837
- /** Drop earlier unattempted pending entries for the same single entity. */scope: 'same-entity';
838
- /**
839
- * Limits which earlier operations may be pruned for that entity.
840
- *
841
- * Omit this to prune every earlier pending operation for the entity,
842
- * use `'self'` to prune only earlier entries of the current operation,
843
- * or provide explicit operation names to target a specific related set.
844
- */
845
- operations?: 'self' | readonly string[];
846
- /**
847
- * When the pruned entries include a temp-entity lifecycle, drop the current
848
- * operation itself instead of persisting a replacement entry.
849
- */
850
- dropSelfIfTempLifecycleCancelled?: boolean;
851
- };
852
- /** Shared context passed to offline replay lifecycle hooks. */
853
- type OperationBaseContext<TInput> = {
854
- /** Input payload for the queued mutation currently being processed. */input: TInput; /** Timestamp when the operation was originally enqueued. */
855
- enqueuedAt: number; /** Timestamp when the queued entry or conflict record was last updated. */
856
- updatedAt: number;
857
- /**
858
- * Resolves a previously temp-backed entity ref to its latest known final ref
859
- * when one has been reconciled.
860
- */
861
- resolveEntityRef: <TEntityRef extends ValidPayload>(entityRef: TEntityRef) => TEntityRef;
862
- };
863
- type OperationExecuteContext<TInput, TUploadRef extends ValidPayload = ValidPayload> = OperationBaseContext<TInput> & {
864
- uploads: OfflineOperationUploadsContext<TUploadRef>;
865
- };
866
- /** Context passed to the post-replay success hook after `execute(...)` settles. */
867
- type OfflineOperationExecuteSuccessContext<TInput, TResult> = OperationBaseContext<TInput> & {
868
- /** Replay result returned by `execute(...)`. */result: TResult;
869
- };
870
- /**
871
- * Optional callback used to synchronize UI/cache state after a successful
872
- * offline replay execute.
873
- */
874
- type OfflineOperationExecuteSuccessHandler<TInput, TResult> = (ctx: OfflineOperationExecuteSuccessContext<TInput, TResult>) => Promise<void> | void;
875
- type IsUnknown<T> = unknown extends T ? [keyof T] extends [never] ? true : false : false;
876
- /** Context passed to replay checks that may use a fresh server snapshot. */
877
- type OperationReplayCheckContext<TInput, TServerSnapshot> = OperationBaseContext<TInput> & {
878
- /**
879
- * Optional snapshot fetched immediately before `shouldSkipSync` and
880
- * `detectConflict`.
881
- */
882
- serverSnapshot: IsUnknown<TServerSnapshot> extends true ? undefined : TServerSnapshot;
883
- };
884
- /**
885
- * Conflict hook configuration for a queued offline operation.
886
- *
887
- * @typeParam TInput - Input type of the queued operation being checked and potentially requeued.
888
- * @typeParam TConflict - Conflict payload produced by detection and persisted for later external resolution.
889
- */
890
- type OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot = unknown> = {
891
- /** Schema used to validate and sanitize persisted conflict payloads. */schema: PersistentStorageSchema<TConflict>;
892
- /**
893
- * Inspect remote state before replaying the mutation and return conflict payload
894
- * when the queued mutation can no longer be applied safely.
895
- */
896
- detectConflict: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<TConflict | false | null> | TConflict | false | null;
897
- };
898
- type ConflictHandlingField<TInput, TConflict, TServerSnapshot> = IsUnknown<TConflict> extends true ? {
899
- /**
900
- * Optional conflict strategy when a queued operation diverges from remote state.
901
- */
902
- conflictHandling?: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
903
- } : {
904
- /**
905
- * Conflict strategy required when the operation declares a concrete
906
- * conflict payload type.
907
- */
908
- conflictHandling: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
909
- };
910
- type ServerSnapshotField<TInput, TServerSnapshot> = IsUnknown<TServerSnapshot> extends true ? {
911
- /**
912
- * Optionally loads a fresh server-side snapshot before replay checks run.
913
- * The result is passed to `shouldSkipSync` and `detectConflict` as
914
- * `ctx.serverSnapshot`.
915
- */
916
- getServerSnapshot?: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
917
- } : {
918
- /**
919
- * Required when the operation declares a concrete server snapshot type.
920
- * The result is passed to `shouldSkipSync` and `detectConflict` as
921
- * `ctx.serverSnapshot`.
922
- */
923
- getServerSnapshot: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
924
- };
925
- /**
926
- * Replacement data returned by `tempEntity.reconcileServerEntity(...)`.
927
- *
928
- * @typeParam TFinalPayload - Final payload that should replace the temporary one.
929
- * @typeParam TFinalData - Optional replacement entity data for the final payload.
930
- */
931
- type OfflineTempEntityReconciliation<TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
932
- /** Final payload that should replace the temporary optimistic one. */finalPayload: TFinalPayload;
933
- /**
934
- * Optional replacement data for the final payload.
935
- * Omit this to keep the current optimistic entity data and only swap the
936
- * payload/identity.
937
- */
938
- finalData?: TFinalData;
939
- };
940
- /**
941
- * Replacement data returned by `tempEntities.reconcileServerEntities(...)`.
942
- *
943
- * @typeParam TTempId - Temporary payload that should be reconciled.
944
- * @typeParam TFinalPayload - Final payload that should replace the temporary one.
945
- * @typeParam TFinalData - Optional replacement entity data for the final payload.
946
- */
947
- type OfflineTempEntitiesReconciliation<TTempId extends ValidPayload = ValidPayload, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = OfflineTempEntityReconciliation<TFinalPayload, TFinalData> & {
948
- /** Temporary payload that should be reconciled. */tempId: TTempId;
949
- };
950
- /**
951
- * Pending temp-entity returned by `tempEntities.buildPendingEntities(...)`.
952
- *
953
- * @typeParam TTempId - Temporary payload used to track the optimistic entity.
954
- * @typeParam TPendingEntity - Pending entity snapshot to insert locally.
955
- */
956
- type OfflineTempEntityPendingEntry<TTempId extends ValidPayload = ValidPayload, TPendingEntity = unknown> = {
957
- /** Temporary payload that identifies the optimistic entity. */tempId: TTempId; /** Pending entity snapshot inserted while the mutation is queued. */
958
- pendingEntity: TPendingEntity;
959
- };
960
- /**
961
- * Optional temp-id lifecycle for optimistic offline create flows.
962
- *
963
- * @typeParam TInput - Input type used to derive the temporary entity and identifier.
964
- * @typeParam TTempResult - Result returned by `execute`, used only by `tempEntity.reconcileServerEntity(...)`.
965
- * @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
966
- */
967
- type OfflineTempEntityConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
968
- /**
969
- * Builds the optimistic entity inserted into local state while the mutation
970
- * is queued offline.
971
- *
972
- * `tempId` is the temporary payload used to identify the optimistic entity
973
- * until replay succeeds and the final server entity can replace it.
974
- */
975
- buildPendingEntity: (input: TInput, tempId: TTempId) => TPendingEntity;
976
- /**
977
- * Reconciles the optimistic temp entity with the successful replay result.
978
- */
979
- reconcileServerEntity: (result: TTempResult, tempId: TTempId) => OfflineTempEntityReconciliation<TFinalPayload, TFinalData>;
980
- };
981
- /**
982
- * Optional temp-id lifecycle for optimistic offline batch-create flows.
983
- *
984
- * @typeParam TInput - Input type used to derive the temporary entities and identifiers.
985
- * @typeParam TTempResult - Result returned by `execute`, used only by `tempEntities.reconcileServerEntities(...)`.
986
- * @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
987
- */
988
- type OfflineTempEntitiesConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
989
- /**
990
- * Builds the optimistic entities inserted into local state while the mutation
991
- * is queued offline.
992
- *
993
- * `tempIds` are the temporary payloads derived from the operation entity refs
994
- * and used until replay succeeds and the final server entities can replace them.
995
- */
996
- buildPendingEntities: (input: TInput, tempIds: readonly TTempId[]) => readonly OfflineTempEntityPendingEntry<TTempId, TPendingEntity>[];
997
- /**
998
- * Reconciles the optimistic temp entities with the successful replay result.
999
- */
1000
- reconcileServerEntities: (result: TTempResult, tempIds: readonly TTempId[]) => readonly OfflineTempEntitiesReconciliation<TTempId, TFinalPayload, TFinalData>[];
1001
- };
1002
- type NoTempEntityFields = {
1003
- tempEntity?: never;
1004
- tempEntities?: never;
1005
- };
1006
- type ConfiguredTempEntityFields<TInput, TTempResult, TTempId extends ValidPayload, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
1007
- tempEntity: OfflineTempEntityConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
1008
- tempEntities?: never;
1009
- } | {
1010
- tempEntity?: never;
1011
- tempEntities: OfflineTempEntitiesConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
1012
- };
1013
- /**
1014
- * Shape used by `persistentStorage.offline.operations` for each operation name.
1015
- *
1016
- * @typeParam TInput - The persisted input payload for the queued offline operation.
1017
- * @typeParam TConflict - The conflict payload produced by pre-execution conflict detection.
1018
- * @typeParam TTempResult - Result returned by `execute`, used only when `tempEntity` or `tempEntities` needs to reconcile the final server entity. Defaults to `void`.
1019
- */
1020
- type OfflineOperationDefinition<TInput, TConflict, TTempResult = void, TServerSnapshot = unknown, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown, TUploadRef extends ValidPayload = ValidPayload> = {
1021
- /** Schema used to validate incoming operation input. */inputSchema: PersistentStorageSchema<TInput>; /** Lifecycle classification for the queued operation. */
1022
- kind: OfflineOperationKind;
1023
- /**
1024
- * Optional queue pruning for newer operations that supersede older queued work.
1025
- *
1026
- * This is mutually exclusive with `accumulation`.
1027
- */
1028
- supersedes?: OfflineSupersedeConfig;
1029
- /**
1030
- * Executes the queued mutation against the remote source during replay.
1031
- * This may run multiple times when transient failures occur.
1032
- */
1033
- execute: (ctx: OperationExecuteContext<TInput, TUploadRef>) => Promise<TTempResult> | TTempResult;
1034
- /**
1035
- * Optional check executed before retrying a previously failed sync attempt.
1036
- * Return `true` to drop the queued entry because the remote side already reflects it.
1037
- * Return `false` to continue with normal replay.
1038
- */
1039
- shouldSkipSync?: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<boolean> | boolean;
1040
- } & ConflictHandlingField<TInput, TConflict, TServerSnapshot> & ServerSnapshotField<TInput, TServerSnapshot> & (({
1041
- /**
1042
- * Explicit store-sync step that runs after `execute(...)` succeeds during
1043
- * offline replay.
1044
- *
1045
- * Provide a callback when replay should update the live store after the
1046
- * server-side execute succeeds.
1047
- */
1048
- onSuccessExecute: OfflineOperationExecuteSuccessHandler<TInput, TTempResult>;
1049
- /**
1050
- * Optional queue compaction for consecutive mutations with same refs.
1051
- */
1052
- accumulation?: OfflineAccumulationConfig<TInput>;
1053
- } & NoTempEntityFields) | ({
1054
- /**
1055
- * Temp-entity operations already reconcile the live store through
1056
- * `tempEntity` / `tempEntities`, so they must not declare an extra
1057
- * success sync callback.
1058
- */
1059
- onSuccessExecute?: undefined; /** Temp-entity operations cannot compact multiple queued creates. */
1060
- accumulation?: never;
1061
- } & ConfiguredTempEntityFields<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>));
1062
- type WithoutTempEntity<T extends {
1063
- tempEntity?: unknown;
1064
- tempEntities?: unknown;
1065
- }> = Omit<T, 'tempEntity' | 'tempEntities'> & {
1066
- /** Document stores do not support optimistic temp entities. */tempEntity?: never; /** Document stores do not support optimistic batch temp entities. */
1067
- tempEntities?: never;
1068
- };
1069
- /** Context used to resolve which entities a queued mutation affects. */
1070
- type OperationEntityRefsContext<TInput> = {
1071
- /** Input payload for the queued mutation. */input: TInput;
1072
- };
1073
- /** Non-store-specific offline operation definition alias. */
1074
- type AnyOfflineOperationDefinition<TUploadRef extends ValidPayload = ValidPayload> = {
1075
- inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
1076
- kind: OfflineOperationKind;
1077
- conflictHandling?: {
1078
- schema: PersistentStorageSchema<__LEGIT_ANY__>;
1079
- detectConflict: (ctx: __LEGIT_ANY__) => unknown;
1080
- };
1081
- accumulation?: OfflineAccumulationConfig<__LEGIT_ANY__>;
1082
- supersedes?: OfflineSupersedeConfig;
1083
- tempEntity?: OfflineTempEntityConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
1084
- tempEntities?: OfflineTempEntitiesConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
1085
- getServerSnapshot?: (ctx: OperationBaseContext<__LEGIT_ANY__>) => unknown;
1086
- execute: (ctx: OperationExecuteContext<__LEGIT_ANY__, TUploadRef>) => unknown;
1087
- onSuccessExecute?: OfflineOperationExecuteSuccessHandler<__LEGIT_ANY__, __LEGIT_ANY__>;
1088
- shouldSkipSync?: (ctx: OperationReplayCheckContext<__LEGIT_ANY__, __LEGIT_ANY__>) => Promise<boolean> | boolean;
1089
- } & {
1090
- getEntityRefs?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => unknown[];
1091
- dependsOn?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => __LEGIT_ANY__[];
1092
- dependsOnUploads?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => string[];
1093
- };
1094
- /**
1095
- * Compact type-spec helper for a single offline operation.
1096
- *
1097
- * Use this helper with {@link DefineDocumentOfflineOperations} to describe each
1098
- * operation using generic parameters instead of inline object literals.
1099
- *
1100
- * The generic order is `input`, `conflict`, `temp result`, then `server snapshot`.
1101
- *
1102
- * @typeParam TInput - Input payload accepted by the operation.
1103
- * @typeParam TConflict - Conflict payload produced by optional conflict handling.
1104
- * @typeParam TTempResult - Result returned by `execute`, also reused when externally committed conflict resolution needs temp-entity reconciliation.
1105
- *
1106
- * @example
1107
- * ```ts
1108
- * type UpdateName = DefineOfflineOperation<
1109
- * { name: string },
1110
- * { remoteName: string },
1111
- * { name: string }
1112
- * >;
1113
- * ```
1114
- */
1115
- type DefineOfflineOperation<TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown> = {
1116
- /** Input type accepted by the operation. */input?: TInput; /** Conflict payload type produced by the optional conflict handler. */
1117
- conflict?: TConflict; /** Result returned by `execute`, also reused by externally committed conflict resolution for temp-entity reconciliation. */
1118
- result?: TTempResult; /** Snapshot type returned by `getServerSnapshot` and exposed to replay checks. */
1119
- serverSnapshot?: TServerSnapshot;
1120
- };
1121
- type DocumentOperationInput<TOptions extends DefineOfflineOperation> = TOptions extends {
1122
- input?: infer TInput;
1123
- } ? TInput : unknown;
1124
- type DocumentOperationConflict<TOptions extends DefineOfflineOperation> = TOptions extends {
1125
- conflict?: infer TConflict;
1126
- } ? TConflict : unknown;
1127
- type DocumentOperationResult<TOptions extends DefineOfflineOperation> = TOptions extends {
1128
- result?: infer TTempResult;
1129
- } ? TTempResult : unknown;
1130
- type DocumentOperationServerSnapshot<TOptions extends DefineOfflineOperation> = TOptions extends {
1131
- serverSnapshot?: infer TServerSnapshot;
1132
- } ? TServerSnapshot : unknown;
1133
- /**
1134
- * Document-store specific offline operation definition.
1135
- *
1136
- * Prefer this alias when manually typing a single operation inside
1137
- * `persistentStorage.offline.operations` for a document store.
1138
- *
1139
- * `TOptions` is usually provided with {@link DefineOfflineOperation}, which lets
1140
- * callers specify the queued `input`, replay `result`, and optional `conflict`
1141
- * payload concisely. Document stores do not support `tempEntity`.
1142
- *
1143
- * Omitted properties default to `unknown`.
1144
- *
1145
- * @typeParam State - Document state type for the owning store.
1146
- * @typeParam TOptions - Operation typing options, usually created with {@link DefineOfflineOperation}.
1147
- *
1148
- * @example
1149
- * ```ts
1150
- * type RenameOperation = DocumentOfflineOperationDefinition<
1151
- * UserDoc,
1152
- * DefineOfflineOperation<
1153
- * { name: string },
1154
- * { remoteName: string },
1155
- * { name: string }
1156
- * >
1157
- * >;
1158
- * ```
1159
- */
1160
- type DocumentOfflineOperationDefinition<State extends ValidStoreState, TOptions extends DefineOfflineOperation = DefineOfflineOperation, TUploadRef extends ValidPayload = ValidPayload> = WithoutTempEntity<OfflineOperationDefinition<DocumentOperationInput<TOptions>, DocumentOperationConflict<TOptions>, DocumentOperationResult<TOptions>, DocumentOperationServerSnapshot<TOptions>, string, unknown, ValidPayload, unknown, TUploadRef>> & {
1161
- /** Declares which upload ids must finish before replaying this operation. */dependsOnUploads?: (ctx: OperationEntityRefsContext<DocumentOperationInput<TOptions>>) => string[];
1162
- } & ([State] extends [never] ? never : unknown);
1163
- /**
1164
- * Builds a document offline operations map from a compact operation spec.
1165
- *
1166
- * This is the recommended way to type a document store's full offline operation map.
1167
- * Each operation key is typically described with {@link DefineOfflineOperation},
1168
- * and this helper expands that into the full
1169
- * {@link DocumentOfflineOperationDefinition} map expected by the store.
1170
- *
1171
- * @typeParam State - Document state type for the owning store.
1172
- * @typeParam TOperations - Operation map where each key declares its input, replay result, and optional conflict payload.
1173
- *
1174
- * @example
1175
- * ```ts
1176
- * type Operations = DefineDocumentOfflineOperations<
1177
- * UserDoc,
1178
- * {
1179
- * updateName: DefineOfflineOperation<
1180
- * { name: string },
1181
- * unknown,
1182
- * { name: string }
1183
- * >;
1184
- * archive: DefineOfflineOperation<
1185
- * { reason: string },
1186
- * { code: string }
1187
- * >;
1188
- * }
1189
- * >;
1190
- * ```
1191
- *
1192
- * Then use the resulting type as the `operations` object contract:
1193
- *
1194
- * ```ts
1195
- * const operations: Operations = {
1196
- * updateName: {
1197
- * inputSchema: z.object({ name: z.string() }),
1198
- * kind: 'update',
1199
- * execute: ({ input }) => ({ name: input.name }),
1200
- * },
1201
- * archive: {
1202
- * inputSchema: z.object({ reason: z.string() }),
1203
- * kind: 'delete',
1204
- * conflictHandling: {
1205
- * schema: z.object({ code: z.string() }),
1206
- * detectConflict: () => false,
1207
- * },
1208
- * execute: () => undefined,
1209
- * },
1210
- * };
1211
- * ```
1212
- */
1213
- type DefineDocumentOfflineOperations<State extends ValidStoreState, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: DocumentOfflineOperationDefinition<State, TOperations[TName], TUploadRef> };
1214
- /**
1215
- * Collection offline entity reference.
1216
- *
1217
- * Collection operations return raw item payloads, which are normalized to the
1218
- * internal item key by the store.
1219
- *
1220
- * @typeParam ItemPayload - Collection item payload type for the owning store.
1221
- */
1222
- type CollectionOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
1223
- /**
1224
- * Collection-store specific offline operation definition.
1225
- *
1226
- * @typeParam ItemState - Collection item state type for the owning store.
1227
- * @typeParam ItemPayloadUnused - Collection payload type used to anchor the operation to the owning store type.
1228
- * @typeParam TInput - Input type accepted by the offline operation.
1229
- * @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
1230
- * @typeParam TTempResult - Result returned by `execute`.
1231
- * When `tempEntity` or `tempEntities` is provided, the pending builders must
1232
- * return `ItemState`, and the reconciliation hooks must return an
1233
- * `ItemPayload` plus optional `ItemState` replacement data.
1234
- */
1235
- type CollectionOfflineOperationDefinition<ItemState extends ValidStoreState, ItemPayloadUnused extends ValidPayload, TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown, TUploadRef extends ValidPayload = ValidPayload> = OfflineOperationDefinition<TInput, TConflict, TTempResult, TServerSnapshot, ItemPayloadUnused, ItemState, ItemPayloadUnused, ItemState, TUploadRef> & {
1236
- /**
1237
- * Declares which collection items are affected by this queued mutation.
1238
- *
1239
- * Return the raw collection payloads for the affected items. The store will
1240
- * convert each payload with the configured item key logic.
1241
- */
1242
- getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[];
1243
- /**
1244
- * Declares which collection item refs must resolve before replaying this
1245
- * operation.
1246
- */
1247
- dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
1248
- dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
1249
- } & ([ItemState | ItemPayloadUnused] extends [never] ? never : unknown);
1250
- /**
1251
- * Builds a collection offline operations map from a compact operation spec.
1252
- *
1253
- * Use this helper to define the full `persistentStorage.offline.operations` contract for a
1254
- * collection store while keeping each operation's type declaration short.
1255
- *
1256
- * Each operation key is described with {@link DefineOfflineOperation}, and this
1257
- * helper expands it into the corresponding
1258
- * {@link CollectionOfflineOperationDefinition}. The runtime operation object
1259
- * still needs to provide `getEntityRefs(...)`.
1260
- *
1261
- * @typeParam ItemState - Collection item state type for the owning store.
1262
- * @typeParam ItemPayload - Collection payload type for the owning store.
1263
- * @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
1264
- *
1265
- * @example
1266
- * ```ts
1267
- * type Operations = DefineCollectionOfflineOperations<
1268
- * TodoItem,
1269
- * string,
1270
- * {
1271
- * renameTodo: DefineOfflineOperation<
1272
- * { id: string; title: string }
1273
- * >;
1274
- * createTodo: DefineOfflineOperation<
1275
- * { title: string },
1276
- * unknown,
1277
- * { id: string; title: string }
1278
- * >;
1279
- * }
1280
- * >;
1281
- * ```
1282
- */
1283
- type DefineCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: CollectionOfflineOperationDefinition<ItemState, ItemPayload, DocumentOperationInput<TOperations[TName]>, DocumentOperationConflict<TOperations[TName]>, DocumentOperationResult<TOperations[TName]>, DocumentOperationServerSnapshot<TOperations[TName]>, TUploadRef> };
1284
- /**
1285
- * List-query offline entity reference.
1286
- *
1287
- * List-query operations return raw item payloads, which are normalized to the
1288
- * internal item key by the store.
1289
- *
1290
- * @typeParam ItemPayload - Item payload type for the owning list-query store.
1291
- */
1292
- type ListQueryOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
1293
- /**
1294
- * List-query-store specific offline operation definition.
1295
- *
1296
- * @typeParam ItemState - List item state type for the owning store.
1297
- * @typeParam QueryPayload - Query payload type used by the list store.
1298
- * @typeParam ItemPayloadUnused - Item payload type used to anchor the operation to the owning store type.
1299
- * @typeParam TInput - Input type accepted by the offline operation.
1300
- * @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
1301
- * @typeParam TTempResult - Result returned by `execute`.
1302
- * When `tempEntity` or `tempEntities` is provided, the pending builders must
1303
- * return `ItemState`, and the reconciliation hooks must return an
1304
- * `ItemPayload` plus optional `ItemState` replacement data.
1305
- */
1306
- type ListQueryOfflineOperationDefinition<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayloadUnused extends ValidPayload, TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown, TUploadRef extends ValidPayload = ValidPayload> = OfflineOperationDefinition<TInput, TConflict, TTempResult, TServerSnapshot, ItemPayloadUnused, ItemState, ItemPayloadUnused, ItemState, TUploadRef> & {
1307
- /**
1308
- * Declares which list-query entities are affected by this queued mutation.
1309
- *
1310
- * Return the raw item payloads for the affected items. The store will
1311
- * convert each payload with the configured item key logic.
1312
- */
1313
- getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[];
1314
- /**
1315
- * Declares which list item refs must resolve before replaying this
1316
- * operation.
1317
- */
1318
- dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
1319
- dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
1320
- } & ([ItemState | QueryPayload | ItemPayloadUnused] extends [never] ? never : unknown);
1321
- /**
1322
- * Builds a list-query offline operations map from a compact operation spec.
1323
- *
1324
- * Use this helper to define the full `persistentStorage.offline.operations` contract for a
1325
- * list-query store while keeping each operation's type declaration short.
1326
- *
1327
- * Each operation key is described with {@link DefineOfflineOperation}, and this
1328
- * helper expands it into the corresponding
1329
- * {@link ListQueryOfflineOperationDefinition}. The runtime operation object
1330
- * still needs to provide `getEntityRefs(...)`.
1331
- *
1332
- * @typeParam ItemState - List item state type for the owning store.
1333
- * @typeParam QueryPayload - Query payload type used by the list store.
1334
- * @typeParam ItemPayload - Item payload type used by the list store.
1335
- * @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
1336
- *
1337
- * @example
1338
- * ```ts
1339
- * type Operations = DefineListQueryOfflineOperations<
1340
- * User,
1341
- * { tableId: 'users' },
1342
- * { tableId: 'users'; id: number } | string,
1343
- * {
1344
- * renameUser: DefineOfflineOperation<
1345
- * { id: number; name: string }
1346
- * >;
1347
- * createUser: DefineOfflineOperation<
1348
- * { name: string },
1349
- * unknown,
1350
- * { id: number; name: string }
1351
- * >;
1352
- * }
1353
- * >;
1354
- * ```
1355
- */
1356
- type DefineListQueryOfflineOperations<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: ListQueryOfflineOperationDefinition<ItemState, QueryPayload, ItemPayload, DocumentOperationInput<TOperations[TName]>, DocumentOperationConflict<TOperations[TName]>, DocumentOperationResult<TOperations[TName]>, DocumentOperationServerSnapshot<TOperations[TName]>, TUploadRef> };
1357
- /**
1358
- * Extracts operation conflict payload from a registered operation map.
1359
- *
1360
- * @typeParam TOperations - Operation registry to inspect.
1361
- * @typeParam TName - Operation name whose conflict payload should be extracted.
1362
- */
1363
- type OperationConflict<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
1364
- conflictHandling?: OfflineConflictHandlingConfig<__LEGIT_ANY__, infer TConflict>;
1365
- } ? TConflict : never;
1366
- /**
1367
- * Result returned when decoding a stored offline conflict payload.
1368
- *
1369
- * `ok: true` contains the typed conflict payload. `ok: false` contains a
1370
- * machine-readable parse error describing why decoding was not possible.
1371
- */
1372
- type ParsedOfflineResolutionConflictResultForOperation<TOperations, TName extends keyof TOperations & string> = Result<OperationConflict<TOperations, TName>, OfflineResolutionConflictParseError>;
1373
- type ParsedOfflineResolutionConflictResultForStore<TOperations> = ParsedOfflineResolutionConflictResultForOperation<TOperations, keyof TOperations & string>;
1374
- /**
1375
- * Operation-aware offline resolution record for a specific registered operation.
1376
- *
1377
- * @typeParam TOperations - Operation registry to inspect.
1378
- * @typeParam TName - Operation name whose stored resolution shape should be extracted.
1379
- */
1380
- type OfflineResolutionRecordForOperation<TOperations, TName extends keyof TOperations & string> = (OfflineConflictResolutionRecord<OperationConflict<TOperations, TName>, OperationInput<TOperations, TName>> & {
1381
- operation: TName;
1382
- }) | (OfflineRetryExhaustedResolutionRecord<OperationInput<TOperations, TName>> & {
1383
- operation: TName;
1384
- });
1385
- /**
1386
- * Union of operation-aware offline resolution records for an operation registry.
1387
- *
1388
- * @typeParam TOperations - Operation registry to inspect.
1389
- * @typeParam TName - Optional subset of operation names to include.
1390
- */
1391
- type OfflineResolutionRecordForStore<TOperations, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: OfflineResolutionRecordForOperation<TOperations, K> }[TName];
1392
- type OfflineResolutionConflictParseErrorCode = 'not-conflict' | 'offline-not-configured' | 'operation-not-found' | 'conflict-handling-missing' | 'invalid-conflict-payload';
1393
- /** Error returned when decoding a stored offline conflict payload fails. */
1394
- declare class OfflineResolutionConflictParseError extends Error {
1395
- code: OfflineResolutionConflictParseErrorCode;
1396
- operation: string;
1397
- kind?: OfflineResolutionRecord['kind'];
1398
- rawValue?: unknown;
1399
- validationError?: SchemaValidationError;
1400
- constructor(args: {
1401
- code: OfflineResolutionConflictParseErrorCode;
1402
- operation: string;
1403
- kind?: OfflineResolutionRecord['kind'];
1404
- rawValue?: unknown;
1405
- validationError?: SchemaValidationError;
1406
- });
1407
- }
1408
- //#endregion
1409
8
  //#region src/persistentStorage/offline/mutationRuntime.d.ts
1410
9
  /**
1411
10
  * Successful result of an offline-enabled mutation attempt.
@@ -1414,26 +13,33 @@ declare class OfflineResolutionConflictParseError extends Error {
1414
13
  * `queued` means the mutation was durably persisted for offline replay.
1415
14
  */
1416
15
  type OfflineMutationResult<T> = {
1417
- kind: 'online';
16
+ /** The direct online mutation completed successfully. */kind: 'online'; /** Server payload returned by the direct mutation. */
1418
17
  data: Awaited<T>;
1419
18
  } | {
1420
- kind: 'queued';
19
+ /** The mutation was durably queued for offline replay. */kind: 'queued';
1421
20
  };
1422
21
  //#endregion
1423
22
  //#region src/utils/performMutation.d.ts
23
+ /** Starts a temporary window-close block while a mutation is in progress. */
1424
24
  type BlockWindowCloseHandler = () => {
1425
- unblock: () => void;
25
+ /** Releases the window-close block. */unblock: () => void;
1426
26
  };
27
+ /** Debounce settings for mutation calls sharing a logical context and payload. */
1427
28
  type MutationDebounce = {
1428
- context: string;
1429
- payload: unknown;
29
+ /** Logical namespace for the debounced mutation group. */context: string; /** Payload compared with the context to decide which calls supersede each other. */
30
+ payload: unknown; /** Debounce window in milliseconds. */
1430
31
  ms: number;
1431
32
  };
1432
33
  //#endregion
1433
34
  //#region src/storeManager.d.ts
35
+ type DynamicRealtimeThrottleMs = (params: {
36
+ readonly lastFetchDuration: number;
37
+ readonly windowIsNotFocused: boolean;
38
+ }) => number;
1434
39
  type StoreManagerStoreDefaults = {
1435
40
  /** Default minimum interval between low-priority fetches for attached stores. */readonly lowPriorityThrottleMs: number; /** Default coalescing window used by attached stores when they do not override it. */
1436
- readonly baseCoalescingWindowMs: number; /** Shared window-close blocker used by mutations in attached stores. */
41
+ readonly baseCoalescingWindowMs: number; /** Default adaptive throttle for real-time updates in attached stores. */
42
+ readonly dynamicRealtimeThrottleMs: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. */
1437
43
  readonly blockWindowClose: BlockWindowCloseHandler | null; /** Default focus revalidation policy for attached stores. */
1438
44
  readonly revalidateOnWindowFocus: boolean | (() => boolean) | undefined;
1439
45
  };
@@ -1464,8 +70,10 @@ type StoreManagerOfflineApi<TUploadRef extends ValidPayload = ValidPayload> = {
1464
70
  useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** React hook subscribing to the manager's aggregated offline uploads. */
1465
71
  useOfflineUploads: () => readonly OfflineUpload<TUploadRef>[];
1466
72
  };
73
+ /** Shared coordinator passed to every TSDF store instance in an app/session. */
1467
74
  type StoreManager<TUploadRef extends ValidPayload = ValidPayload> = {
1468
- /** Returns the active shared session / tenant key. */getSessionKey: () => string | false; /** Normalizes raw exceptions into the shared StoreError shape. */
75
+ /** Returns the active shared session / tenant key. */getSessionKey: () => string | false; /** Shared debug logger for browser-tab sync and persistent storage internals. */
76
+ debugLogger?: TSDFDebugLogger; /** Normalizes raw exceptions into the shared StoreError shape. */
1469
77
  errorNormalizer: (exception: Error) => StoreError; /** Global fallback for persistent storage failures in attached stores. */
1470
78
  onPersistentStorageError: PersistentStorageErrorHandler | undefined; /** Global fallback for mutation failures in attached stores. */
1471
79
  onMutationError: StoreManagerMutationErrorHandler | undefined; /** Shared defaults used by attached stores unless a store-level override exists. */
@@ -1474,6 +82,7 @@ type StoreManager<TUploadRef extends ValidPayload = ValidPayload> = {
1474
82
  resetAll: (ignoreStores: string[]) => void; /** Signals a shared real-time transport reconnect to all registered stores. */
1475
83
  onTransportReconnect: () => void;
1476
84
  } & StoreManagerOfflineApi<TUploadRef>;
85
+ /** Options used to create a shared TSDF store manager. */
1477
86
  type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> = {
1478
87
  /**
1479
88
  * Returns the current authenticated session / tenant key shared by all
@@ -1483,49 +92,21 @@ type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> =
1483
92
  getSessionKey: () => string | false; /** Normalizes raw exceptions into the shared StoreError shape. */
1484
93
  errorNormalizer: (exception: Error) => StoreError; /** Default minimum interval between low-priority fetches for attached stores. Defaults to 5ms. */
1485
94
  lowPriorityThrottleMs?: number; /** Default coalescing window for attached stores. Defaults to 10ms. */
1486
- baseCoalescingWindowMs?: number; /** Shared window-close blocker used by mutations in attached stores. Pass `null` to disable. */
95
+ baseCoalescingWindowMs?: number; /** Default adaptive throttle for real-time updates in attached stores. Store-level values override it. */
96
+ dynamicRealtimeThrottleMs?: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. Pass `null` to disable. */
1487
97
  blockWindowClose?: BlockWindowCloseHandler | null; /** Global fallback for persistent storage failures when a store does not provide its own handler. */
1488
98
  onPersistentStorageError?: PersistentStorageErrorHandler; /** Global fallback for mutation failures when a store does not provide its own handler. */
1489
99
  onMutationError?: StoreManagerMutationErrorHandler; /** Default focus revalidation policy for attached stores. Store-level values override it. */
1490
- revalidateOnWindowFocus?: boolean | (() => boolean); /** Optional shared offline session config for every attached store. */
100
+ revalidateOnWindowFocus?: boolean | (() => boolean);
101
+ /**
102
+ * Enables debug logs for browser-tab sync and persistent storage operations.
103
+ * Pass `true` to use console logging, or pass a logger function.
104
+ */
105
+ debug?: TSDFDebugOptions; /** Optional shared offline session config for every attached store. */
1491
106
  offlineSession?: OfflineSessionConfig<TUploadRef>;
1492
107
  };
1493
108
  declare function createStoreManager<TUploadRef extends ValidPayload = ValidPayload>(options: CreateStoreManagerOptions<TUploadRef>): StoreManager<TUploadRef>;
1494
109
  //#endregion
1495
- //#region src/utils/browserTabsPriority.d.ts
1496
- type BrowserTabsPriorityTimings = {
1497
- heartbeatMs?: number;
1498
- presenceTtlMs?: number;
1499
- fetchLeaseMs?: number | ((lastFetchDuration: number) => number);
1500
- };
1501
- type BrowserTabsTabStatusMessage = {
1502
- kind: 'tab-status';
1503
- isFocused: boolean;
1504
- lastFocusedAt: number;
1505
- lastPresenceAt: number;
1506
- };
1507
- //#endregion
1508
- //#region src/utils/browserTabsSync.d.ts
1509
- type BrowserTabsStoreType = 'document' | 'collection' | 'listQuery' | 'offline';
1510
- type BrowserTabsTransport = {
1511
- postMessage: (message: unknown) => void;
1512
- close: () => void;
1513
- };
1514
- type BrowserTabsTransportFactory = (options: {
1515
- channelName: string;
1516
- onMessage: (message: unknown) => void;
1517
- }) => BrowserTabsTransport | null;
1518
- type BrowserTabsMessageMeta = {
1519
- protocolVersion: 1;
1520
- messageId: string;
1521
- storeType: BrowserTabsStoreType;
1522
- sessionKey: string;
1523
- tabId: string;
1524
- seq: number;
1525
- sentAt: number;
1526
- };
1527
- type SnapshotConsistency = 'optimistic' | 'confirmed';
1528
- //#endregion
1529
110
  //#region src/collectionStore/useMultipleItems.d.ts
1530
111
  type UseMultipleItemsOptions$1<ItemState extends ValidStoreState, Selected> = {
1531
112
  /** Maps each item before it is returned from the hook. */selector?: (data: ItemState | null) => Selected; /** Returns `idle` instead of `loading` while items have not been fetched. */
@@ -1558,26 +139,31 @@ type UseItemOptions$1<ItemState extends ValidStoreState, Selected> = UseMultiple
1558
139
  };
1559
140
  //#endregion
1560
141
  //#region src/collectionStore/collectionStore.d.ts
142
+ /** Lifecycle status for a cached collection item. */
1561
143
  type CollectionItemStatus = TSDFStatus;
144
+ /** Raw cached state for one collection item. */
1562
145
  type TSFDCollectionItem<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
1563
- data: ItemState | null;
1564
- error: StoreError | null;
1565
- status: CollectionItemStatus;
1566
- payload: ItemPayload;
1567
- refetchOnMount: false | FetchType;
146
+ /** Latest loaded item data, or `null` before the item is available. */data: ItemState | null; /** Last fetch error for this item, when the latest fetch failed. */
147
+ error: StoreError | null; /** Current fetch lifecycle status for this item. */
148
+ status: CollectionItemStatus; /** Payload used to identify and fetch this item. */
149
+ payload: ItemPayload; /** Pending automatic refetch priority for stale data mounted by hooks. */
150
+ refetchOnMount: false | FetchType; /** Whether this item has ever loaded successfully. */
1568
151
  wasLoaded: boolean;
1569
152
  };
153
+ /** Raw t-state shape used by a collection store. */
1570
154
  type TSFDCollectionState<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, TSFDCollectionItem<ItemState, ItemPayload> | null>;
155
+ /** Value returned by `CollectionStore.useItem(...)` and `useMultipleItems(...)`. */
1571
156
  type TSFDUseCollectionItemReturn<Selected, ItemPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
1572
- data: Selected;
1573
- status: CollectionItemStatus | 'idle' | 'deleted';
1574
- payload: ItemPayload | undefined;
1575
- error: StoreError | null;
1576
- itemStateKey: string;
157
+ /** Selected item data. Defaults to the full item or `null`. */data: Selected; /** Hook-visible item status, including idle/deleted states for hook ergonomics. */
158
+ status: CollectionItemStatus | 'idle' | 'deleted'; /** Item payload for this result, unless omitted or unavailable. */
159
+ payload: ItemPayload | undefined; /** Last item fetch error, if any. */
160
+ error: StoreError | null; /** Stable store key for the current item payload. */
161
+ itemStateKey: string; /** Convenience flag for `loading` or `refetching` states. */
1577
162
  isLoading: boolean; /** Whether this result has local offline changes that still need to sync to the server. */
1578
- pendingSync: boolean;
163
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
1579
164
  queryMetadata: QueryMetadata;
1580
165
  };
166
+ /** Item descriptor accepted by `CollectionStore.useMultipleItems(...)`. */
1581
167
  type CollectionUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
1582
168
  /** Item payload to subscribe to and fetch when needed. */payload: ItemPayload; /** Metadata returned with this query result for caller-side bookkeeping. */
1583
169
  queryMetadata?: QueryMetadata; /** Omits `payload` from this query result. */
@@ -1592,15 +178,13 @@ type CollectionUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMeta
1592
178
  returnRefetchingStatus?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
1593
179
  isOffScreen?: boolean;
1594
180
  };
181
+ /** Callback invoked when an already-loaded collection item is invalidated. */
1595
182
  type OnCollectionItemInvalidate<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (props: {
1596
- itemState: ItemState;
1597
- payload: ItemPayload;
183
+ /** Current cached item state at invalidation time. */itemState: ItemState; /** Payload of the invalidated item. */
184
+ payload: ItemPayload; /** Fetch priority requested for the invalidation. */
1598
185
  priority: FetchType;
1599
186
  }) => void;
1600
- type CollectionInitialStateItem<ItemPayload extends ValidPayload, ItemState extends ValidStoreState> = {
1601
- payload: ItemPayload;
1602
- data: ItemState;
1603
- };
187
+ /** Events emitted by collection mutation lifecycle helpers. */
1604
188
  type CollectionStoreStoreEvents<ItemPayload extends ValidPayload> = {
1605
189
  /** Emitted when a mutation begins executing */mutationStart: {
1606
190
  mutationId: number;
@@ -1616,61 +200,46 @@ type CollectionStoreStoreEvents<ItemPayload extends ValidPayload> = {
1616
200
  finalPayload: ItemPayload;
1617
201
  };
1618
202
  };
203
+ /** Details passed when collection cache-limit cleanup evicts cached items. */
1619
204
  type CollectionStateCleanup<ItemPayload extends ValidPayload> = {
1620
- reason: 'cacheLimitEviction';
1621
- itemKeys: string[];
205
+ /** Cleanup trigger that removed these items. */reason: 'cacheLimitEviction'; /** Store keys removed from the collection state. */
206
+ itemKeys: string[]; /** Original item payloads removed from the collection state. */
1622
207
  payloads: ItemPayload[];
1623
208
  };
1624
- type CollectionBrowserTabsMessage<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (BrowserTabsMessageMeta & BrowserTabsTabStatusMessage) | (BrowserTabsMessageMeta & {
1625
- kind: 'collection-item-snapshot';
1626
- itemKey: string;
1627
- consistency: SnapshotConsistency;
1628
- item: TSFDCollectionItem<ItemState, ItemPayload> | null;
1629
- }) | (BrowserTabsMessageMeta & {
1630
- kind: 'fetch-start';
1631
- targetKey: string;
1632
- requestIds: string[];
1633
- startedAt: number;
1634
- }) | (BrowserTabsMessageMeta & {
1635
- kind: 'fetch-success';
1636
- targetKey: string;
1637
- requestIds: string[];
1638
- startedAt: number;
1639
- duration: number;
1640
- });
1641
209
  type InternalCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition & {
1642
210
  getEntityRefs: (ctx: {
1643
211
  input: __LEGIT_ANY__;
1644
212
  }) => CollectionOfflineEntityRef<ItemPayload>[];
1645
213
  }> & ([ItemState | ItemPayload] extends [never] ? never : unknown);
1646
214
  type CollectionOfflineOperationsConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = InternalCollectionOfflineOperations<ItemState, ItemPayload> | null;
215
+ /** Options used to create a collection store. */
1647
216
  type CollectionStoreOptions<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null, StorageState = unknown> = {
1648
217
  /**
1649
218
  * Stable id for this logical collection store. Used for debug labels,
1650
219
  * persistence namespaces, and browser tab sync.
1651
220
  */
1652
221
  id: string; /** Shared global store manager providing session scoping and error normalization. */
1653
- storeManager: StoreManager;
1654
- fetchFn: (params: ItemPayload, signal: AbortSignal) => Promise<ItemState>; /** Optional batch fetch function for fetching multiple items at once */
1655
- batchFetchFn?: (payloads: ItemPayload[], signal: AbortSignal, batchKey: string) => Promise<Map<ItemPayload, ItemState | Error>>; /** Optional function to group batch fetches by key. Return false to fall back to individual fetchFn */
222
+ storeManager: StoreManager; /** Fetches one item by payload. */
223
+ fetchFn: (params: ItemPayload, signal: AbortSignal) => Promise<MaybeTSDFResult<ItemState>>; /** Optional batch fetch function for fetching multiple items at once */
224
+ batchFetchFn?: (payloads: ItemPayload[], signal: AbortSignal, batchKey: string) => Promise<MaybeTSDFResult<Map<ItemPayload, MaybeTSDFResult<ItemState> | Error>>>; /** Optional function to group batch fetches by key. When omitted, all batched items share one default batch key. Return false to fall back to individual fetchFn */
1656
225
  getItemsBatchKey?: (payload: ItemPayload) => string | false; /** Max items per batch - triggers immediate fetch when reached */
1657
226
  maxBatchSize?: number; /** Maximum number of cached items kept in memory. Defaults to 5,000. Inactive items are evicted in LRU order, while mounted hook items stay protected. */
1658
227
  maxItems?: number; /** Called when cache-limit eviction removes items from in-memory state. */
1659
- onStateCleanup?: (cleanup: CollectionStateCleanup<ItemPayload>) => void;
228
+ onStateCleanup?: (cleanup: CollectionStateCleanup<ItemPayload>) => void; /** Converts an item payload to the stable cache key used by this store. */
1660
229
  getCollectionItemKey?: (params: ItemPayload) => ValidPayload | unknown[]; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
1661
230
  lowPriorityThrottleMs?: number; /** Overrides the manager's default coalescing window for this store. */
1662
- baseCoalescingWindowMs?: number;
1663
- mediumPriorityDelayMs?: number;
231
+ baseCoalescingWindowMs?: number; /** Delay applied to medium-priority requests before they enter the scheduler. */
232
+ mediumPriorityDelayMs?: number; /** Computes a per-fetch throttle for real-time updates using recent fetch cost and focus state. */
1664
233
  dynamicRealtimeThrottleMs?: (params: {
1665
234
  lastFetchDuration: number;
1666
235
  windowIsNotFocused: boolean;
1667
- }) => number;
236
+ }) => number; /** Store-level focus revalidation policy. Overrides the manager default. */
1668
237
  revalidateOnWindowFocus?: boolean | (() => boolean);
1669
- /** Reconnect-specific cooldown. The first reconnect revalidates immediately;
238
+ /** Reconnect-specific cooldown. Defaults to 2,000ms. The first reconnect revalidates immediately;
1670
239
  * additional reconnects within the cooldown are coalesced into one trailing
1671
240
  * revalidation. Set to `0` to disable this cooldown. */
1672
- transportReconnectCooldownMs?: number;
1673
- onInvalidate?: OnCollectionItemInvalidate<ItemState, ItemPayload>;
241
+ transportReconnectCooldownMs?: number; /** Called when an already-loaded item is invalidated. */
242
+ onInvalidate?: OnCollectionItemInvalidate<ItemState, ItemPayload>; /** Observes request scheduler lifecycle events for this store. */
1674
243
  onSchedulerEvent?: (event: RequestSchedulerEvents, data?: RequestSchedulerEventData) => void;
1675
244
  /**
1676
245
  * Store-specific mutation error handler.
@@ -1678,7 +247,7 @@ type CollectionStoreOptions<ItemState extends ValidStoreState, ItemPayload exten
1678
247
  * Overrides the manager fallback. Use `null` to disable inherited mutation
1679
248
  * error handling for this store.
1680
249
  */
1681
- onMutationError?: ((error: unknown, options: StoreMutationErrorOptions) => void) | null;
250
+ onMutationError?: ((error: unknown, options: StoreMutationErrorOptions) => void) | null; /** Treats refetches as real-time driven, disabling stale mount refetches by default. Defaults to `false`. */
1682
251
  usesRealTimeUpdates?: boolean;
1683
252
  /** Opt-in persistent storage configuration. When provided, cached items are loaded
1684
253
  * from storage on first read and saved back on successful fetches.
@@ -1686,9 +255,10 @@ type CollectionStoreOptions<ItemState extends ValidStoreState, ItemPayload exten
1686
255
  * persisted namespace always reuses this store's `id`. */
1687
256
  persistentStorage?: CollectionPersistentStorageConfig<ItemState, ItemPayload, StorageState, TOfflineOperations>;
1688
257
  };
258
+ /** Event payloads emitted by `CollectionStore.events`. */
1689
259
  type CollectionStoreEvents = {
1690
- invalidateData: {
1691
- priority: FetchType;
260
+ /** Emitted whenever one or more cached items are invalidated. */invalidateData: {
261
+ /** Fetch priority requested by the invalidation. */priority: FetchType; /** Store key for the invalidated item. */
1692
262
  itemKey: string;
1693
263
  };
1694
264
  };
@@ -1705,7 +275,7 @@ type CollectionMutationArgsBase<T, ItemPayload extends ValidPayload> = {
1705
275
  */
1706
276
  optimisticUpdate?: (payload: CollectionMutationPayloadToUse<ItemPayload>) => void | boolean; /** Performs the server mutation for the affected item payloads. */
1707
277
  mutation: (payload: CollectionMutationPayloadToUse<ItemPayload>) => Promise<T>; /** Called after a successful online mutation. */
1708
- onSuccess?: (response: Awaited<T>, payload: CollectionMutationPayloadToUse<ItemPayload>) => void; /** Invalidates affected items after a successful online mutation. */
278
+ onSuccess?: (response: UnwrapTSDFResult<Awaited<T>>, payload: CollectionMutationPayloadToUse<ItemPayload>) => void; /** Invalidates affected items after a successful online mutation. */
1709
279
  revalidateOnSuccess?: boolean;
1710
280
  /**
1711
281
  * Passes `{ silentErrors: true }` to `onMutationError`.
@@ -1725,25 +295,55 @@ type CollectionOnlineMutationArgs<T, ItemPayload extends ValidPayload> = Collect
1725
295
  upload?: undefined;
1726
296
  };
1727
297
  type CollectionOfflineMutationArgs<T, ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload>> = CollectionMutationArgsBase<T, ItemPayload> & {
1728
- offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>;
298
+ /**
299
+ * Queues this mutation through the store's registered offline operation when
300
+ * the session is offline or the direct request fails with an offline outage.
301
+ */
302
+ offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>; /** Files to attach if this mutation is queued for offline replay. */
1729
303
  upload?: OfflineMutationUploadsInput;
1730
304
  };
1731
305
  type CollectionPerformMutation<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload>> = {
1732
- <T>(payload: CollectionMutationTarget<ItemPayload>, args: CollectionOnlineMutationArgs<T, ItemPayload>): Promise<Result<Awaited<T>, StoreMutationError | MutationSkipped>>;
1733
- <T>(payload: CollectionMutationTarget<ItemPayload>, args: CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>): Promise<Result<OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
1734
- <T>(payload: null, args: Omit<CollectionOnlineMutationArgs<T, ItemPayload>, 'optimisticUpdate'>): Promise<Result<Awaited<T>, StoreMutationError | MutationSkipped>>;
1735
- <T>(payload: null, args: Omit<CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>, 'optimisticUpdate'>): Promise<Result<OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
1736
- <T>(payload: CollectionMutationPayload<ItemPayload>, args: CollectionOnlineMutationArgs<T, ItemPayload> | CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>): Promise<Result<Awaited<T> | OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
306
+ /**
307
+ * Runs a collection mutation for one or more existing item payloads.
308
+ *
309
+ * Returns the direct server result when offline replay is not configured for
310
+ * this call.
311
+ */
312
+ <T>(payload: CollectionMutationTarget<ItemPayload>, args: CollectionOnlineMutationArgs<T, ItemPayload>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
313
+ /**
314
+ * Runs a collection mutation for one or more existing item payloads, with
315
+ * durable offline queueing as a fallback.
316
+ *
317
+ * When the mutation is queued, the result is `{ kind: 'queued' }` instead of
318
+ * the server payload.
319
+ */
320
+ <T>(payload: CollectionMutationTarget<ItemPayload>, args: CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
321
+ /**
322
+ * Runs a collection mutation with no current item target.
323
+ *
324
+ * Use this for create mutations that do not have a pre-generated item payload
325
+ * yet. Optimistic updates are not available without a target payload.
326
+ */
327
+ <T>(payload: null, args: Omit<CollectionOnlineMutationArgs<T, ItemPayload>, 'optimisticUpdate'>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
328
+ /**
329
+ * Runs an offline-capable collection mutation with no current item target.
330
+ *
331
+ * Use this for create mutations that do not have a pre-generated item payload
332
+ * yet. When the mutation is queued, the result is `{ kind: 'queued' }`.
333
+ */
334
+ <T>(payload: null, args: Omit<CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>, 'optimisticUpdate'>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
335
+ <T>(payload: CollectionMutationPayload<ItemPayload>, args: CollectionOnlineMutationArgs<T, ItemPayload> | CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>): Promise<Result<UnwrapTSDFResult<Awaited<T>> | OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
1737
336
  };
337
+ /** Public API returned by `createCollectionStore(...)`. */
1738
338
  type CollectionStore<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null> = {
1739
- store: Store<TSFDCollectionState<ItemState, ItemPayload>>;
1740
- events: Emitter<CollectionStoreEvents>;
1741
- storeEvents: Emitter<CollectionStoreStoreEvents<ItemPayload>>;
1742
- readonly invalidationWasTriggered: Set<string>;
339
+ /** Underlying t-state store containing raw cached items. */store: Store<TSFDCollectionState<ItemState, ItemPayload>>; /** Invalidation event emitter used by hooks and integrations. */
340
+ events: Emitter<CollectionStoreEvents>; /** Mutation lifecycle event emitter for observers and tests. */
341
+ storeEvents: Emitter<CollectionStoreStoreEvents<ItemPayload>>; /** Item keys that have been explicitly invalidated and are awaiting refresh. */
342
+ readonly invalidationWasTriggered: Set<string>; /** Schedules a fetch for one item or a batch of item payloads. */
1743
343
  scheduleFetch: {
1744
344
  (fetchType: FetchType, payload: ItemPayload, options?: ScheduleFetchOptions): ScheduleFetchResults;
1745
345
  (fetchType: FetchType, payload: ItemPayload[], options?: ScheduleFetchOptions): ScheduleFetchResults[];
1746
- };
346
+ }; /** Waits for an item fetch to settle and returns data or a fetch error. */
1747
347
  awaitFetch: (params: ItemPayload, options?: {
1748
348
  timeoutMs?: number;
1749
349
  }) => Promise<{
@@ -1752,25 +352,25 @@ type CollectionStore<ItemState extends ValidStoreState, ItemPayload extends Vali
1752
352
  } | {
1753
353
  data: null;
1754
354
  error: StoreFetchError;
1755
- }>;
355
+ }>; /** Returns cached item data when usable, otherwise fetches it first. */
1756
356
  getItemFromStateOrFetch: (params: ItemPayload, options?: {
1757
- ignoreStaleState?: boolean;
357
+ /** When `true`, stale cached data is ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean;
1758
358
  timeoutMs?: number;
1759
- }) => Promise<Result<ItemState, StoreFetchError>>;
1760
- useMultipleItems: <Selected = ItemState | null, QueryMetadata extends undefined | Record<string, unknown> = undefined>(items: CollectionUseMultipleItemsQuery<ItemPayload, QueryMetadata>[], options?: UseMultipleItemsOptions$1<ItemState, Selected>) => readonly TSFDUseCollectionItemReturn<Selected, ItemPayload, QueryMetadata>[];
1761
- useItem: <Selected = ItemState | null>(payload: ItemPayload | undefined | false | null, options?: UseItemOptions$1<ItemState, Selected>) => TSFDUseCollectionItemReturn<Selected, ItemPayload>;
359
+ }) => Promise<Result<ItemState, StoreFetchError>>; /** React hook for subscribing to many collection items at once. */
360
+ useMultipleItems: <Selected = ItemState | null, QueryMetadata extends undefined | Record<string, unknown> = undefined>(items: CollectionUseMultipleItemsQuery<ItemPayload, QueryMetadata>[], options?: UseMultipleItemsOptions$1<ItemState, Selected>) => readonly TSFDUseCollectionItemReturn<Selected, ItemPayload, QueryMetadata>[]; /** React hook for subscribing to one collection item. */
361
+ useItem: <Selected = ItemState | null>(payload: ItemPayload | undefined | false | null, options?: UseItemOptions$1<ItemState, Selected>) => TSFDUseCollectionItemReturn<Selected, ItemPayload>; /** React hook that tracks whether a nested list item is still loading. */
1762
362
  useListItemIsLoading: (payload: ItemPayload, args: {
1763
363
  /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts the sub-item from the collection item data. */
1764
364
  selector: (data: ItemState | null) => unknown; /** Called if the sub-item is still missing and no refetch is in progress. */
1765
365
  loadItemFallback?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
1766
366
  ensureIsLoaded?: boolean;
1767
- }) => boolean;
367
+ }) => boolean; /** React hook that tracks whether a nested list item has been deleted. */
1768
368
  useListItemIsDeleted: (payload: ItemPayload, args: {
1769
369
  /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts the sub-item from the collection item data. */
1770
370
  selector: (data: ItemState | null) => unknown; /** Called once when deletion is detected. */
1771
371
  onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
1772
372
  ensureIsLoaded?: boolean;
1773
- }) => boolean;
373
+ }) => boolean; /** React hook for selecting one nested list item plus loading/deleted flags. */
1774
374
  useListItem: <Selected>(payload: ItemPayload, args: {
1775
375
  /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts and maps the sub-item from the collection item data. */
1776
376
  selector: (data: ItemState | null) => Selected; /** Called if the sub-item is still missing and no refetch is in progress. */
@@ -1781,74 +381,61 @@ type CollectionStore<ItemState extends ValidStoreState, ItemPayload extends Vali
1781
381
  isLoading: boolean;
1782
382
  isDeleted: boolean;
1783
383
  data: Selected;
1784
- };
1785
- reset: () => void;
1786
- dispose: () => void;
1787
- preloadItemFromStorage: (params: ItemPayload | ItemPayload[]) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>;
1788
- getItemKey: (params: ItemPayload) => string;
384
+ }; /** Clears in-memory state and cancels store-local runtime state. */
385
+ reset: () => void; /** Unregisters listeners and releases resources owned by this store. */
386
+ dispose: () => void; /** Loads item payloads from persistent storage into memory when available. */
387
+ preloadItemFromStorage: (params: ItemPayload | ItemPayload[]) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>; /** Returns the stable cache key for an item payload. */
388
+ getItemKey: (params: ItemPayload) => string; /** Reads one or many cached items directly from store state. */
1789
389
  getItemState: {
1790
390
  (params: ItemPayload): TSFDCollectionItem<ItemState, ItemPayload> | undefined | null;
1791
391
  (params: ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>): TSFDCollectionItem<ItemState, ItemPayload>[];
1792
- };
1793
- getOfflineEntities: () => GlobalOfflineEntity[];
1794
- useOfflineEntities: () => readonly GlobalOfflineEntity[];
1795
- useOfflineResolutions: () => readonly OfflineResolutionRecord[];
1796
- getOfflineResolutions: () => OfflineResolutionRecord[];
1797
- parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedCollectionOfflineOperations<TOfflineOperations>>;
1798
- resolveOfflineResolution: <TName extends keyof ResolvedCollectionOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedCollectionOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void;
1799
- startMutation: (fetchParams: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>) => () => void;
1800
- invalidateItem: (itemPayload: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>, priority?: FetchType) => void;
392
+ }; /** Returns offline sync metadata for this store's tracked entities. */
393
+ getOfflineEntities: () => GlobalOfflineEntity[]; /** React hook subscribing to this store's offline entity metadata. */
394
+ useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to manual offline resolutions for this store. */
395
+ useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns manual offline resolutions for this store. */
396
+ getOfflineResolutions: () => OfflineResolutionRecord[]; /** Parses a stored offline conflict into the operation-specific conflict shape. */
397
+ parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedCollectionOfflineOperations<TOfflineOperations>>; /** Applies a retry/discard/requeue/commit action to a pending offline resolution. */
398
+ resolveOfflineResolution: <TName extends keyof ResolvedCollectionOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedCollectionOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void; /** Marks one or more items as mutating and returns a function that ends the mutation. */
399
+ startMutation: (fetchParams: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>) => () => void; /** Marks cached items stale and schedules refetches for active subscriptions. Defaults to `highPriority`. */
400
+ invalidateItem: (itemPayload: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>, /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
401
+
402
+ priority?: FetchType) => void; /** Applies an immutable update to one or more cached collection items. */
1801
403
  updateItemState: (fetchParams: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>, produceNewData: (draftData: ItemState, collectionItem: TSFDCollectionItem<ItemState, ItemPayload>) => void | ItemState, options?: {
1802
404
  ifNothingWasUpdated?: () => void;
1803
- }) => boolean;
1804
- addItemToState: (fetchParams: ItemPayload, data: ItemState) => void;
405
+ }) => boolean; /** Adds or replaces one cached item directly in state. */
406
+ addItemToState: (fetchParams: ItemPayload, data: ItemState) => void; /** Deletes one or more cached items directly from state. */
1805
407
  deleteItemState: (fetchParams: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>) => void;
1806
- performMutation: CollectionPerformMutation<ItemState, ItemPayload, TOfflineOperations>;
408
+ /**
409
+ * Runs the full mutation lifecycle: optional optimistic update, async
410
+ * mutation, rollback/error handling, revalidation, and offline queue fallback.
411
+ */
412
+ performMutation: CollectionPerformMutation<ItemState, ItemPayload, TOfflineOperations>; /** Notifies the store that a shared transport reconnected and should revalidate active data. */
1807
413
  onTransportReconnect: () => void;
1808
414
  };
1809
- declare function createCollectionStore<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null, StorageState = unknown>({
1810
- id,
1811
- storeManager,
1812
- fetchFn,
1813
- batchFetchFn,
1814
- getItemsBatchKey,
1815
- maxBatchSize,
1816
- maxItems,
1817
- onStateCleanup,
1818
- lowPriorityThrottleMs: storeLowPriorityThrottleMs,
1819
- baseCoalescingWindowMs: storeBaseCoalescingWindowMs,
1820
- mediumPriorityDelayMs,
1821
- dynamicRealtimeThrottleMs,
1822
- revalidateOnWindowFocus,
1823
- transportReconnectCooldownMs,
1824
- getCollectionItemKey: filterCollectionItemObjKey,
1825
- onInvalidate,
1826
- onSchedulerEvent,
1827
- onMutationError,
1828
- usesRealTimeUpdates,
1829
- persistentStorage: persistentStorageConfig,
1830
- '~test': testOptions
1831
- }: CollectionStoreOptions<ItemState, ItemPayload, TOfflineOperations, StorageState>): CollectionStore<ItemState, ItemPayload, TOfflineOperations>;
415
+ declare function createCollectionStore<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null, StorageState = unknown>(storeOptions: CollectionStoreOptions<ItemState, ItemPayload, TOfflineOperations, StorageState>): CollectionStore<ItemState, ItemPayload, TOfflineOperations>;
1832
416
  //#endregion
1833
417
  //#region src/documentStore.d.ts
418
+ /** Lifecycle status for a document store. */
1834
419
  type DocumentStatus = 'idle' | TSDFStatus;
420
+ /** Value returned by `DocumentStore.useDocument(...)`. */
1835
421
  type TSDFUseDocumentReturn<Selected> = {
1836
- status: DocumentStatus;
1837
- data: Selected;
1838
- error: StoreError | null;
422
+ /** Hook-visible document status. */status: DocumentStatus; /** Selected document data. Defaults to the full document or `null`. */
423
+ data: Selected; /** Last document fetch error, if any. */
424
+ error: StoreError | null; /** Convenience flag for `loading` or `refetching` states. */
1839
425
  isLoading: boolean; /** Whether this result has local offline changes that still need to sync to the server. */
1840
426
  pendingSync: boolean;
1841
427
  };
1842
428
  type DocumentStoreState<State extends ValidStoreState> = {
1843
- data: State | null;
1844
- error: StoreError | null;
1845
- status: DocumentStatus;
429
+ /** Latest loaded document data, or `null` before the document is available. */data: State | null; /** Last fetch error for this document, when the latest fetch failed. */
430
+ error: StoreError | null; /** Current fetch lifecycle status for the document. */
431
+ status: DocumentStatus; /** Pending automatic refetch priority for stale data mounted by hooks. */
1846
432
  refetchOnMount: false | FetchType;
1847
433
  };
1848
434
  type DocumentStoreEvents = {
1849
435
  invalidateData: FetchType;
1850
436
  };
1851
437
  type OnDocumentInvalidate = (priority: FetchType) => void;
438
+ /** Events emitted by document mutation lifecycle helpers. */
1852
439
  type DocumentStoreStoreEvents = {
1853
440
  /** Emitted when a mutation begins executing */mutationStart: {
1854
441
  mutationId: number;
@@ -1858,22 +445,6 @@ type DocumentStoreStoreEvents = {
1858
445
  status: 'success' | 'error' | 'skipped';
1859
446
  };
1860
447
  };
1861
- type DocumentBrowserTabsMessage<State extends ValidStoreState> = (BrowserTabsMessageMeta & BrowserTabsTabStatusMessage) | (BrowserTabsMessageMeta & {
1862
- kind: 'document-snapshot';
1863
- consistency: SnapshotConsistency;
1864
- data: State | null;
1865
- }) | (BrowserTabsMessageMeta & {
1866
- kind: 'fetch-start';
1867
- targetKey: 'document';
1868
- requestIds: string[];
1869
- startedAt: number;
1870
- }) | (BrowserTabsMessageMeta & {
1871
- kind: 'fetch-success';
1872
- targetKey: 'document';
1873
- requestIds: string[];
1874
- startedAt: number;
1875
- duration: number;
1876
- });
1877
448
  type InternalDocumentOfflineOperations<State extends ValidStoreState> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> & ([State] extends [never] ? never : unknown);
1878
449
  type DocumentOfflineOperationsConfig<State extends ValidStoreState> = InternalDocumentOfflineOperations<State> | null;
1879
450
  type DocumentStoreOptions<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown> = {
@@ -1883,19 +454,19 @@ type DocumentStoreOptions<State extends ValidStoreState, TOfflineOperations exte
1883
454
  */
1884
455
  id: string; /** Shared global store manager providing session scoping and error normalization. */
1885
456
  storeManager: StoreManager;
1886
- fetchFn: (signal: AbortSignal) => Promise<State>; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
457
+ fetchFn: (signal: AbortSignal) => Promise<MaybeTSDFResult<State>>; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
1887
458
  lowPriorityThrottleMs?: number; /** Overrides the manager's default coalescing window for this store. */
1888
- baseCoalescingWindowMs?: number;
459
+ baseCoalescingWindowMs?: number; /** Computes a per-fetch throttle for real-time updates using recent fetch cost and focus state. */
1889
460
  dynamicRealtimeThrottleMs?: (params: {
1890
461
  lastFetchDuration: number;
1891
462
  windowIsNotFocused: boolean;
1892
- }) => number;
463
+ }) => number; /** Store-level focus revalidation policy. Overrides the manager default. */
1893
464
  revalidateOnWindowFocus?: boolean | (() => boolean);
1894
- /** Reconnect-specific cooldown. The first reconnect revalidates immediately;
465
+ /** Reconnect-specific cooldown. Defaults to 2,000ms. The first reconnect revalidates immediately;
1895
466
  * additional reconnects within the cooldown are coalesced into one trailing
1896
467
  * revalidation. Set to `0` to disable this cooldown. */
1897
- transportReconnectCooldownMs?: number;
1898
- mediumPriorityDelayMs?: number;
468
+ transportReconnectCooldownMs?: number; /** Delay applied to medium-priority requests before they enter the scheduler. */
469
+ mediumPriorityDelayMs?: number; /** Observes request scheduler lifecycle events for this store. */
1899
470
  onSchedulerEvent?: (event: RequestSchedulerEvents, data?: RequestSchedulerEventData) => void;
1900
471
  /**
1901
472
  * Store-specific mutation error handler.
@@ -1904,6 +475,9 @@ type DocumentStoreOptions<State extends ValidStoreState, TOfflineOperations exte
1904
475
  * error handling for this store.
1905
476
  */
1906
477
  onMutationError?: ((error: unknown, options: StoreMutationErrorOptions) => void) | null;
478
+ /** Indicates that fresh data arrives via a real-time channel. Defaults to `false`. The store
479
+ * skips the mount-time stale refetch since real-time pushes already cover
480
+ * revalidation. */
1907
481
  usesRealTimeUpdates?: boolean;
1908
482
  /** Opt-in persistent storage configuration. When provided, cached data is loaded
1909
483
  * from storage on first read and saved back on successful fetches.
@@ -1945,20 +519,36 @@ type DocumentOnlineMutationArgs<State extends ValidStoreState, T> = DocumentMuta
1945
519
  upload?: undefined;
1946
520
  };
1947
521
  type DocumentOfflineMutationArgs<State extends ValidStoreState, T, TOfflineOperations extends DocumentOfflineOperationsConfig<State>> = DocumentMutationArgsBase<State, T> & {
1948
- offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>;
522
+ /**
523
+ * Queues this mutation through the store's registered offline operation when
524
+ * the session is offline or the direct request fails with an offline outage.
525
+ */
526
+ offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>; /** Files to attach if this mutation is queued for offline replay. */
1949
527
  upload?: OfflineMutationUploadsInput;
1950
528
  };
1951
529
  type DocumentPerformMutation<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State>> = {
1952
- <T>(args: DocumentOnlineMutationArgs<State, T>): Promise<Result<Awaited<T>, StoreMutationError | MutationSkipped>>;
1953
- <T>(args: DocumentOfflineMutationArgs<State, T, TOfflineOperations>): Promise<Result<OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
1954
- <T>(args: DocumentOnlineMutationArgs<State, T> | DocumentOfflineMutationArgs<State, T, TOfflineOperations>): Promise<Result<Awaited<T> | OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
530
+ /**
531
+ * Runs a document mutation with optional optimistic updates and revalidation.
532
+ *
533
+ * Returns the direct server result when offline replay is not configured for
534
+ * this call.
535
+ */
536
+ <T>(args: DocumentOnlineMutationArgs<State, T>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
537
+ /**
538
+ * Runs a document mutation that may fall back to durable offline queueing.
539
+ *
540
+ * When the mutation is queued, the result is `{ kind: 'queued' }` instead of
541
+ * the server payload.
542
+ */
543
+ <T>(args: DocumentOfflineMutationArgs<State, T, TOfflineOperations>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
544
+ <T>(args: DocumentOnlineMutationArgs<State, T> | DocumentOfflineMutationArgs<State, T, TOfflineOperations>): Promise<Result<UnwrapTSDFResult<Awaited<T>> | OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
1955
545
  };
1956
546
  type DocumentStore<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null> = {
1957
- store: Store<DocumentStoreState<State>>;
1958
- events: Emitter<DocumentStoreEvents>;
1959
- storeEvents: Emitter<DocumentStoreStoreEvents>;
1960
- readonly invalidationWasTriggered: boolean;
1961
- scheduleFetch: (fetchType: FetchType, options?: ScheduleFetchOptions) => ScheduleFetchResults;
547
+ /** Underlying t-state store containing the raw document cache state. */store: Store<DocumentStoreState<State>>; /** Invalidation event emitter used by hooks and integrations. */
548
+ events: Emitter<DocumentStoreEvents>; /** Mutation lifecycle event emitter for observers and tests. */
549
+ storeEvents: Emitter<DocumentStoreStoreEvents>; /** Whether the document has been explicitly invalidated and is awaiting refresh. */
550
+ readonly invalidationWasTriggered: boolean; /** Schedules a document fetch with the requested priority. */
551
+ scheduleFetch: (fetchType: FetchType, options?: ScheduleFetchOptions) => ScheduleFetchResults; /** Waits for a document fetch to settle and returns data or a fetch error. */
1962
552
  awaitFetch: (options?: {
1963
553
  timeoutMs?: number;
1964
554
  }) => Promise<{
@@ -1967,22 +557,24 @@ type DocumentStore<State extends ValidStoreState, TOfflineOperations extends Doc
1967
557
  } | {
1968
558
  data: null;
1969
559
  error: StoreFetchError;
1970
- }>;
560
+ }>; /** Returns cached document data when usable, otherwise fetches it first. */
1971
561
  getDataFromStateOrFetch: (options?: {
1972
- ignoreStaleState?: boolean;
562
+ /** When `true`, stale cached data is ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean;
1973
563
  timeoutMs?: number;
1974
- }) => Promise<Result<State, StoreFetchError>>;
1975
- preloadPersistentStorage: () => Promise<void>;
1976
- invalidateData: (priority?: FetchType) => void;
1977
- updateState: DocumentUpdateState<State>;
1978
- reset: () => void;
1979
- dispose: () => void;
1980
- startMutation: () => () => boolean;
1981
- getOfflineEntities: () => GlobalOfflineEntity[];
1982
- useOfflineEntities: () => readonly GlobalOfflineEntity[];
1983
- useOfflineResolutions: () => readonly OfflineResolutionRecord[];
1984
- getOfflineResolutions: () => OfflineResolutionRecord[];
1985
- parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedDocumentOfflineOperations<TOfflineOperations>>;
564
+ }) => Promise<Result<State, StoreFetchError>>; /** Loads cached document data from persistent storage when available. */
565
+ preloadPersistentStorage: () => Promise<void>; /** Marks the document stale and schedules refetches for active subscriptions. Defaults to `highPriority`. */
566
+ invalidateData: (/** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
567
+
568
+ priority?: FetchType) => void; /** Applies an immutable update to the cached document data. */
569
+ updateState: DocumentUpdateState<State>; /** Clears in-memory state and cancels store-local runtime state. */
570
+ reset: () => void; /** Unregisters listeners and releases resources owned by this store. */
571
+ dispose: () => void; /** Marks the document as mutating and returns a function that ends the mutation. */
572
+ startMutation: () => () => boolean; /** Returns offline sync metadata for this store's tracked entity. */
573
+ getOfflineEntities: () => GlobalOfflineEntity[]; /** React hook subscribing to this store's offline entity metadata. */
574
+ useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to manual offline resolutions for this store. */
575
+ useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns manual offline resolutions for this store. */
576
+ getOfflineResolutions: () => OfflineResolutionRecord[]; /** Parses a stored offline conflict into the operation-specific conflict shape. */
577
+ parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedDocumentOfflineOperations<TOfflineOperations>>; /** Applies a retry/discard/requeue/commit action to a pending offline resolution. */
1986
578
  resolveOfflineResolution: <TName extends keyof ResolvedDocumentOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedDocumentOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void;
1987
579
  useDocument: <Selected = State | null>(args?: {
1988
580
  /** Maps the document data before it is returned from the hook. */selector?: (data: State | null) => Selected; /** Disables this hook subscription and prevents automatic fetches. */
@@ -2001,19 +593,19 @@ type DocumentStore<State extends ValidStoreState, TOfflineOperations extends Doc
2001
593
  */
2002
594
  ensureIsLoaded?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
2003
595
  returnRefetchingStatus?: boolean;
2004
- }) => TSDFUseDocumentReturn<Selected>;
596
+ }) => TSDFUseDocumentReturn<Selected>; /** React hook that tracks whether a nested list item is still loading. */
2005
597
  useListItemIsLoading: (args: {
2006
598
  /** Unique identifier of the item within the document. */itemId: string; /** Extracts the item from the document data. */
2007
599
  selector: (data: State | null) => unknown; /** Called if the item is still missing and no refetch is in progress. */
2008
600
  loadItemFallback?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
2009
601
  ensureIsLoaded?: boolean;
2010
- }) => boolean;
602
+ }) => boolean; /** React hook that tracks whether a nested list item has been deleted. */
2011
603
  useListItemIsDeleted: (args: {
2012
604
  /** Unique identifier of the item within the document. */itemId: string; /** Extracts the item from the document data. */
2013
605
  selector: (data: State | null) => unknown; /** Called once when deletion is detected. */
2014
606
  onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
2015
607
  ensureIsLoaded?: boolean;
2016
- }) => boolean;
608
+ }) => boolean; /** React hook for selecting one nested list item plus loading/deleted flags. */
2017
609
  useListItem: <Selected>(args: {
2018
610
  /** Unique identifier of the item within the document. */itemId: string; /** Extracts and maps the item from the document data. */
2019
611
  selector: (data: State | null) => Selected; /** Called if the item is still missing and no refetch is in progress. */
@@ -2025,60 +617,42 @@ type DocumentStore<State extends ValidStoreState, TOfflineOperations extends Doc
2025
617
  isDeleted: boolean;
2026
618
  data: Selected;
2027
619
  };
2028
- performMutation: DocumentPerformMutation<State, TOfflineOperations>;
620
+ /**
621
+ * Runs the full mutation lifecycle: optional optimistic update, async
622
+ * mutation, rollback/error handling, revalidation, and offline queue fallback.
623
+ */
624
+ performMutation: DocumentPerformMutation<State, TOfflineOperations>; /** Notifies the store that a shared transport reconnected and should revalidate active data. */
2029
625
  onTransportReconnect: () => void;
2030
626
  };
2031
- declare function createDocumentStore<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown>({
2032
- id,
2033
- storeManager,
2034
- fetchFn,
2035
- lowPriorityThrottleMs: storeLowPriorityThrottleMs,
2036
- baseCoalescingWindowMs: storeBaseCoalescingWindowMs,
2037
- dynamicRealtimeThrottleMs,
2038
- revalidateOnWindowFocus,
2039
- transportReconnectCooldownMs,
2040
- mediumPriorityDelayMs,
2041
- onSchedulerEvent,
2042
- onMutationError,
2043
- usesRealTimeUpdates,
2044
- persistentStorage: persistentStorageConfig,
2045
- '~test': testOptions
2046
- }: DocumentStoreOptions<State, TOfflineOperations, StorageState>): DocumentStore<State, TOfflineOperations>;
2047
- //#endregion
2048
- //#region src/internal/testTimelineTypes.d.ts
2049
- type TestTimelineSessionKey = string | false;
2050
- type TestSessionKeyChangedEvent = {
2051
- previousSessionKey: TestTimelineSessionKey;
2052
- sessionKey: TestTimelineSessionKey;
2053
- };
2054
- type TestOfflineTimelineEvent = {
2055
- operation: string;
2056
- phase: 'queued' | 'replay-started' | 'replay-finished' | 'replay-failed';
2057
- };
627
+ declare function createDocumentStore<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown>(storeOptions: DocumentStoreOptions<State, TOfflineOperations, StorageState>): DocumentStore<State, TOfflineOperations>;
2058
628
  //#endregion
2059
629
  //#region src/listQueryStore/types.d.ts
630
+ /** Lifecycle status for a list query or list item query. */
2060
631
  type QueryStatus = TSDFStatus | 'loadingMore';
632
+ /** Raw cached state for one list query. */
2061
633
  type TSFDListQuery<QueryPayload extends ValidPayload> = {
2062
- error: StoreError | null;
2063
- status: QueryStatus;
2064
- payload: QueryPayload;
2065
- hasMore: boolean;
2066
- wasLoaded: boolean;
2067
- refetchOnMount: false | FetchType;
634
+ /** Last fetch error for this query, when the latest fetch failed. */error: StoreError | null; /** Current fetch lifecycle status for this query. */
635
+ status: QueryStatus; /** Payload used to identify and fetch this query. */
636
+ payload: QueryPayload; /** Whether another page is available. */
637
+ hasMore: boolean; /** Whether this query has ever loaded successfully. */
638
+ wasLoaded: boolean; /** Pending automatic refetch priority for stale data mounted by hooks. */
639
+ refetchOnMount: false | FetchType; /** Ordered item keys included in the cached query page. */
2068
640
  items: string[];
2069
641
  };
642
+ /** Raw cached state for one item query in a list-query store. */
2070
643
  type TSDFItemQuery<ItemPayload extends ValidPayload> = {
2071
- error: StoreError | null;
2072
- status: Exclude<QueryStatus, 'loadingMore'>;
2073
- wasLoaded: boolean;
2074
- refetchOnMount: false | FetchType;
644
+ /** Last item fetch error, if any. */error: StoreError | null; /** Current fetch lifecycle status for this item. */
645
+ status: Exclude<QueryStatus, 'loadingMore'>; /** Whether this item has ever loaded successfully. */
646
+ wasLoaded: boolean; /** Pending automatic refetch priority for stale data mounted by hooks. */
647
+ refetchOnMount: false | FetchType; /** Payload used to identify and fetch this item. */
2075
648
  payload: ItemPayload;
2076
649
  };
650
+ /** Raw t-state shape used by a list-query store. */
2077
651
  type TSFDListQueryState<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2078
- items: Record<string, ItemState | null>;
2079
- queries: Record<string, TSFDListQuery<QueryPayload>>;
2080
- itemQueries: Record<string, TSDFItemQuery<ItemPayload> | null>;
2081
- itemLoadedFields: Record<string, string[]>;
652
+ /** Item data records keyed by item store key. */items: Record<string, ItemState | null>; /** List query records keyed by query store key. */
653
+ queries: Record<string, TSFDListQuery<QueryPayload>>; /** Item query records keyed by item store key. */
654
+ itemQueries: Record<string, TSDFItemQuery<ItemPayload> | null>; /** Loaded partial-resource fields for each item key. */
655
+ itemLoadedFields: Record<string, string[]>; /** Pending field invalidations for each item key. */
2082
656
  itemFieldInvalidationFields: Record<string, string[]>;
2083
657
  };
2084
658
  /**
@@ -2088,55 +662,50 @@ type TSFDListQueryState<ItemState extends ValidStoreState, QueryPayload extends
2088
662
  * complete item.
2089
663
  */
2090
664
  type FieldsInput = string[] | '*';
665
+ /** Value returned by `ListQueryStore.useListQuery(...)` and `useMultipleListQueries(...)`. */
2091
666
  type TSFDUseListQueryReturn<Selected, QueryPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined, HasPartialResources extends boolean = false> = {
2092
- items: Selected[];
2093
- status: QueryStatus | 'idle';
2094
- payload: QueryPayload | undefined;
667
+ /** Selected items included in the current query result. */items: Selected[]; /** Hook-visible query status, including `idle` before a query runs. */
668
+ status: QueryStatus | 'idle'; /** Query payload for this result, unless omitted or unavailable. */
669
+ payload: QueryPayload | undefined; /** Requested partial-resource fields for this query result. */
2095
670
  fields: HasPartialResources extends true ? FieldsInput : FieldsInput | undefined; /** Requested partial-resource fields that are still pending. */
2096
- loadingFields?: string[];
2097
- error: StoreError | null;
2098
- queryKey: string;
2099
- hasMore: boolean;
2100
- isDerived: boolean;
2101
- isLoading: boolean;
671
+ loadingFields?: string[]; /** Last query fetch error, if any. */
672
+ error: StoreError | null; /** Stable store key for the current query payload. */
673
+ queryKey: string; /** Whether another page is available. */
674
+ hasMore: boolean; /** Whether this result was derived from local items instead of fetched directly. */
675
+ isDerived: boolean; /** Convenience flag for `loading` or `refetching` states. */
676
+ isLoading: boolean; /** Whether a `loadMore(...)` request is currently active. */
2102
677
  isLoadingMore: boolean; /** Whether this result has local offline changes that still need to sync to the server. */
2103
- pendingSync: boolean;
678
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
2104
679
  queryMetadata: QueryMetadata;
2105
680
  };
681
+ /** Value returned by `ListQueryStore.useItem(...)` and `useMultipleItems(...)`. */
2106
682
  type TSFDUseListItemReturn<Selected, ItemPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
2107
- data: Selected;
2108
- status: QueryStatus | 'idle' | 'deleted';
683
+ /** Selected item data. Defaults to the full item or `null`. */data: Selected; /** Hook-visible item status, including idle/deleted states for hook ergonomics. */
684
+ status: QueryStatus | 'idle' | 'deleted'; /** Item payload for this result, or `null` when unavailable. */
2109
685
  payload: ItemPayload | null; /** Requested partial-resource fields that are still pending. */
2110
- loadingFields?: string[];
2111
- error: StoreError | null;
2112
- isLoading: boolean;
686
+ loadingFields?: string[]; /** Last item fetch error, if any. */
687
+ error: StoreError | null; /** Convenience flag for `loading` or `refetching` states. */
688
+ isLoading: boolean; /** Stable store key for the current item payload. */
2113
689
  itemStateKey: string; /** Whether this result has local offline changes that still need to sync to the server. */
2114
- pendingSync: boolean;
690
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
2115
691
  queryMetadata: QueryMetadata;
2116
692
  };
693
+ /** Value returned by `ListQueryStore.usePendingOfflineItems(...)`. */
2117
694
  type TSFDUsePendingOfflineItemsReturn<Selected, ItemPayload extends ValidPayload> = {
2118
- items: Selected[];
695
+ /** Locally created or updated offline items selected by the hook. */items: Selected[]; /** Payloads for locally deleted offline items. */
2119
696
  deletedItems: ItemPayload[];
2120
697
  };
698
+ /** One item returned from a list query fetch function. */
2121
699
  type FetchListFnReturnItem<ItemPayload extends ValidPayload, ItemState extends ValidStoreState> = {
2122
- itemPayload: ItemPayload;
700
+ /** Item payload used to key and refetch the returned item. */itemPayload: ItemPayload; /** Item data returned by the server. */
2123
701
  data: ItemState;
2124
702
  };
703
+ /** Return shape for list query fetch functions. */
2125
704
  type FetchListFnReturn<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
2126
- items: FetchListFnReturnItem<ItemPayload, ItemState>[];
705
+ /** Items included in the fetched page. */items: FetchListFnReturnItem<ItemPayload, ItemState>[]; /** Whether the query has another page available. */
2127
706
  hasMore: boolean;
2128
707
  };
2129
- type ListQueryStoreInitialData<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2130
- items: {
2131
- payload: ItemPayload;
2132
- data: ItemState;
2133
- }[];
2134
- queries: {
2135
- payload: QueryPayload;
2136
- items: string[];
2137
- hasMore: boolean;
2138
- }[];
2139
- };
708
+ /** Item descriptor accepted by `ListQueryStore.useMultipleItems(...)`. */
2140
709
  type ListQueryUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
2141
710
  /** Item payload to subscribe to and fetch when needed. */payload: ItemPayload;
2142
711
  /**
@@ -2162,6 +731,7 @@ type ListQueryUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetad
2162
731
  showPartialAsRefetching?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
2163
732
  isOffScreen?: boolean;
2164
733
  };
734
+ /** Query descriptor accepted by `ListQueryStore.useMultipleListQueries(...)`. */
2165
735
  type ListQueryUseMultipleListQueriesQuery<QueryPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
2166
736
  /** Query payload to subscribe to and fetch when needed. */payload: QueryPayload;
2167
737
  /**
@@ -2189,22 +759,26 @@ type ListQueryUseMultipleListQueriesQuery<QueryPayload extends ValidPayload, Que
2189
759
  isOffScreen?: boolean; /** Number of items to request when fetching this query page. */
2190
760
  loadSize?: number;
2191
761
  };
762
+ /** Callback invoked when an already-loaded list query is invalidated. */
2192
763
  type OnListQueryInvalidate<QueryPayload extends ValidPayload> = (query: QueryPayload, priority: FetchType) => void;
764
+ /** Callback invoked when an already-loaded list-query item is invalidated. */
2193
765
  type OnListQueryItemInvalidate<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (props: {
2194
- itemState: ItemState;
2195
- payload: ItemPayload;
766
+ /** Current cached item state at invalidation time. */itemState: ItemState; /** Payload of the invalidated item. */
767
+ payload: ItemPayload; /** Fetch priority requested for the invalidation. */
2196
768
  priority: FetchType;
2197
769
  }) => void;
770
+ /** Rule for keeping cached list query membership in sync after item updates. */
2198
771
  type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2199
- queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[];
2200
- filterItem?: (item: ItemState) => boolean | null;
2201
- appendNewTo?: 'start' | 'end';
2202
- invalidateQueries?: boolean;
772
+ /** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[]; /** Restricts this rule to items that should belong in the affected query set. */
773
+ filterItem?: (item: ItemState) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
774
+ appendNewTo?: 'start' | 'end'; /** Whether affected queries should still refetch after the optimistic list update. */
775
+ invalidateQueries?: boolean; /** Sort order to maintain inside affected query pages. */
2203
776
  sort?: {
2204
- sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[];
777
+ /** Selects sortable values from an item. */sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[]; /** Sort direction for each `sortBy` value. */
2205
778
  order?: 'asc' | 'desc' | ('asc' | 'desc')[];
2206
779
  };
2207
780
  };
781
+ /** Payload passed to list fetch functions. */
2208
782
  type QueryFetchPayload<QueryPayload extends ValidPayload> = {
2209
783
  /** Whether this request loads the first page or a later page. */type: 'load' | 'loadMore'; /** Query payload being fetched. */
2210
784
  payload: QueryPayload; /** Offset used for offset-paginated fetches. */
@@ -2212,12 +786,14 @@ type QueryFetchPayload<QueryPayload extends ValidPayload> = {
2212
786
  limit: number; /** Partial-resource fields requested for each item in the fetched query. */
2213
787
  fields?: string[];
2214
788
  };
789
+ /** Options for offset-based list pagination. */
2215
790
  type OffsetPaginationConfig = {
2216
- maxInvalidationLimit: number; /** Max parallel chunk requests during chunked invalidation (default: 3) */
791
+ /** Largest item count requested when refetching invalidated offset queries. */maxInvalidationLimit: number; /** Max parallel chunk requests during chunked invalidation (default: 3) */
2217
792
  maxParallel?: number;
2218
793
  };
794
+ /** Partial-resource helpers used to merge and select field subsets. */
2219
795
  type PartialResourcesConfig<ItemState extends ValidStoreState> = {
2220
- mergeItems: (prev: ItemState | undefined, fetched: ItemState) => ItemState;
796
+ /** Merges a partial fetch result into an existing item snapshot. */mergeItems: (prev: ItemState | undefined, fetched: ItemState) => ItemState; /** Returns an item containing only the requested fields. */
2221
797
  selectFields: (fields: string[], item: ItemState) => ItemState;
2222
798
  };
2223
799
  type DerivedQuerySummary<QueryPayload extends ValidPayload> = {
@@ -2242,6 +818,7 @@ type DerivedQueryContext = {
2242
818
  */
2243
819
  deriveSource: DerivedQuerySource;
2244
820
  };
821
+ /** Configuration for deriving query membership from locally materialized items. */
2245
822
  type DerivedQueriesConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2246
823
  /** Extracts the domain/group key for a query payload. */getQueryGroup: (queryPayload: QueryPayload) => string; /** Extracts the domain/group key for a materialized item. */
2247
824
  getItemGroup: (item: ItemState, itemPayload: ItemPayload) => string;
@@ -2259,6 +836,7 @@ type DerivedQueriesConfig<ItemState extends ValidStoreState, QueryPayload extend
2259
836
  */
2260
837
  deriveQuery: (queryPayload: QueryPayload, items: DerivedQueryItem<ItemState>[], context: DerivedQueryContext) => string[] | false;
2261
838
  };
839
+ /** Field option shape used by APIs that are conditional on `partialResources`. */
2262
840
  type FieldsOption<HasPartialResources extends boolean> = HasPartialResources extends true ? {
2263
841
  /**
2264
842
  * Partial-resource fields to request.
@@ -2382,14 +960,15 @@ type UsePendingOfflineItemsOptions<ItemState extends ValidStoreState, ItemPayloa
2382
960
  };
2383
961
  //#endregion
2384
962
  //#region src/listQueryStore/listQueryStore.d.ts
963
+ /** Event payloads emitted by `ListQueryStore.events`. */
2385
964
  type ListQueryStoreEvents = {
2386
- invalidateQuery: {
2387
- priority: FetchType;
965
+ /** Emitted whenever one or more list queries are invalidated. */invalidateQuery: {
966
+ /** Fetch priority requested by the invalidation. */priority: FetchType; /** Store key for the invalidated query. */
2388
967
  queryKey: string;
2389
- };
968
+ }; /** Emitted whenever one or more list-query items are invalidated. */
2390
969
  invalidateItem: {
2391
- priority: FetchType;
2392
- itemKey: string;
970
+ /** Fetch priority requested by the invalidation. */priority: FetchType; /** Store key for the invalidated item. */
971
+ itemKey: string; /** Partial-resource fields invalidated on this item, when applicable. */
2393
972
  invalidateFields?: string[];
2394
973
  };
2395
974
  };
@@ -2429,19 +1008,19 @@ type ListQueryFetchFieldsOption<TPartialResources extends boolean> = ListQueryHa
2429
1008
  };
2430
1009
  type ListQueryScheduleFetchWithFieldsOption<TPartialResources extends boolean> = ScheduleFetchOptions & ListQueryFetchFieldsOption<TPartialResources>;
2431
1010
  type ListQueryScheduleListQueryFetchApi<QueryPayload extends ValidPayload, TPartialResources extends boolean> = {
2432
- (fetchType: FetchType, payload: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [size: number | undefined, options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [size?: number, options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults;
2433
- (fetchType: FetchType, payload: QueryPayload[], ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [size: number | undefined, options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [size?: number, options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults[];
1011
+ (fetchType: FetchType, payload: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size: number | undefined, options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size?: number, options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults;
1012
+ (fetchType: FetchType, payload: QueryPayload[], ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size: number | undefined, options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size?: number, options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults[];
2434
1013
  };
2435
1014
  type ListQueryScheduleItemFetchApi<ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
2436
1015
  (fetchType: FetchType, itemPayload: ItemPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults;
2437
1016
  (fetchType: FetchType, itemPayload: ItemPayload[], ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults[];
2438
1017
  };
2439
1018
  type ListQueryLoadMoreWithFieldsOptions<TPartialResources extends boolean> = {
2440
- size?: number;
1019
+ /** Number of additional items to request. Defaults to the store's `defaultQuerySize`. */size?: number;
2441
1020
  } & ListQueryFetchFieldsOption<TPartialResources>;
2442
- type ListQueryLoadMoreApi<QueryPayload extends ValidPayload, TPartialResources extends boolean> = (params: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [size: number, options: ListQueryFetchFieldsOption<TPartialResources>] | [options: ListQueryLoadMoreWithFieldsOptions<TPartialResources>] : [size?: number, options?: ListQueryFetchFieldsOption<TPartialResources>] | [options?: ListQueryLoadMoreWithFieldsOptions<TPartialResources>]) => ScheduleFetchResults;
1021
+ type ListQueryLoadMoreApi<QueryPayload extends ValidPayload, TPartialResources extends boolean> = (params: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [size: number, options: ListQueryFetchFieldsOption<TPartialResources>] | [options: ListQueryLoadMoreWithFieldsOptions<TPartialResources>] : [/** Number of additional items to request. Defaults to the store's `defaultQuerySize`. */size?: number, options?: ListQueryFetchFieldsOption<TPartialResources>] | [options?: ListQueryLoadMoreWithFieldsOptions<TPartialResources>]) => ScheduleFetchResults;
2443
1022
  type ListQueryAwaitListQueryFetchOptions<TPartialResources extends boolean> = {
2444
- size?: number;
1023
+ /** Number of items to request. Defaults to the store's `defaultQuerySize`. */size?: number;
2445
1024
  timeoutMs?: number;
2446
1025
  } & ListQueryFetchFieldsOption<TPartialResources>;
2447
1026
  type ListQueryAwaitListQueryFetchApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean> = (params: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryAwaitListQueryFetchOptions<TPartialResources>] : [options?: ListQueryAwaitListQueryFetchOptions<TPartialResources>]) => Promise<{
@@ -2457,7 +1036,7 @@ type ListQueryAwaitListQueryFetchApi<ItemState extends ValidStoreState, QueryPay
2457
1036
  hasMore: boolean;
2458
1037
  }>;
2459
1038
  type ListQueryGetQueryFromStateOrFetchOptions<TPartialResources extends boolean> = {
2460
- ignoreStaleState?: boolean;
1039
+ /** When `true`, stale cached queries are ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean; /** Number of items to request when a fetch is needed. Defaults to the store's `defaultQuerySize`. */
2461
1040
  size?: number;
2462
1041
  timeoutMs?: number;
2463
1042
  } & ListQueryFetchFieldsOption<TPartialResources>;
@@ -2479,7 +1058,7 @@ type ListQueryAwaitItemFetchApi<ItemState extends ValidStoreState, ItemPayload e
2479
1058
  error: null;
2480
1059
  }>;
2481
1060
  type ListQueryGetItemFromStateOrFetchOptions<TPartialResources extends boolean> = {
2482
- ignoreStaleState?: boolean;
1061
+ /** When `true`, stale cached items are ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean;
2483
1062
  timeoutMs?: number;
2484
1063
  } & ListQueryFetchFieldsOption<TPartialResources>;
2485
1064
  type ListQueryGetItemFromStateOrFetchApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TPartialResources extends boolean> = (itemPayload: ItemPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryGetItemFromStateOrFetchOptions<TPartialResources>] : [options?: ListQueryGetItemFromStateOrFetchOptions<TPartialResources>]) => Promise<Result<ItemState, StoreFetchError>>;
@@ -2509,12 +1088,30 @@ type ListQueryFilterItem<ItemState extends ValidStoreState, ItemPayload extends
2509
1088
  type ListQueryMutationPayload<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload> | null;
2510
1089
  type ListQueryMutationPayloadToUse<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>;
2511
1090
  type ListQueryMutationArgsBase<T, ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2512
- optimisticUpdate?: (payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => void | boolean;
1091
+ /**
1092
+ * Applies optimistic updates for the affected item payloads before the
1093
+ * mutation runs. Return `false` to cancel the mutation before the async
1094
+ * mutation function is called.
1095
+ */
1096
+ optimisticUpdate?: (payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => void | boolean; /** Performs the server mutation for the affected item payloads. */
2513
1097
  mutation: (payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => Promise<T>;
2514
- revalidateOnSuccess?: ListQueryRevalidateOnSuccessOption<QueryPayload>;
2515
- onSuccess?: (response: Awaited<T>, payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => void;
1098
+ /**
1099
+ * Controls query and item invalidation after a successful online mutation.
1100
+ *
1101
+ * Use `true` to invalidate affected items and all queries, `'queries'` to
1102
+ * invalidate only queries, a query filter to invalidate affected items and
1103
+ * matching queries, or `{ queries, items }` to choose both explicitly.
1104
+ */
1105
+ revalidateOnSuccess?: ListQueryRevalidateOnSuccessOption<QueryPayload>; /** Called after a successful online mutation. */
1106
+ onSuccess?: (response: UnwrapTSDFResult<Awaited<T>>, payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => void; /** Called after a failed or skipped mutation. */
2516
1107
  onError?: (error: StoreMutationError | MutationSkipped) => void;
2517
- silentErrors?: boolean;
1108
+ /**
1109
+ * Passes `{ silentErrors: true }` to `onMutationError`.
1110
+ *
1111
+ * The handler is still called so centralized logging and recovery can run,
1112
+ * but UI handlers can suppress user-facing notifications.
1113
+ */
1114
+ silentErrors?: boolean; /** Debounces mutations with the same context and payload. Superseded calls are skipped. */
2518
1115
  debounce?: {
2519
1116
  context: string;
2520
1117
  payload: unknown;
@@ -2526,15 +1123,44 @@ type ListQueryOnlineMutationArgs<T, ItemState extends ValidStoreState, QueryPayl
2526
1123
  upload?: undefined;
2527
1124
  };
2528
1125
  type ListQueryOfflineMutationArgs<T, ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload>> = ListQueryMutationArgsBase<T, ItemState, QueryPayload, ItemPayload> & {
2529
- offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>;
1126
+ /**
1127
+ * Queues this mutation through the store's registered offline operation when
1128
+ * the session is offline or the direct request fails with an offline outage.
1129
+ */
1130
+ offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>; /** Files to attach if this mutation is queued for offline replay. */
2530
1131
  upload?: OfflineMutationUploadsInput;
2531
1132
  };
2532
1133
  type ListQueryPerformMutationApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload>> = {
2533
- <T>(payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>, args: ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload>): Promise<Result<Awaited<T>, StoreMutationError | MutationSkipped>>;
2534
- <T>(payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>, args: ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>): Promise<Result<OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
2535
- <T>(payload: null, args: Omit<ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload>, 'optimisticUpdate'>): Promise<Result<Awaited<T>, StoreMutationError | MutationSkipped>>;
2536
- <T>(payload: null, args: Omit<ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>, 'optimisticUpdate'>): Promise<Result<OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
2537
- <T>(payload: ListQueryMutationPayload<ItemState, ItemPayload>, args: ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload> | ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>): Promise<Result<Awaited<T> | OfflineMutationResult<T>, StoreMutationError | MutationSkipped>>;
1134
+ /**
1135
+ * Runs a list-query mutation for existing item payloads or an item filter.
1136
+ *
1137
+ * Returns the direct server result when offline replay is not configured for
1138
+ * this call.
1139
+ */
1140
+ <T>(payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>, args: ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
1141
+ /**
1142
+ * Runs a list-query mutation for existing item payloads or an item filter,
1143
+ * with durable offline queueing as a fallback.
1144
+ *
1145
+ * When the mutation is queued, the result is `{ kind: 'queued' }` instead of
1146
+ * the server payload.
1147
+ */
1148
+ <T>(payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>, args: ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
1149
+ /**
1150
+ * Runs a list-query mutation with no current item target.
1151
+ *
1152
+ * Use this for create mutations that do not have a pre-generated item payload
1153
+ * yet. Optimistic updates are not available without a target payload.
1154
+ */
1155
+ <T>(payload: null, args: Omit<ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload>, 'optimisticUpdate'>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
1156
+ /**
1157
+ * Runs an offline-capable list-query mutation with no current item target.
1158
+ *
1159
+ * Use this for create mutations that do not have a pre-generated item payload
1160
+ * yet. When the mutation is queued, the result is `{ kind: 'queued' }`.
1161
+ */
1162
+ <T>(payload: null, args: Omit<ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>, 'optimisticUpdate'>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
1163
+ <T>(payload: ListQueryMutationPayload<ItemState, ItemPayload>, args: ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload> | ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>): Promise<Result<UnwrapTSDFResult<Awaited<T>> | OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
2538
1164
  };
2539
1165
  type ListQueryUpdateItemStateApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (itemIds: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>, produceNewData: (draftData: ItemState, itemPayload: ItemPayload) => void | ItemState, options?: {
2540
1166
  ifNothingWasUpdated?: () => void;
@@ -2547,7 +1173,7 @@ type ListQueryAddItemToStateApi<ItemState extends ValidStoreState, QueryPayload
2547
1173
  }) => void;
2548
1174
  type ListQueryDeleteItemStateApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>) => void;
2549
1175
  type ListQueryInvalidateQueryAndItemsArgs<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2550
- /** Invalidate every cached query and every cached item. */all: true; /** Fetch priority used for refetches triggered by this invalidation. */
1176
+ /** Invalidate every cached query and every cached item. */all: true; /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
2551
1177
  type?: FetchType;
2552
1178
  /**
2553
1179
  * Partial-resource fields to invalidate on matching items.
@@ -2572,7 +1198,7 @@ type ListQueryInvalidateQueryAndItemsArgs<ItemState extends ValidStoreState, Que
2572
1198
  * Pass one payload, many payloads, a predicate over cached queries, or
2573
1199
  * `false` to skip query invalidation.
2574
1200
  */
2575
- queryPayload: QueryPayload | QueryPayload[] | ListQueryFilterQuery<QueryPayload> | false; /** Fetch priority used for refetches triggered by this invalidation. */
1201
+ queryPayload: QueryPayload | QueryPayload[] | ListQueryFilterQuery<QueryPayload> | false; /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
2576
1202
  type?: FetchType;
2577
1203
  /**
2578
1204
  * Partial-resource fields to invalidate on matching items.
@@ -2581,167 +1207,130 @@ type ListQueryInvalidateQueryAndItemsArgs<ItemState extends ValidStoreState, Que
2581
1207
  */
2582
1208
  fields?: string[];
2583
1209
  };
1210
+ /** Public API returned by `createListQueryStore(...)`. */
2584
1211
  type ListQueryStore<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = {
2585
- store: Store<TSFDListQueryState<ItemState, QueryPayload, ItemPayload>>;
2586
- events: Emitter<ListQueryStoreEvents>;
2587
- storeEvents: Emitter<ListQueryStoreStoreEvents<ItemPayload>>;
2588
- readonly queryInvalidationWasTriggered: Set<string>;
2589
- readonly itemInvalidationWasTriggered: Set<string>;
2590
- reset: () => void;
2591
- dispose: () => void;
2592
- scheduleListQueryFetch: ListQueryScheduleListQueryFetchApi<QueryPayload, TPartialResources>;
2593
- getQueryState: (params: QueryPayload) => TSFDListQuery<QueryPayload> | undefined;
2594
- getQueryKey: (params: QueryPayload) => string;
1212
+ /** Underlying t-state store containing raw cached queries and items. */store: Store<TSFDListQueryState<ItemState, QueryPayload, ItemPayload>>; /** Invalidation event emitter used by hooks and integrations. */
1213
+ events: Emitter<ListQueryStoreEvents>; /** Mutation lifecycle event emitter for observers and tests. */
1214
+ storeEvents: Emitter<ListQueryStoreStoreEvents<ItemPayload>>; /** Query keys that have been explicitly invalidated and are awaiting refresh. */
1215
+ readonly queryInvalidationWasTriggered: Set<string>; /** Item keys that have been explicitly invalidated and are awaiting refresh. */
1216
+ readonly itemInvalidationWasTriggered: Set<string>; /** Clears in-memory state and cancels store-local runtime state. */
1217
+ reset: () => void; /** Unregisters listeners and releases resources owned by this store. */
1218
+ dispose: () => void; /** Schedules a list-query fetch with the requested priority. */
1219
+ scheduleListQueryFetch: ListQueryScheduleListQueryFetchApi<QueryPayload, TPartialResources>; /** Reads one cached query directly from store state. */
1220
+ getQueryState: (params: QueryPayload) => TSFDListQuery<QueryPayload> | undefined; /** Returns the stable cache key for a query payload. */
1221
+ getQueryKey: (params: QueryPayload) => string; /** Reads many cached queries directly from store state. */
2595
1222
  getQueriesState: (params: QueryPayload[] | ListQueryFilterQuery<QueryPayload>) => {
2596
1223
  query: TSFDListQuery<QueryPayload>;
2597
1224
  key: string;
2598
- }[];
1225
+ }[]; /** Finds cached queries that currently include the item payload. */
2599
1226
  getQueriesRelatedToItem: (itemPayload: ItemPayload) => {
2600
1227
  query: TSFDListQuery<QueryPayload>;
2601
1228
  key: string;
2602
- }[];
2603
- awaitListQueryFetch: ListQueryAwaitListQueryFetchApi<ItemState, QueryPayload, ItemPayload, TPartialResources>;
2604
- getQueryFromStateOrFetch: ListQueryGetQueryFromStateOrFetchApi<ItemState, QueryPayload, ItemPayload, TPartialResources>;
2605
- preloadQueryFromStorage: (params: QueryPayload | QueryPayload[]) => Promise<PersistentStoragePreloadResult<QueryPayload>[]>;
2606
- loadMore: ListQueryLoadMoreApi<QueryPayload, TPartialResources>;
2607
- getItemKey: (params: ItemPayload) => string;
1229
+ }[]; /** Waits for a list-query fetch to settle and returns query data or a fetch error. */
1230
+ awaitListQueryFetch: ListQueryAwaitListQueryFetchApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** Returns a cached query when usable, otherwise fetches it first. */
1231
+ getQueryFromStateOrFetch: ListQueryGetQueryFromStateOrFetchApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** Loads query payloads from persistent storage into memory when available. */
1232
+ preloadQueryFromStorage: (params: QueryPayload | QueryPayload[]) => Promise<PersistentStoragePreloadResult<QueryPayload>[]>; /** Fetches and appends the next page for a list query. */
1233
+ loadMore: ListQueryLoadMoreApi<QueryPayload, TPartialResources>; /** Returns the stable cache key for an item payload. */
1234
+ getItemKey: (params: ItemPayload) => string; /** Reads one or many cached items directly from store state. */
2608
1235
  getItemState: {
2609
1236
  (itemPayload: ItemPayload): ItemState | null | undefined;
2610
1237
  (itemPayload: ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>): {
2611
1238
  payload: ItemPayload;
2612
1239
  data: ItemState;
2613
1240
  }[];
2614
- };
2615
- usePendingOfflineItems: ListQueryUsePendingOfflineItemsApi<ItemState, ItemPayload>;
2616
- getOfflineEntities: () => GlobalOfflineEntity[];
2617
- useOfflineEntities: () => readonly GlobalOfflineEntity[];
2618
- useOfflineResolutions: () => readonly OfflineResolutionRecord[];
2619
- getOfflineResolutions: () => OfflineResolutionRecord[];
2620
- parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedListQueryOfflineOperations<TOfflineOperations>>;
2621
- resolveOfflineResolution: <TName extends keyof ResolvedListQueryOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedListQueryOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void;
2622
- preloadItemFromStorage: (params: ItemPayload | ItemPayload[]) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>;
2623
- scheduleItemFetch: ListQueryScheduleItemFetchApi<ItemPayload, TPartialResources>;
2624
- awaitItemFetch: ListQueryAwaitItemFetchApi<ItemState, ItemPayload, TPartialResources>;
2625
- getItemFromStateOrFetch: ListQueryGetItemFromStateOrFetchApi<ItemState, ItemPayload, TPartialResources>;
2626
- invalidateQueryAndItems: (args: ListQueryInvalidateQueryAndItemsArgs<ItemState, QueryPayload, ItemPayload>) => void;
2627
- invalidateItem: (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>, priority?: FetchType) => void;
2628
- startItemMutation: (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>) => () => void;
2629
- updateItemState: ListQueryUpdateItemStateApi<ItemState, ItemPayload>;
2630
- addItemToState: ListQueryAddItemToStateApi<ItemState, QueryPayload, ItemPayload>;
1241
+ }; /** React hook for locally pending offline items in this store. */
1242
+ usePendingOfflineItems: ListQueryUsePendingOfflineItemsApi<ItemState, ItemPayload>; /** Returns offline sync metadata for this store's tracked entities. */
1243
+ getOfflineEntities: () => GlobalOfflineEntity[]; /** React hook subscribing to this store's offline entity metadata. */
1244
+ useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to manual offline resolutions for this store. */
1245
+ useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns manual offline resolutions for this store. */
1246
+ getOfflineResolutions: () => OfflineResolutionRecord[]; /** Parses a stored offline conflict into the operation-specific conflict shape. */
1247
+ parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedListQueryOfflineOperations<TOfflineOperations>>; /** Applies a retry/discard/requeue/commit action to a pending offline resolution. */
1248
+ resolveOfflineResolution: <TName extends keyof ResolvedListQueryOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedListQueryOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void; /** Loads item payloads from persistent storage into memory when available. */
1249
+ preloadItemFromStorage: (params: ItemPayload | ItemPayload[]) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>; /** Schedules an item fetch with the requested priority. */
1250
+ scheduleItemFetch: ListQueryScheduleItemFetchApi<ItemPayload, TPartialResources>; /** Waits for an item fetch to settle and returns data or a fetch error. */
1251
+ awaitItemFetch: ListQueryAwaitItemFetchApi<ItemState, ItemPayload, TPartialResources>; /** Returns cached item data when usable, otherwise fetches it first. */
1252
+ getItemFromStateOrFetch: ListQueryGetItemFromStateOrFetchApi<ItemState, ItemPayload, TPartialResources>; /** Invalidates selected queries and items together. Defaults to `highPriority`. */
1253
+ invalidateQueryAndItems: (args: ListQueryInvalidateQueryAndItemsArgs<ItemState, QueryPayload, ItemPayload>) => void; /** Marks cached items stale and schedules refetches for active subscriptions. Defaults to `highPriority`. */
1254
+ invalidateItem: (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>, /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
1255
+
1256
+ priority?: FetchType) => void; /** Marks one or more items as mutating and returns a function that ends the mutation. */
1257
+ startItemMutation: (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>) => () => void; /** Applies an immutable update to one or more cached list-query items. */
1258
+ updateItemState: ListQueryUpdateItemStateApi<ItemState, ItemPayload>; /** Adds or replaces one cached item directly in state. */
1259
+ addItemToState: ListQueryAddItemToStateApi<ItemState, QueryPayload, ItemPayload>; /** Deletes one cached item directly from state and query membership. */
2631
1260
  deleteItemState: ListQueryDeleteItemStateApi<ItemState, ItemPayload>;
2632
- performMutation: ListQueryPerformMutationApi<ItemState, QueryPayload, ItemPayload, TOfflineOperations>;
2633
- useMultipleListQueries: ListQueryUseMultipleListQueriesApi<ItemState, QueryPayload, ItemPayload, TPartialResources>;
2634
- useListQuery: ListQueryUseListQueryApi<ItemState, QueryPayload, ItemPayload, TPartialResources>;
2635
- useMultipleItems: ListQueryUseMultipleItemsApi<ItemState, ItemPayload, TPartialResources>;
2636
- useItem: ListQueryUseItemApi<ItemState, ItemPayload, TPartialResources>;
1261
+ /**
1262
+ * Runs the full mutation lifecycle: optional optimistic update, async
1263
+ * mutation, rollback/error handling, revalidation, and offline queue fallback.
1264
+ */
1265
+ performMutation: ListQueryPerformMutationApi<ItemState, QueryPayload, ItemPayload, TOfflineOperations>; /** React hook for subscribing to many list queries at once. */
1266
+ useMultipleListQueries: ListQueryUseMultipleListQueriesApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** React hook for subscribing to one list query. */
1267
+ useListQuery: ListQueryUseListQueryApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** React hook for subscribing to many list-query items at once. */
1268
+ useMultipleItems: ListQueryUseMultipleItemsApi<ItemState, ItemPayload, TPartialResources>; /** React hook for subscribing to one list-query item. */
1269
+ useItem: ListQueryUseItemApi<ItemState, ItemPayload, TPartialResources>; /** React hook for selecting the first cached item matching a predicate. */
2637
1270
  useFindItem: <SelectedItem = ItemState | null>(findItemFn: (item: ItemState, itemPayload: ItemPayload) => boolean, options?: {
2638
1271
  /** Maps the matched item before it is returned from the hook. */selector?: (data: ItemState, id: ItemPayload) => SelectedItem;
2639
- }) => SelectedItem | null;
1272
+ }) => SelectedItem | null; /** Notifies the store that a shared transport reconnected and should revalidate active data. */
2640
1273
  onTransportReconnect: () => void;
2641
1274
  };
1275
+ /** Details passed when list-query cache-limit cleanup evicts cached items or queries. */
2642
1276
  type ListQueryStateCleanup<QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2643
- reason: 'cacheLimitEviction';
2644
- itemKeys: string[];
2645
- itemPayloads: ItemPayload[];
2646
- queryKeys: string[];
1277
+ /** Cleanup trigger that removed these records. */reason: 'cacheLimitEviction'; /** Item store keys removed from state. */
1278
+ itemKeys: string[]; /** Original item payloads removed from state. */
1279
+ itemPayloads: ItemPayload[]; /** Query store keys removed from state. */
1280
+ queryKeys: string[]; /** Original query payloads removed from state. */
2647
1281
  queryPayloads: QueryPayload[];
2648
1282
  };
2649
1283
  type FetchListFnSizeMode<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = (payload: QueryPayload, size: number, options: {
2650
1284
  signal: AbortSignal;
2651
1285
  fields?: string[];
2652
- }) => Promise<FetchListFnReturn<ItemState, ItemPayload>>;
1286
+ }) => Promise<MaybeTSDFResult<FetchListFnReturn<ItemState, ItemPayload>>>;
2653
1287
  type FetchListFnOffsetMode<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = (payload: QueryPayload, pagination: {
2654
1288
  offset: number;
2655
1289
  limit: number;
2656
1290
  }, options: {
2657
1291
  signal: AbortSignal;
2658
1292
  fields?: string[];
2659
- }) => Promise<FetchListFnReturn<ItemState, ItemPayload>>;
2660
- type ListQuerySnapshotItemEntry<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
2661
- itemKey: string;
2662
- item: ItemState | null;
2663
- itemQuery: TSDFItemQuery<ItemPayload> | null;
2664
- loadedFields: string[];
2665
- };
2666
- type ListQueryBrowserTabsMessage<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = (BrowserTabsMessageMeta & BrowserTabsTabStatusMessage) | (BrowserTabsMessageMeta & {
2667
- kind: 'list-query-snapshot';
2668
- queryKey: string;
2669
- consistency: SnapshotConsistency;
2670
- query: TSFDListQuery<QueryPayload>;
2671
- items: ListQuerySnapshotItemEntry<ItemState, ItemPayload>[];
2672
- }) | (BrowserTabsMessageMeta & {
2673
- kind: 'list-item-snapshot';
2674
- itemKey: string;
2675
- consistency: SnapshotConsistency;
2676
- item: ItemState | null;
2677
- itemQuery: TSDFItemQuery<ItemPayload> | null;
2678
- loadedFields: string[];
2679
- }) | (BrowserTabsMessageMeta & {
2680
- kind: 'fetch-start';
2681
- targetKey: string;
2682
- requestIds: string[];
2683
- startedAt: number;
2684
- }) | (BrowserTabsMessageMeta & {
2685
- kind: 'fetch-success';
2686
- targetKey: string;
2687
- requestIds: string[];
2688
- startedAt: number;
2689
- duration: number;
2690
- });
1293
+ }) => Promise<MaybeTSDFResult<FetchListFnReturn<ItemState, ItemPayload>>>;
2691
1294
  type ListQueryStoreOptionsBase<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null, StorageState = unknown> = {
2692
1295
  /**
2693
1296
  * Stable id for this logical list-query store. Used for debug labels,
2694
1297
  * persistence namespaces, and browser tab sync.
2695
1298
  */
2696
1299
  id: string; /** Shared global store manager providing session scoping and error normalization. */
2697
- storeManager: StoreManager;
1300
+ storeManager: StoreManager; /** Fetches one item by payload. Required when items can be loaded outside list pages. */
2698
1301
  fetchItemFn?: (payload: ItemPayload, options: {
2699
1302
  signal: AbortSignal;
2700
1303
  fields?: string[];
2701
- }) => Promise<ItemState>;
1304
+ }) => Promise<MaybeTSDFResult<ItemState>>; /** Optional batch fetch function for fetching multiple items at once. */
2702
1305
  batchFetchItemFn?: (requests: {
2703
1306
  payload: ItemPayload;
2704
1307
  fields?: string[];
2705
1308
  }[], options: {
2706
1309
  signal: AbortSignal;
2707
1310
  batchKey: string;
2708
- }) => Promise<Map<ItemPayload, ItemState | Error>>;
2709
- getItemsBatchKey?: (payload: ItemPayload) => string | false;
2710
- defaultQuerySize?: number;
1311
+ }) => Promise<MaybeTSDFResult<Map<ItemPayload, MaybeTSDFResult<ItemState> | Error>>>; /** Optional function to group item batch fetches by key. When omitted, all batched items share one default batch key. Return false to fetch individually. */
1312
+ getItemsBatchKey?: (payload: ItemPayload) => string | false; /** Default number of items requested by list-query fetches. Defaults to 50. */
1313
+ defaultQuerySize?: number; /** Max items per item batch. Defaults to 50. Triggers an immediate fetch when reached. */
2711
1314
  maxItemBatchSize?: number; /** Maximum number of cached items kept in memory. Defaults to 5,000. Item pressure may evict whole inactive queries to avoid leaving cached queries partially loaded. */
2712
1315
  maxItems?: number; /** Maximum number of cached queries kept in memory. Defaults to 1,000. Inactive queries are evicted in LRU order while mounted hook queries stay protected. */
2713
1316
  maxQueries?: number; /** Called when cache-limit eviction removes items or queries from in-memory state. */
2714
- onStateCleanup?: (cleanup: ListQueryStateCleanup<QueryPayload, ItemPayload>) => void;
2715
- usesRealTimeUpdates?: boolean;
2716
- '~test'?: {
2717
- initialData?: ListQueryStoreInitialData<ItemState, QueryPayload, ItemPayload>;
2718
- initialRefetchOnMount?: FetchType | false;
2719
- initialLastFetchStartTime?: number;
2720
- getWindowIsFocused?: () => boolean;
2721
- onWindowFocus?: (handler: () => void) => () => void;
2722
- onWindowFocusChange?: (handler: () => void) => () => void;
2723
- browserTabsTransportFactory?: BrowserTabsTransportFactory;
2724
- browserTabsPriorityTimings?: BrowserTabsPriorityTimings;
2725
- browserTabsLeadershipTimings?: BrowserTabsPriorityTimings;
2726
- onReceiveRemoteMsg?: (message: ListQueryBrowserTabsMessage<ItemState, QueryPayload, ItemPayload>) => void;
2727
- onSessionKeyChanged?: (event: TestSessionKeyChangedEvent) => void;
2728
- onOfflineTimelineEvent?: (event: TestOfflineTimelineEvent) => void;
2729
- }; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
1317
+ onStateCleanup?: (cleanup: ListQueryStateCleanup<QueryPayload, ItemPayload>) => void; /** Treats refetches as real-time driven, disabling stale mount refetches by default. Defaults to `false`. */
1318
+ usesRealTimeUpdates?: boolean; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
2730
1319
  lowPriorityThrottleMs?: number; /** Overrides the manager's default coalescing window for this store. */
2731
- baseCoalescingWindowMs?: number;
2732
- mediumPriorityDelayMs?: number;
1320
+ baseCoalescingWindowMs?: number; /** Delay applied to medium-priority requests before they enter the scheduler. */
1321
+ mediumPriorityDelayMs?: number; /** Computes a per-fetch throttle for real-time updates using recent fetch cost and focus state. */
2733
1322
  dynamicRealtimeThrottleMs?: (params: {
2734
1323
  lastFetchDuration: number;
2735
1324
  windowIsNotFocused: boolean;
2736
- }) => number;
1325
+ }) => number; /** Store-level focus revalidation policy. Overrides the manager default. */
2737
1326
  revalidateOnWindowFocus?: boolean | (() => boolean);
2738
- /** Reconnect-specific cooldown. The first reconnect revalidates immediately;
1327
+ /** Reconnect-specific cooldown. Defaults to 2,000ms. The first reconnect revalidates immediately;
2739
1328
  * additional reconnects within the cooldown are coalesced into one trailing
2740
1329
  * revalidation. Set to `0` to disable this cooldown. */
2741
- transportReconnectCooldownMs?: number;
2742
- optimisticListUpdates?: OptimisticListUpdate<ItemState, QueryPayload, ItemPayload>[];
2743
- onInvalidateQuery?: OnListQueryInvalidate<QueryPayload>;
2744
- onInvalidateItem?: OnListQueryItemInvalidate<ItemState, ItemPayload>;
1330
+ transportReconnectCooldownMs?: number; /** Rules that keep cached query membership in sync after item updates. */
1331
+ optimisticListUpdates?: OptimisticListUpdate<ItemState, QueryPayload, ItemPayload>[]; /** Called when an already-loaded query is invalidated. */
1332
+ onInvalidateQuery?: OnListQueryInvalidate<QueryPayload>; /** Called when an already-loaded item is invalidated. */
1333
+ onInvalidateItem?: OnListQueryItemInvalidate<ItemState, ItemPayload>; /** Observes request scheduler lifecycle events for this store. */
2745
1334
  onSchedulerEvent?: (event: RequestSchedulerEvents, data?: RequestSchedulerEventData) => void;
2746
1335
  /**
2747
1336
  * Store-specific mutation error handler.
@@ -2750,8 +1339,8 @@ type ListQueryStoreOptionsBase<ItemState extends ValidStoreState, QueryPayload e
2750
1339
  * error handling for this store.
2751
1340
  */
2752
1341
  onMutationError?: ((error: unknown, options: StoreMutationErrorOptions) => void) | null; /** Opt-in hook-level query derivation from locally materialized items. */
2753
- derivedQueries?: DerivedQueriesConfig<ItemState, QueryPayload, ItemPayload>;
2754
- getQueryKey?: (params: QueryPayload) => ValidPayload | unknown[];
1342
+ derivedQueries?: DerivedQueriesConfig<ItemState, QueryPayload, ItemPayload>; /** Converts a query payload to the stable cache key used by this store. */
1343
+ getQueryKey?: (params: QueryPayload) => ValidPayload | unknown[]; /** Converts an item payload to the stable cache key used by this store. */
2755
1344
  getItemKey?: (params: ItemPayload) => ValidPayload | unknown[];
2756
1345
  /** Opt-in persistent storage configuration. When provided, cached items and queries
2757
1346
  * are loaded from storage on first read and saved back on successful fetches.
@@ -2763,11 +1352,12 @@ type ListQueryStoreOptionsBase<ItemState extends ValidStoreState, QueryPayload e
2763
1352
  } : {
2764
1353
  partialResources?: undefined;
2765
1354
  });
1355
+ /** Options used to create a list-query store. */
2766
1356
  type ListQueryStoreOptions<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOffsetPagination extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null, StorageState = unknown> = ListQueryStoreOptionsBase<ItemState, QueryPayload, ItemPayload, TPartialResources, TOfflineOperations, StorageState> & ([TOffsetPagination] extends [true] ? {
2767
- fetchListFn: FetchListFnOffsetMode<ItemState, QueryPayload, ItemPayload>;
1357
+ /** Fetches one offset-paginated list query page. */fetchListFn: FetchListFnOffsetMode<ItemState, QueryPayload, ItemPayload>; /** Enables offset-pagination behavior and invalidation sizing. */
2768
1358
  offsetPagination: OffsetPaginationConfig;
2769
1359
  } : {
2770
- fetchListFn: FetchListFnSizeMode<ItemState, QueryPayload, ItemPayload>;
1360
+ /** Fetches one size-based list query page. */fetchListFn: FetchListFnSizeMode<ItemState, QueryPayload, ItemPayload>; /** Not allowed unless offset pagination is enabled. */
2771
1361
  offsetPagination?: undefined;
2772
1362
  });
2773
1363
  declare function createListQueryStore<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOffsetPagination extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null, StorageState = unknown>(storeOptions: ListQueryStoreOptions<ItemState, QueryPayload, ItemPayload, TPartialResources, TOffsetPagination, TOfflineOperations, StorageState>): ListQueryStore<ItemState, QueryPayload, ItemPayload, TPartialResources, TOfflineOperations>;
@@ -2828,14 +1418,6 @@ declare function useGlobalOfflineEntities(sessionKey: string): readonly GlobalOf
2828
1418
  */
2829
1419
  declare function useGlobalOfflineResolutions(sessionKey: string): readonly OfflineResolutionRecord[];
2830
1420
  //#endregion
2831
- //#region src/persistentStorage/asyncStorageAdapter.d.ts
2832
- declare function createAsyncStorageAdapter(driver: AsyncStorageDriver): AsyncStorageAdapter;
2833
- //#endregion
2834
- //#region src/persistentStorage/indexedDbAsyncStorageAdapter.d.ts
2835
- type IndexedDbPersistentStorageOptions$1 = {
2836
- databaseName?: string;
2837
- };
2838
- //#endregion
2839
1421
  //#region src/persistentStorage/localStorageMetadata.d.ts
2840
1422
  type ManagedLocalStorageIo = {
2841
1423
  getItem(key: string): string | null;
@@ -2919,10 +1501,6 @@ type LocalPersistentStorage = {
2919
1501
  syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>): void;
2920
1502
  };
2921
1503
  declare const localPersistentStorage: LocalPersistentStorage;
2922
- declare const opfsPersistentStorage: AsyncStorageAdapter;
2923
- declare const indexedDbPersistentStorage: AsyncStorageAdapter;
2924
- type IndexedDbPersistentStorageOptions = IndexedDbPersistentStorageOptions$1;
2925
- declare function createIndexedDbPersistentStorage(options?: IndexedDbPersistentStorageOptions): AsyncStorageAdapter;
2926
1504
  //#endregion
2927
1505
  //#region src/persistentStorage/persistentStorageManager.d.ts
2928
1506
  /** Clears all persistent storage entries for a given session key and adapter. */
@@ -2933,4 +1511,4 @@ declare function clearAllSessionStorage(sessionKey: string): Promise<void>;
2933
1511
  //#region src/persistentStorage/opfsOfflineUploadAdapter.d.ts
2934
1512
  declare const opfsOfflineUploadAdapter: OfflineUploadAdapter;
2935
1513
  //#endregion
2936
- export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionBrowserTabsMessage, CollectionInitialStateItem, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, DocumentBrowserTabsMessage, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, type IndexedDbPersistentStorageOptions, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreInitialData, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFItemQuery, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createAsyncStorageAdapter, createCollectionStore, createDocumentStore, createIndexedDbPersistentStorage, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, indexedDbPersistentStorage, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, opfsPersistentStorage, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
1514
+ export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFDebugOptions, type TSDFItemQuery, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };