tsdf 18.1.1 → 18.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/async-storage.d.ts +1 -1
- package/dist/async-storage.js +1 -1
- package/dist/{asyncStorageAdapter-DgsuE-T8.d.ts → asyncStorageAdapter-BDWpJ1vC.d.ts} +1 -1
- package/dist/{asyncStorageAdapter-CxDIO_Pv.js → asyncStorageAdapter-NrI38v4g.js} +83 -2
- package/dist/{asyncStorageAdapters-Dno2qiLy.js → asyncStorageAdapters-Daewq7dv.js} +2 -2
- package/dist/indexed-db-storage.d.ts +2 -4
- package/dist/indexed-db-storage.js +1 -1
- package/dist/{indexedDbPersistentStorage-BEJA8z8c.js → indexedDbPersistentStorage-JJdUGGI8.js} +5 -3
- package/dist/main.d.ts +78 -15
- package/dist/main.js +609 -83
- package/dist/opfs-storage.d.ts +1 -1
- package/dist/opfs-storage.js +1 -1
- package/dist/{opfsPersistentStorage-BngS1m0X.d.ts → opfsPersistentStorage-CcdWYuhc.d.ts} +1 -1
- package/dist/{opfsPersistentStorage-CZThibFg.js → opfsPersistentStorage-amwSWm_p.js} +27 -4
- package/dist/{types-BlyGC_PO.d.ts → types-2UJIjziu.d.ts} +112 -14
- package/docs/list-query-store.md +1 -0
- package/docs/offline.md +111 -3
- package/docs/optimistic-list-updates.md +37 -1
- package/docs/partial-resources.md +2 -0
- package/docs/persistent-storage.md +51 -3
- package/docs/store-manager.md +27 -5
- package/package.json +9 -10
package/dist/opfs-storage.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as opfsPersistentStorage } from "./opfsPersistentStorage-
|
|
1
|
+
import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CcdWYuhc.js";
|
|
2
2
|
export { opfsPersistentStorage };
|
package/dist/opfs-storage.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as opfsPersistentStorage } from "./opfsPersistentStorage-
|
|
1
|
+
import { t as opfsPersistentStorage } from "./opfsPersistentStorage-amwSWm_p.js";
|
|
2
2
|
export { opfsPersistentStorage };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { X as getNamespaceId, Y as encodePersistedAsyncNamespaceKind, Z as getPayloadRecordKey, b as emitTSDFDebugLog, i as createAsyncStorageAdapter, nt as parsePersistedAsyncNamespaceKind, tt as parseAsyncStorageRecordKey, x as getTSDFDebugTimingMs } from "./asyncStorageAdapter-NrI38v4g.js";
|
|
2
2
|
import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
|
|
3
3
|
import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
|
|
4
4
|
import { isObject } from "@ls-stack/utils/typeGuards";
|
|
@@ -111,8 +111,14 @@ function parseFileNameInfo(fileName) {
|
|
|
111
111
|
//#endregion
|
|
112
112
|
//#region src/persistentStorage/opfsHelpers.ts
|
|
113
113
|
async function getNavigatorStorageDirectory() {
|
|
114
|
+
const root = await getNavigatorStorageDirectoryIfAvailable();
|
|
115
|
+
if (root === null) throw new Error("[TSDF] OPFS is unavailable in this environment.");
|
|
116
|
+
return root;
|
|
117
|
+
}
|
|
118
|
+
/** Returns `null` when the environment has no OPFS at all. */
|
|
119
|
+
async function getNavigatorStorageDirectoryIfAvailable() {
|
|
114
120
|
const storage = asPossiblyUndefined(globalThis.navigator)?.storage;
|
|
115
|
-
if (storage?.getDirectory === void 0)
|
|
121
|
+
if (storage?.getDirectory === void 0) return null;
|
|
116
122
|
return storage.getDirectory();
|
|
117
123
|
}
|
|
118
124
|
async function getDirectoryHandleIfExists(parent, name) {
|
|
@@ -134,6 +140,7 @@ async function getFileHandleIfExists(parent, name) {
|
|
|
134
140
|
const OPFS_DIR_HANDLE_CACHE_MAX_SIZE = 500;
|
|
135
141
|
const OPFS_FILE_HANDLE_CACHE_MAX_SIZE = 1e4;
|
|
136
142
|
var OpfsAsyncStorageDriver = class {
|
|
143
|
+
storageId = "opfs";
|
|
137
144
|
debugLogger;
|
|
138
145
|
#rootDirPromise = null;
|
|
139
146
|
#mainCacheContext = {
|
|
@@ -470,8 +477,11 @@ var OpfsAsyncStorageDriver = class {
|
|
|
470
477
|
return Object.keys(rawEntries).map((key) => getPayloadRecordKey(key));
|
|
471
478
|
}
|
|
472
479
|
async #getSessionEntries(sessionKey, cacheContext) {
|
|
473
|
-
|
|
474
|
-
|
|
480
|
+
if (sessionKey === void 0) {
|
|
481
|
+
const root = await this.#getExistingRootDir();
|
|
482
|
+
return root === null ? [] : await this.#listDirectoryEntries(root, OPFS_ROOT_DIR, cacheContext);
|
|
483
|
+
}
|
|
484
|
+
return [{
|
|
475
485
|
handle: await this.#getSessionDir(sessionKey, {
|
|
476
486
|
create: false,
|
|
477
487
|
cacheContext
|
|
@@ -480,6 +490,19 @@ var OpfsAsyncStorageDriver = class {
|
|
|
480
490
|
path: this.#getSessionDirPath(sessionKey)
|
|
481
491
|
}];
|
|
482
492
|
}
|
|
493
|
+
/**
|
|
494
|
+
* Root directory for listings, which must not create storage: `null` when
|
|
495
|
+
* OPFS is unavailable or TSDF never wrote to it, since nothing can be
|
|
496
|
+
* stored there either way.
|
|
497
|
+
*/
|
|
498
|
+
async #getExistingRootDir() {
|
|
499
|
+
if (this.#rootDirPromise !== null) return this.#rootDirPromise;
|
|
500
|
+
const navigatorRoot = await getNavigatorStorageDirectoryIfAvailable();
|
|
501
|
+
if (navigatorRoot === null) return null;
|
|
502
|
+
const root = await getDirectoryHandleIfExists(navigatorRoot, OPFS_ROOT_DIR);
|
|
503
|
+
if (root !== null) this.#rootDirPromise ??= Promise.resolve(root);
|
|
504
|
+
return root;
|
|
505
|
+
}
|
|
483
506
|
async #getRootDir() {
|
|
484
507
|
if (this.#rootDirPromise === null) this.#rootDirPromise = (async () => {
|
|
485
508
|
return (await getNavigatorStorageDirectory()).getDirectoryHandle(OPFS_ROOT_DIR, { create: true });
|
|
@@ -272,8 +272,26 @@ type OnListQueryItemInvalidate<ItemState extends ValidStoreState, ItemPayload ex
|
|
|
272
272
|
}) => void;
|
|
273
273
|
/** Rule for keeping cached list query membership in sync after item updates. */
|
|
274
274
|
type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
|
|
275
|
-
/** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[];
|
|
276
|
-
|
|
275
|
+
/** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[];
|
|
276
|
+
/**
|
|
277
|
+
* Decides whether an item belongs in each affected query. Called once per
|
|
278
|
+
* affected query, so a single rule can decide membership from
|
|
279
|
+
* `context.queryPayload` instead of needing one rule per query.
|
|
280
|
+
*
|
|
281
|
+
* - `true`: the item should be in the query (added if missing)
|
|
282
|
+
* - `false`: the item should not be in the query (removed if present)
|
|
283
|
+
* - `null`: keep the membership as is and skip this rule for the query
|
|
284
|
+
*/
|
|
285
|
+
filterItem?: (item: ItemState, context: {
|
|
286
|
+
/** Payload of the query being evaluated. */readonly queryPayload: QueryPayload; /** Payload of the item being evaluated. */
|
|
287
|
+
readonly itemPayload: ItemPayload;
|
|
288
|
+
/**
|
|
289
|
+
* Whether the item is in the query's cached list right before this rule
|
|
290
|
+
* is applied. Computed on first read, so it costs nothing when unused,
|
|
291
|
+
* and must be read while `filterItem` is running.
|
|
292
|
+
*/
|
|
293
|
+
readonly isInQuery: boolean;
|
|
294
|
+
}) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
|
|
277
295
|
appendNewTo?: 'start' | 'end';
|
|
278
296
|
/**
|
|
279
297
|
* Schedules a background refetch of queries this rule mutated. Leave off
|
|
@@ -341,7 +359,9 @@ type DerivedQueryContext = {
|
|
|
341
359
|
/**
|
|
342
360
|
* What caused derivation to run.
|
|
343
361
|
* `sticky-offline` means a query that was derived offline is still sticking
|
|
344
|
-
* to the local derived view after reconnect, until
|
|
362
|
+
* to the local derived view after reconnect, until it is invalidated: by
|
|
363
|
+
* the app, or by the automatic revalidation that runs once the offline
|
|
364
|
+
* session recovered (queued mutations replayed).
|
|
345
365
|
*/
|
|
346
366
|
deriveSource: DerivedQuerySource;
|
|
347
367
|
};
|
|
@@ -393,6 +413,28 @@ type OfflineUploadProgress = {
|
|
|
393
413
|
loadedBytes?: number; /** Total byte count, when available from the transport. */
|
|
394
414
|
totalBytes?: number;
|
|
395
415
|
};
|
|
416
|
+
/** Arguments for staging a session-scoped offline upload. */
|
|
417
|
+
type SaveOfflineUploadArgs = {
|
|
418
|
+
/** Stable upload id referenced by offline operation inputs. */id: string; /** File to stage until it can be uploaded. */
|
|
419
|
+
file: Blob | File;
|
|
420
|
+
/**
|
|
421
|
+
* App-defined, JSON-serializable metadata persisted with the upload. It is
|
|
422
|
+
* handed to the session `upload` transport and exposed on the `OfflineUpload`
|
|
423
|
+
* status entries. Saving over an existing id stores exactly this value, so
|
|
424
|
+
* omitting it leaves the upload without metadata.
|
|
425
|
+
*/
|
|
426
|
+
metadata?: ValidPayload;
|
|
427
|
+
};
|
|
428
|
+
/** Arguments for replacing the file of a staged session-scoped offline upload. */
|
|
429
|
+
type ReplaceOfflineUploadArgs = {
|
|
430
|
+
/** Id of the staged upload to replace. */id: string; /** New file for the upload. */
|
|
431
|
+
file: Blob | File;
|
|
432
|
+
/**
|
|
433
|
+
* New metadata for the upload. Omit it to keep the metadata already saved
|
|
434
|
+
* for this id.
|
|
435
|
+
*/
|
|
436
|
+
metadata?: ValidPayload;
|
|
437
|
+
};
|
|
396
438
|
/** Public metadata for a file staged for offline mutation replay. */
|
|
397
439
|
type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
398
440
|
/** Stable upload id used by offline operation inputs. */id: string; /** Session key that owns this upload. */
|
|
@@ -409,6 +451,12 @@ type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
|
409
451
|
lastError?: {
|
|
410
452
|
message: string;
|
|
411
453
|
};
|
|
454
|
+
/**
|
|
455
|
+
* App-defined metadata saved with the upload through `saveOfflineUpload` /
|
|
456
|
+
* `replaceOfflineUpload`. It is persisted with the upload record, so it is
|
|
457
|
+
* restored from storage after a reload and must be narrowed before use.
|
|
458
|
+
*/
|
|
459
|
+
metadata?: ValidPayload;
|
|
412
460
|
};
|
|
413
461
|
/** Persisted offline upload record including the staged file object. */
|
|
414
462
|
type OfflineStoredUploadRecord<TResolvedRef extends ValidPayload = ValidPayload> = OfflineUpload<TResolvedRef> & {
|
|
@@ -429,7 +477,17 @@ type OfflineUploadAdapter = {
|
|
|
429
477
|
type OfflineUploadTransportContext = {
|
|
430
478
|
/** Stable upload id being transported. */id: string; /** Session key that owns this upload. */
|
|
431
479
|
sessionKey: string; /** File to upload. */
|
|
432
|
-
file: File;
|
|
480
|
+
file: File;
|
|
481
|
+
/**
|
|
482
|
+
* App-defined metadata saved with this upload, for request parameters that
|
|
483
|
+
* differ per upload (target kind, parent ids, ...). `undefined` when the
|
|
484
|
+
* upload was staged without metadata, which is always the case for files
|
|
485
|
+
* attached directly to a mutation with its `upload` option.
|
|
486
|
+
*
|
|
487
|
+
* The value is restored from storage, so it is typed as an unvalidated
|
|
488
|
+
* JSON-safe payload: parse it (e.g. with a `runcheck` schema) before use.
|
|
489
|
+
*/
|
|
490
|
+
metadata?: ValidPayload; /** Reports upload progress back to TSDF. */
|
|
433
491
|
onProgress: (progress: OfflineUploadProgress) => void;
|
|
434
492
|
};
|
|
435
493
|
/** Upload handling config for an offline session. */
|
|
@@ -768,14 +826,8 @@ type OfflineSession<TUploadRef extends ValidPayload = ValidPayload> = {
|
|
|
768
826
|
getOfflineUploads: () => readonly OfflineUpload<TUploadRef>[]; /** Resolves a staged upload id to its latest final ref, uploading first if needed. */
|
|
769
827
|
resolveOfflineUpload: (id: string) => Promise<TUploadRef>; /** Resolves multiple staged upload ids to their latest final refs. */
|
|
770
828
|
resolveOfflineUploads: (ids: readonly string[]) => Promise<Record<string, TUploadRef>>; /** Saves a session-scoped upload locally for later dependency resolution or ref usage. */
|
|
771
|
-
saveOfflineUpload: (args:
|
|
772
|
-
|
|
773
|
-
file: Blob | File;
|
|
774
|
-
}) => Promise<void>; /** Replaces a previously stored session-scoped upload. */
|
|
775
|
-
replaceOfflineUpload: (args: {
|
|
776
|
-
id: string;
|
|
777
|
-
file: Blob | File;
|
|
778
|
-
}) => Promise<void>; /** Loads a previously stored session-scoped upload. */
|
|
829
|
+
saveOfflineUpload: (args: SaveOfflineUploadArgs) => Promise<void>; /** Replaces a previously stored session-scoped upload, keeping its metadata unless new metadata is passed. */
|
|
830
|
+
replaceOfflineUpload: (args: ReplaceOfflineUploadArgs) => Promise<void>; /** Loads a previously stored session-scoped upload. */
|
|
779
831
|
loadOfflineUpload: (id: string) => Promise<File | null>; /** Deletes a stored upload when it is no longer referenced. */
|
|
780
832
|
deleteOfflineUpload: (id: string) => Promise<void>; /** React hook subscribing to the session's global offline status. */
|
|
781
833
|
useOfflineStatus: () => GlobalOfflineStatus; /** React hook subscribing to the session's aggregated offline entities. */
|
|
@@ -1497,6 +1549,44 @@ declare class OfflineResolutionConflictParseError extends Error {
|
|
|
1497
1549
|
validationError?: SchemaValidationError;
|
|
1498
1550
|
});
|
|
1499
1551
|
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Generic resolution actions that `storeManager.resolveOfflineResolution(...)`
|
|
1554
|
+
* can apply to any resolution of the session without operation-specific input.
|
|
1555
|
+
*
|
|
1556
|
+
* - `retry` - Requeues a `retry-exhausted` record (and its retryable
|
|
1557
|
+
* descendants) for another replay attempt.
|
|
1558
|
+
* - `discard` - Drops the record, its queued mutation, and its dependents.
|
|
1559
|
+
*/
|
|
1560
|
+
type OfflineResolutionGenericAction = 'retry' | 'discard';
|
|
1561
|
+
/**
|
|
1562
|
+
* Failure code returned by `storeManager.resolveOfflineResolution(...)`.
|
|
1563
|
+
*
|
|
1564
|
+
* - `offline-not-configured` - The manager was created without `offlineSession`.
|
|
1565
|
+
* - `resolution-not-found` - No resolution with this id exists in the active
|
|
1566
|
+
* session, e.g. it was already resolved or the session is logged out. Also
|
|
1567
|
+
* returned when another tab created the record after this tab's store
|
|
1568
|
+
* loaded its resolutions.
|
|
1569
|
+
* - `store-not-registered` - The store that owns the resolution was not created
|
|
1570
|
+
* with this manager (yet), so the action cannot be applied from here.
|
|
1571
|
+
* - `retry-not-supported` - `retry` was requested for a `conflict` record;
|
|
1572
|
+
* conflicts are resolved with `discard` or with the owning store's
|
|
1573
|
+
* `requeue` / `commit` actions.
|
|
1574
|
+
* - `resolution-blocked` - The resolution is blocked by parent resolutions
|
|
1575
|
+
* (`blockedByResolutionIds`) that must be resolved first.
|
|
1576
|
+
* - `action-failed` - The owning store failed while applying the action; the
|
|
1577
|
+
* original error is available in `cause`.
|
|
1578
|
+
*/
|
|
1579
|
+
type OfflineResolutionActionErrorCode = 'offline-not-configured' | 'resolution-not-found' | 'store-not-registered' | 'retry-not-supported' | 'resolution-blocked' | 'action-failed';
|
|
1580
|
+
/** Error returned when a manager-level offline resolution action is not applied. */
|
|
1581
|
+
declare class OfflineResolutionActionError extends Error {
|
|
1582
|
+
/** Reason the action was not applied. */
|
|
1583
|
+
code: OfflineResolutionActionErrorCode;
|
|
1584
|
+
/** Resolution id the action was requested for. */
|
|
1585
|
+
resolutionId: string;
|
|
1586
|
+
/** Store that owns the resolution, when the resolution was found. */
|
|
1587
|
+
storeName?: string;
|
|
1588
|
+
constructor(code: OfflineResolutionActionErrorCode, resolutionId: string, storeName?: string, cause?: Error);
|
|
1589
|
+
}
|
|
1500
1590
|
//#endregion
|
|
1501
1591
|
//#region src/persistentStorage/types.d.ts
|
|
1502
1592
|
/** Logical namespaces used by managed async persistent storage. */
|
|
@@ -1569,7 +1659,15 @@ type AsyncStorageDiscoveredScope = {
|
|
|
1569
1659
|
};
|
|
1570
1660
|
/** Low-level async backend contract implemented by custom storage drivers. */
|
|
1571
1661
|
type AsyncStorageDriver = {
|
|
1572
|
-
/**
|
|
1662
|
+
/**
|
|
1663
|
+
* Stable id of the storage this driver reads and writes, unique among the
|
|
1664
|
+
* app's adapters and the same on every page load (for example
|
|
1665
|
+
* `indexedDb:<database name>`). TSDF uses it to remember one-time
|
|
1666
|
+
* maintenance across page loads: stores listed in the store manager's
|
|
1667
|
+
* `removedStores` can only be cleaned from adapters whose driver has one.
|
|
1668
|
+
*/
|
|
1669
|
+
readonly storageId?: string; /** Mutable debug logger used by concrete adapters to emit operation timings. */
|
|
1670
|
+
debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
|
|
1573
1671
|
logger?: TSDFDebugLogger; /** Read a single raw record from a logical namespace. */
|
|
1574
1672
|
get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
|
|
1575
1673
|
set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
|
|
@@ -1733,4 +1831,4 @@ type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPay
|
|
|
1733
1831
|
/** Persistent storage config for ListQueryStore. */
|
|
1734
1832
|
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>;
|
|
1735
1833
|
//#endregion
|
|
1736
|
-
export {
|
|
1834
|
+
export { OfflineResolutionConflictParseError as $, TSFDUseListQueryReturn as $t, DefineListQueryOfflineOperations as A, OfflineUploadTransportContext as At, OfflineEntityMutationKind as B, ListQueryUseMultipleItemsQuery as Bt, PersistentStorageSchema as C, TSDFFocusDebugOperation as Cn, OfflineSessionUploadsConfig as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadProgress as Dt, CollectionOfflineEntityRef as E, OfflineUploadAdapter as Et, ListQueryOfflineEntityRef as F, DerivedQuerySource as Ft, OfflineMutationQueueingPolicy as G, OptimisticListUpdate as Gt, OfflineMutationInput as H, OffsetPaginationConfig as Ht, ListQueryOfflineOperationDefinition as I, FetchListFnReturn as It, OfflineReplayRetryConfig as J, QueryStatus as Jt, OfflineOperationKind as K, PartialResourcesConfig as Kt, OfflineAccumulationConfig as L, FetchListFnReturnItem as Lt, DocumentOfflineOperationDefinition as M, SaveOfflineUploadArgs as Mt, GlobalOfflineEntity as N, DerivedQueriesConfig as Nt, DefineCollectionOfflineOperations as O, OfflineUploadSource as Ot, GlobalOfflineStatus as P, DerivedQueryContext as Pt, OfflineResolutionActionForOperation as Q, TSFDUseListItemReturn as Qt, OfflineAccumulationMergeContext as R, FieldsInput as Rt, PersistentStoragePreloadResult as S, TSDFDebugLogger as Sn, OfflineOperationUploadsContext as St, AnyOfflineOperationDefinition as T, OfflineUpload as Tt, OfflineMutationQueueingCause as U, OnListQueryInvalidate as Ut, OfflineMutationDescriptor as V, ListQueryUseMultipleListQueriesQuery as Vt, OfflineMutationQueueingConfig as W, OnListQueryItemInvalidate as Wt, OfflineResolutionActionError as X, TSFDListQuery as Xt, OfflineResolutionAction as Y, TSDFItemQuery as Yt, OfflineResolutionActionErrorCode as Z, TSFDListQueryState as Zt, ListQueryOfflineOperationsConfig as _, ScheduleFetchOptions as _n, OperationResult as _t, AsyncStorageMetadataOrder as a, StoreFetchError as an, OfflineRetryExhaustedResolutionAction as at, PersistentStorageDataSchema as b, TSDFDebugLogEntry as bn, defaultOfflineRuntimeConfig as bt, AsyncStorageNamespaceCommitUpsert as c, TSDFStatus as cn, OfflineSession as ct, AsyncStorageNamespaceKind as d, ValidStoreState as dn, OfflineSyncState as dt, TSFDUsePendingOfflineItemsReturn as en, OfflineResolutionConflictParseErrorCode as et, AsyncStorageNamespaceScope as f, fetchTypePriority as fn, OfflineTempEntitiesConfig as ft, DocumentPersistentStorageConfig as g, RequestSchedulerEvents as gn, OperationConflict as gt, ConvertedPersistentStorageDataSchema as h, RequestSchedulerEventData as hn, OfflineTempEntityPendingEntry as ht, AsyncStorageDriverSetEntry as i, StoreError as in, OfflineResolutionRecordForStore as it, DefineOfflineOperation as j, ReplaceOfflineUploadArgs as jt, DefineDocumentOfflineOperations as k, OfflineUploadState as kt, AsyncStorageNamespaceGetResult as l, UnwrapTSDFResult as ln, OfflineSessionConfig as lt, CollectionPersistentStorageConfig as m, FetchType as mn, OfflineTempEntityConfig as mt, AsyncStorageDiscoveredScope as n, MutationSkipped as nn, OfflineResolutionRecord as nt, AsyncStorageNamespaceCommitArgs as o, StoreMutationError as on, OfflineRuntimeConfig as ot, AsyncStorageReadOptions as p, mutationSkipped as pn, OfflineTempEntitiesReconciliation as pt, OfflineQueueEntry as q, QueryFetchPayload as qt, AsyncStorageDriver as r, PayloadDebounce as rn, OfflineResolutionRecordForOperation as rt, AsyncStorageNamespaceCommitTouch as s, StoreMutationErrorOptions as sn, OfflineRuntimeConfigUpdate as st, AsyncStorageAdapter as t, MaybeTSDFResult as tn, OfflineResolutionGenericAction as tt, AsyncStorageNamespaceHandle as u, ValidPayload as un, OfflineSupersedeConfig as ut, ListQueryPersistentStorageConfig as v, ScheduleFetchResults as vn, ParsedOfflineResolutionConflictResultForOperation as vt, StorageAdapter as w, TSDFLoggerOptions as wn, OfflineStoredUploadRecord as wt, PersistentStorageErrorHandler as x, TSDFDebugLogLevel as xn, OfflineMutationUploadsInput as xt, PersistentStorageBaseConfig as y, TSDFDebugLogArea as yn, ParsedOfflineResolutionConflictResultForStore as yt, OfflineConflictResolutionAction as z, FieldsOption as zt };
|
package/docs/list-query-store.md
CHANGED
|
@@ -194,6 +194,7 @@ Behavior:
|
|
|
194
194
|
- `deriveQuery(...)` receives `{ fields, isOfflineMode, deriveSource }`
|
|
195
195
|
- `fields` lets derivation opt out of partial-resource queries when local data is insufficient
|
|
196
196
|
- `deriveSource` is `'online'`, `'offline'`, or `'sticky-offline'`
|
|
197
|
+
- A query derived offline keeps its derived view after reconnecting (`'sticky-offline'`) until it is invalidated, which also happens automatically once the offline session recovered (queued mutations replayed)
|
|
197
198
|
- Derived results expose `isDerived: true`
|
|
198
199
|
- Derived results always expose `hasMore: false`
|
|
199
200
|
- Derived results do not create `state.queries[queryKey]`
|
package/docs/offline.md
CHANGED
|
@@ -105,6 +105,22 @@ await userStore.performMutation(
|
|
|
105
105
|
|
|
106
106
|
When the online mutation succeeds, the result value is `{ kind: 'online', data }`. When TSDF queues the mutation for offline replay, the result value is `{ kind: 'queued' }`.
|
|
107
107
|
|
|
108
|
+
A mutation is also queued while online when older mutations for the same entities (the operation's `getEntityRefs`) or for the entities it depends on (`dependsOn`), or queued mutations that depend on an entity it changes (e.g. a queued subfolder creation and a delete of its folder), are still waiting in the queue, for example right after reconnecting while the replay is in flight. Sent on its own it would reach the server before them (and be overwritten, or reference an entity the server does not have yet), so it joins the queue and is replayed in the order the user made the changes.
|
|
109
|
+
|
|
110
|
+
Queued mutations and pending resolutions are persisted through the store's own `persistentStorage.adapter`, and the cached entries they reference are protected from cache expiry until the queue is replayed or discarded. They are not migrated when a store's adapter changes: let the queue drain first. See [Changing a store's adapter](./persistent-storage.md#changing-a-stores-adapter).
|
|
111
|
+
|
|
112
|
+
## Revalidation After Recovering
|
|
113
|
+
|
|
114
|
+
While the session is in offline mode, automatic revalidations that could only fail are held: `onTransportReconnect()` signals and window-focus revalidations only re-check connectivity (`network.getIsOffline`) instead of refetching, and cached data stays visible. When the re-check finds the connection back, the session leaves offline mode and the stores revalidate as described below.
|
|
115
|
+
|
|
116
|
+
Each store attached to the manager revalidates by itself once it recovers, without the app having to invalidate anything:
|
|
117
|
+
|
|
118
|
+
- the session left offline mode, and
|
|
119
|
+
- its queued mutations finished replaying (data fetched earlier could predate them), and
|
|
120
|
+
- the store has no change left waiting for a manual resolution (a refetch would replace the local changes the user still has to decide on; resolving or discarding them triggers the revalidation).
|
|
121
|
+
|
|
122
|
+
Mounted data refetches right away, unmounted data on its next mount. Stores with `usesRealTimeUpdates` revalidate with `realtimeUpdate` priority, other stores with `highPriority`. Stores with `usesRealTimeUpdates` first wait one `transportReconnectCooldownMs` (2s by default): the app's transport usually reconnects right after the network comes back, and the `onTransportReconnect()` call in that window runs a single revalidation for both. Without a reconnect, the store revalidates when the cooldown ends, or right away when discarding a change refetches the store in the meantime. Tabs that are not focused revalidate when they get focus. Items that only exist locally (offline creations not sent yet) are skipped by invalidations, since there is nothing to fetch for them.
|
|
123
|
+
|
|
108
124
|
## Operation Definitions
|
|
109
125
|
|
|
110
126
|
All offline operations define:
|
|
@@ -144,13 +160,58 @@ await userStore.resolveOfflineResolution(resolutions[0].id, 'renameUser', {
|
|
|
144
160
|
|
|
145
161
|
Supported resolution actions include:
|
|
146
162
|
|
|
147
|
-
- `discard` - Drop the resolution record.
|
|
163
|
+
- `discard` - Drop the resolution record. The optimistic changes of the discarded mutation cannot be rolled back locally, so TSDF refetches what the operation referenced (`getEntityRefs`): the document, the collection item, or the list query item together with the store's lists (the change may have moved or removed the row). An entity that other changes still wait for a decision on is not refetched, since the refetch would replace those changes: it is revalidated once the last one is handled. Likewise, while other changes of a list query store still wait for a manual resolution, only the item is refetched: its lists are revalidated once the last one is handled. Discarding a temp create removes the temp entity and everything queued on top of it; existing entities changed on top of it are refetched.
|
|
148
164
|
- `requeue` - Queue replacement input for an operation conflict.
|
|
149
165
|
- `commit` - Accept an externally completed resolution result.
|
|
150
166
|
- `retry` - Retry a retry-exhausted record.
|
|
151
167
|
|
|
168
|
+
A mutation that exhausted its replay retries leaves the queue when it becomes a resolution record, so the mutations queued behind it keep replaying; only the ones that depend on it (queued on top of its temp entity) wait with it.
|
|
169
|
+
|
|
152
170
|
Use `parseOfflineResolutionConflict(resolution)` to narrow a persisted resolution back to the operation-specific conflict/input type before rendering a manual resolution UI.
|
|
153
171
|
|
|
172
|
+
### Resolving From A Session-Wide UI
|
|
173
|
+
|
|
174
|
+
An app-wide "sync problems" panel that lists `storeManager.useOfflineResolutions()` does not need to import every store to offer Retry / Discard. The manager applies the generic actions to any resolution of the session by finding the store that owns it:
|
|
175
|
+
|
|
176
|
+
```tsx
|
|
177
|
+
function SyncProblems() {
|
|
178
|
+
const resolutions = storeManager.useOfflineResolutions();
|
|
179
|
+
|
|
180
|
+
async function resolve(id: string, action: 'retry' | 'discard') {
|
|
181
|
+
const result = await storeManager.resolveOfflineResolution(id, action);
|
|
182
|
+
if (!result.ok) showToast(result.error.message);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return resolutions.map((resolution) => {
|
|
186
|
+
const isBlocked = resolution.blockedResolutionCount > 0;
|
|
187
|
+
|
|
188
|
+
return (
|
|
189
|
+
<SyncProblemRow
|
|
190
|
+
key={resolution.id}
|
|
191
|
+
resolution={resolution}
|
|
192
|
+
canRetry={resolution.kind === 'retry-exhausted' && !isBlocked}
|
|
193
|
+
canDiscard={!isBlocked}
|
|
194
|
+
onRetry={() => resolve(resolution.id, 'retry')}
|
|
195
|
+
onDiscard={() => resolve(resolution.id, 'discard')}
|
|
196
|
+
/>
|
|
197
|
+
);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
The behavior is the same as calling the owning store's `resolveOfflineResolution(id, operation, { action })`, including retrying retryable descendants and discarding dependents. Only `retry` and `discard` are available here; `requeue` and `commit` need operation-typed input and stay on the store API.
|
|
203
|
+
|
|
204
|
+
Failures are returned as a `Result` instead of thrown. `result.error` is an `OfflineResolutionActionError` with the `resolutionId`, the owning `storeName` (when known), and a `code`:
|
|
205
|
+
|
|
206
|
+
| `code` | Meaning |
|
|
207
|
+
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
208
|
+
| `resolution-not-found` | No resolution with this id in the active session, e.g. it was already resolved or the session is logged out. It is also returned when another tab created the record after this tab's store loaded its resolutions; act on it from the tab that created it or after a reload. |
|
|
209
|
+
| `store-not-registered` | The owning store was not created with this manager (yet). Resolutions are shared by the whole session, including other tabs, so a record can be listed before its store exists here. |
|
|
210
|
+
| `retry-not-supported` | `retry` was requested for a `conflict` record. Conflicts are resolved with `discard`, or with `requeue` / `commit` on the store API. |
|
|
211
|
+
| `resolution-blocked` | The record is blocked by parent resolutions (`blockedByResolutionIds`). Resolve the parents first. |
|
|
212
|
+
| `offline-not-configured` | The manager was created without `offlineSession`. |
|
|
213
|
+
| `action-failed` | The owning store failed while applying the action. The original error is in `error.cause`. |
|
|
214
|
+
|
|
154
215
|
## Reading Offline State
|
|
155
216
|
|
|
156
217
|
Use manager-level APIs for session-wide UI:
|
|
@@ -161,6 +222,8 @@ const entities = storeManager.useOfflineEntities();
|
|
|
161
222
|
const resolutions = storeManager.useOfflineResolutions();
|
|
162
223
|
```
|
|
163
224
|
|
|
225
|
+
`storeManager.resolveOfflineResolution(id, 'retry' | 'discard')` acts on any of those resolutions without the owning store instance (see [Resolving From A Session-Wide UI](#resolving-from-a-session-wide-ui)).
|
|
226
|
+
|
|
164
227
|
Equivalent global helpers are exported for code that only has a session key:
|
|
165
228
|
|
|
166
229
|
```ts
|
|
@@ -196,8 +259,8 @@ storeManager.resetOfflineRuntimeConfig();
|
|
|
196
259
|
|
|
197
260
|
Configure uploads on `offlineSession.uploads` when queued mutations depend on local files. The manager exposes upload helpers:
|
|
198
261
|
|
|
199
|
-
- `saveOfflineUpload({ id, file })`
|
|
200
|
-
- `replaceOfflineUpload({ id, file })`
|
|
262
|
+
- `saveOfflineUpload({ id, file, metadata? })`
|
|
263
|
+
- `replaceOfflineUpload({ id, file, metadata? })`
|
|
201
264
|
- `loadOfflineUpload(id)`
|
|
202
265
|
- `deleteOfflineUpload(id)`
|
|
203
266
|
- `resolveOfflineUpload(id)`
|
|
@@ -205,3 +268,48 @@ Configure uploads on `offlineSession.uploads` when queued mutations depend on lo
|
|
|
205
268
|
- `useOfflineUploads()`
|
|
206
269
|
|
|
207
270
|
Operations can declare `dependsOnUploads({ input })` and then read resolved upload refs from `execute({ uploads })`. `opfsOfflineUploadAdapter` is exported as a built-in OPFS-backed upload adapter.
|
|
271
|
+
|
|
272
|
+
### Upload metadata
|
|
273
|
+
|
|
274
|
+
The session has a single `upload` transport, so uploads that need different request parameters (target kind, parent ids, ...) carry them as `metadata` instead of encoding them in the upload id:
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
const uploadMetadataSchema = rc_discriminated_union('kind', {
|
|
278
|
+
chat: { chatId: rc_string },
|
|
279
|
+
record: { tableId: rc_string },
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
const storeManager = createStoreManager({
|
|
283
|
+
getSessionKey: () => currentTenantId ?? false,
|
|
284
|
+
errorNormalizer: normalizeError,
|
|
285
|
+
offlineSession: {
|
|
286
|
+
uploads: {
|
|
287
|
+
adapter: opfsOfflineUploadAdapter,
|
|
288
|
+
upload: ({ file, metadata, onProgress }) => {
|
|
289
|
+
// Uploads staged without metadata (direct mutation uploads, uploads
|
|
290
|
+
// saved by older versions) use the default request.
|
|
291
|
+
if (metadata === undefined) return uploadFile(file, onProgress);
|
|
292
|
+
|
|
293
|
+
// Restored from storage: validate before use.
|
|
294
|
+
const target = rc_parse(metadata, uploadMetadataSchema).unwrap();
|
|
295
|
+
|
|
296
|
+
return target.kind === 'chat'
|
|
297
|
+
? uploadChatFile(target.chatId, file, onProgress)
|
|
298
|
+
: uploadRecordFile(target.tableId, file, onProgress);
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
await storeManager.saveOfflineUpload({
|
|
305
|
+
id: attachmentId,
|
|
306
|
+
file,
|
|
307
|
+
metadata: { kind: 'chat', chatId },
|
|
308
|
+
});
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
- `metadata` is optional and must be a JSON-serializable `ValidPayload` (`string`, `number`, or a plain object).
|
|
312
|
+
- It is persisted with the upload record, so it survives reloads, is passed to the `upload` transport both on replay and on `resolveOfflineUpload(s)`, and is exposed as `metadata` on the `OfflineUpload` entries returned by `getOfflineUploads()` / `useOfflineUploads()`.
|
|
313
|
+
- Because it is read back from storage, it is typed as an unvalidated `ValidPayload`: parse it with a schema before using it, as above. Uploads staged without metadata reach the transport with `metadata: undefined`, so handle that case explicitly. This includes the ones persisted by older versions and files attached directly to a mutation with its `upload` option, which can't carry metadata.
|
|
314
|
+
- `saveOfflineUpload` stores exactly the metadata it receives. `replaceOfflineUpload` keeps the metadata already saved for that id unless new `metadata` is passed. Both fail while that upload is queued or being sent.
|
|
315
|
+
- Custom `OfflineUploadAdapter` implementations must persist and restore the record's `metadata` field together with the rest of the record.
|
|
@@ -74,7 +74,41 @@ filterItem: (item) => {
|
|
|
74
74
|
|
|
75
75
|
- When `filterItem` returns `true` and the item is not in the query, it's added at the position specified by `appendNewTo`
|
|
76
76
|
- When `filterItem` returns `false` and the item is in the query, it's removed
|
|
77
|
-
- When `filterItem` returns `null`, the rule is skipped for that item
|
|
77
|
+
- When `filterItem` returns `null`, the rule is skipped for that item in that query
|
|
78
|
+
|
|
79
|
+
`filterItem` is called once for each matching query and receives a context object as second argument:
|
|
80
|
+
|
|
81
|
+
| Field | Description |
|
|
82
|
+
| -------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
|
83
|
+
| `queryPayload` | Payload of the query being evaluated |
|
|
84
|
+
| `itemPayload` | Payload of the item being evaluated |
|
|
85
|
+
| `isInQuery` | Whether the item is in the query right before the rule is applied. Computed on first read; read it while `filterItem` is running |
|
|
86
|
+
|
|
87
|
+
With the query payload, one rule can decide membership for every query, instead of one rule per filter combination:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
optimisticListUpdates: [
|
|
91
|
+
{
|
|
92
|
+
queries: () => true,
|
|
93
|
+
filterItem: (task, { queryPayload }) =>
|
|
94
|
+
taskBelongsToQuery(task, queryPayload),
|
|
95
|
+
},
|
|
96
|
+
];
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Return `null` for queries whose filters depend on data the client cannot evaluate (server-side search, permissions). `isInQuery` tells if the item already passed those filters on the server:
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
filterItem: (task, { queryPayload, isInQuery }) => {
|
|
103
|
+
const matchesLocalFilters = taskMatchesLocalFilters(task, queryPayload);
|
|
104
|
+
|
|
105
|
+
if (!queryPayload.search) return matchesLocalFilters;
|
|
106
|
+
|
|
107
|
+
// In the query: it already matched the search, so only the local filters
|
|
108
|
+
// can remove it. Not in the query: no way to know, keep as is.
|
|
109
|
+
return isInQuery ? matchesLocalFilters : null;
|
|
110
|
+
};
|
|
111
|
+
```
|
|
78
112
|
|
|
79
113
|
### appendNewTo
|
|
80
114
|
|
|
@@ -117,6 +151,8 @@ Schedules a background refetch of queries this rule mutated.
|
|
|
117
151
|
invalidateQueries: true;
|
|
118
152
|
```
|
|
119
153
|
|
|
154
|
+
With `invalidateQueries` enabled, a rule with `sort` refetches every matching query that contains the updated item on each update, even when the optimistic order did not change — the client can't tell whether the server order did.
|
|
155
|
+
|
|
120
156
|
## When Rules Are Applied
|
|
121
157
|
|
|
122
158
|
Optimistic list updates are triggered by:
|
|
@@ -143,6 +143,8 @@ If you enable `showPartialAsRefetching`, the hook exposes `loadingFields` with t
|
|
|
143
143
|
|
|
144
144
|
Invalidations are refetches, not new loads: when an invalidation (full or per-field) marks cached data as stale, hooks whose requested fields are still present keep the stale data visible while the refetch is in flight (with a `refetching` status when `returnRefetchingStatus` is enabled). Data is only hidden behind `loading` when a requested field was genuinely never loaded.
|
|
145
145
|
|
|
146
|
+
The same holds across reloads with persistent storage: an item invalidated before the page was closed is persisted with every field its snapshot still holds, and is restored as stale cached data: shown right away, then refetched on mount (a hook with a `fields` selection refetches only the fields it requests). An invalidated fully-loaded (`'*'`) item still satisfies `fields: '*'` reads from cache, which keeps it readable when the app is reopened offline.
|
|
147
|
+
|
|
146
148
|
## Fields in Scheduling and Fetching
|
|
147
149
|
|
|
148
150
|
Fields propagate through the scheduling and fetching APIs:
|
|
@@ -22,6 +22,7 @@ Exported from `tsdf`:
|
|
|
22
22
|
| `StorageAdapter` | `'local-sync'` or a managed async storage adapter |
|
|
23
23
|
| `DocumentPersistentStorageConfig` / `CollectionPersistentStorageConfig` / `ListQueryPersistentStorageConfig` | Store-level persistence config types |
|
|
24
24
|
| `createStoreManager(options)` | Creates the shared store manager used by all stores |
|
|
25
|
+
| `RemovedStore` | A deleted store listed in the manager's `removedStores` |
|
|
25
26
|
| `PersistentStoragePreloadResult<Payload>` | Return shape for preload methods |
|
|
26
27
|
| `localPersistentStorage` | Built-in localStorage helper used by the `'local-sync'` adapter |
|
|
27
28
|
| `clearSessionStorage(sessionKey, adapter)` | Clears all TSDF entries for one session/adapter |
|
|
@@ -62,6 +63,8 @@ Store-specific options:
|
|
|
62
63
|
| Collection Store | `payloadSchema`, `maxBytes`, `pinnedItems`, `ignoreItems` |
|
|
63
64
|
| List Query Store | `itemPayloadSchema`, `queryPayloadSchema`, `maxItemBytes`, `maxQueryBytes`, `maxQuerySize`, `pinnedItems`, `pinnedQueries`, `ignoreItems` |
|
|
64
65
|
|
|
66
|
+
> With [Partial Resources](./partial-resources.md), items are saved with only the fields loaded so far, and each restored item is validated against `schema`. Make the fields that hooks may leave out optional in the schema: an item saved without a required field is discarded when it is read back, so it is not available as cached data.
|
|
67
|
+
|
|
65
68
|
> `persistentStorage` automatically reuses the store's existing `id` for its storage namespace and the store manager's `getSessionKey` for session scoping. When `getSessionKey` returns `false`, no persistence operations run.
|
|
66
69
|
|
|
67
70
|
Enable `createStoreManager({ debugLogger: true, ... })` to inspect load, save/write, commit, clear, metadata, and offline protection persistence operations in development. Production-safe quota cleanup logs are emitted through the manager `logger` by default; they include the affected quota, configured byte budget, total unprotected bytes, and kept/evicted entry counts. Pass `logger: false` to disable them. Async adapters also emit timed `adapter-operation` entries with `durationMs` for concrete OPFS, IndexedDB, or custom driver work in development.
|
|
@@ -171,10 +174,12 @@ Use `createAsyncStorageAdapter(driver)` only when the built-in OPFS and IndexedD
|
|
|
171
174
|
A driver is responsible for storing raw records by logical namespace:
|
|
172
175
|
|
|
173
176
|
```ts
|
|
174
|
-
import { createAsyncStorageAdapter } from 'tsdf/async-storage';
|
|
175
177
|
import type { AsyncStorageDriver } from 'tsdf';
|
|
178
|
+
import { createAsyncStorageAdapter } from 'tsdf/async-storage';
|
|
176
179
|
|
|
177
180
|
const driver: AsyncStorageDriver = {
|
|
181
|
+
// Stable id, needed to list this adapter's deleted stores in `removedStores`
|
|
182
|
+
storageId: 'custom-store',
|
|
178
183
|
get: (scope, key) => customStore.get(scope, key),
|
|
179
184
|
set: (scope, key, value) => customStore.set(scope, key, value),
|
|
180
185
|
remove: (scope, key) => customStore.remove(scope, key),
|
|
@@ -191,7 +196,48 @@ const driver: AsyncStorageDriver = {
|
|
|
191
196
|
const customPersistentStorage = createAsyncStorageAdapter(driver);
|
|
192
197
|
```
|
|
193
198
|
|
|
194
|
-
Driver methods should preserve the JSON-compatible values TSDF gives them, isolate data by the full namespace scope, and implement bulk methods consistently with their single-record equivalents. `listScopes(...)` and `listScopesWithKnownRecordKeys(...)` are required for cleanup, session clearing, and offline protected-key restoration.
|
|
199
|
+
Driver methods should preserve the JSON-compatible values TSDF gives them, isolate data by the full namespace scope, and implement bulk methods consistently with their single-record equivalents. `listScopes(...)` and `listScopesWithKnownRecordKeys(...)` are required for cleanup, session clearing, and offline protected-key restoration. The optional `storageId` must stay the same across page loads and be unique among the app's adapters; it is only needed to list stores persisted with this adapter in the store manager's `removedStores`.
|
|
200
|
+
|
|
201
|
+
### Changing a store's adapter
|
|
202
|
+
|
|
203
|
+
Each adapter is a separate storage. A store only reads what was written through its current `adapter`, so after the adapter changes the store starts with an empty cache and refetches. Nothing is migrated between adapters.
|
|
204
|
+
|
|
205
|
+
Moving a store from `'local-sync'` to an async adapter:
|
|
206
|
+
|
|
207
|
+
- The first time the store runs with the async adapter, TSDF removes everything that store left in `localStorage` for the active session (cached entries and their metadata) during browser idle time. Other stores, other sessions and non-TSDF keys are not touched; entries a store left under another session key are only removed by the regular expiry while some store still uses `'local-sync'`.
|
|
208
|
+
- Detecting this costs one `localStorage.getItem` of a missing key per store namespace at startup for stores that never used `localStorage`; the removal only runs when that read finds something.
|
|
209
|
+
- Queued offline work is never deleted. Offline mutations and pending resolutions are stored through the store's adapter, so they do not follow the store to the new adapter and are only replayed while the store uses `'local-sync'`. When `localStorage` still holds any for the store, TSDF keeps all of that store's `localStorage` entries and reports an error through `onPersistentStorageError` on every page load. Let the offline queue drain before changing the adapter of an offline-enabled store, or roll the adapter back so the queue can replay; the leftovers are removed on the next load after the queue is empty.
|
|
210
|
+
- A tab still running the previous app version keeps working: it serves its data from memory and writes its entries to `localStorage` again. They are removed the next time the new version starts.
|
|
211
|
+
|
|
212
|
+
Moving a store from an async adapter to `'local-sync'`, or from one async adapter to another, does not clean the previous adapter. Its old entries are still removed by that adapter's regular expiry while another store keeps using it; once no store uses that adapter anymore, they stay there.
|
|
213
|
+
|
|
214
|
+
### Deleting a store
|
|
215
|
+
|
|
216
|
+
Deleting a store from the app leaves its persisted data behind: nothing reads it anymore, regular expiry only covers it while another store keeps using the same adapter, and it never removes list queries or offline data. Declare deleted stores in the store manager so TSDF removes their data:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
import { createStoreManager } from 'tsdf';
|
|
220
|
+
import { indexedDbPersistentStorage } from 'tsdf/indexed-db-storage';
|
|
221
|
+
|
|
222
|
+
const storeManager = createStoreManager({
|
|
223
|
+
// ...
|
|
224
|
+
removedStores: [
|
|
225
|
+
{ id: 'legacy-settings', adapter: 'local-sync' },
|
|
226
|
+
{ id: 'old-feed', adapter: indexedDbPersistentStorage },
|
|
227
|
+
],
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
- Each entry names the deleted store's `id` and the `adapter` it persisted with. Add one entry per adapter when the store used more than one. Naming the adapter lets TSDF clean it even when no remaining store uses it, without bundling or opening adapters the app does not import.
|
|
232
|
+
- Once, during browser idle time after startup, TSDF removes everything each listed store persisted with that adapter, in every session: cached entries and their metadata, offline entity records, and any queued offline mutations or pending resolutions. Other stores and non-TSDF keys are not touched.
|
|
233
|
+
- Unsent offline work can no longer be replayed once its store is deleted, so it is removed too, and the number of records dropped is reported once per store through the manager's `onPersistentStorageError`.
|
|
234
|
+
- TSDF then records each cleaned id and adapter pair in a small `localStorage` marker. Every later startup reads that marker once during idle time and stops there; apps without `removedStores` pay nothing. Adding an adapter for an id already cleaned from another adapter still cleans the new one. Entries can be dropped from `removedStores` once every user has run a version that includes them.
|
|
235
|
+
- When an adapter fails (for example a file it cannot delete), the error is reported through `onPersistentStorageError` and only that adapter is retried on the next page load; the other adapters stay marked as done.
|
|
236
|
+
- A store attached to the manager cannot use an id listed in `removedStores`: creating it throws, since the cleanup would remove its data.
|
|
237
|
+
- Custom async adapters are supported when created with `createAsyncStorageAdapter` from a driver with a `storageId`: a stable id, unique among the app's adapters, that TSDF uses to remember the cleanup across page loads. For other adapters TSDF reports an error through `onPersistentStorageError` on every page load and removes nothing, until the entry names a supported adapter.
|
|
238
|
+
- The cleanup runs once per id and adapter. A tab still running the previous app version can write the deleted store's entries again after the cleanup; those are only removed by the adapter's regular expiry while another store keeps using it.
|
|
239
|
+
- In `localStorage`, a store is found through its metadata entries, so a list-query store whose every cached query was empty (and that cached no items) is not found; those small query entries stay.
|
|
240
|
+
- Offline uploads belong to the session, not to a store, and are not removed.
|
|
195
241
|
|
|
196
242
|
## Example configuration
|
|
197
243
|
|
|
@@ -244,6 +290,8 @@ const settingsStore = createDocumentStore<Settings>({
|
|
|
244
290
|
- `local-sync`: ~1 week old entries
|
|
245
291
|
- `opfsPersistentStorage`: ~2 weeks old entries
|
|
246
292
|
- `indexedDbPersistentStorage`: ~2 weeks old entries
|
|
293
|
+
- Entries referenced by queued offline mutations are protected from expiry until that queued work is replayed or discarded.
|
|
294
|
+
- Expiry runs for an adapter only while at least one store uses it, and then covers every entry in that adapter, including ones left by stores that moved elsewhere. See [Changing a store's adapter](#changing-a-stores-adapter).
|
|
247
295
|
|
|
248
296
|
## Preload APIs
|
|
249
297
|
|
|
@@ -291,4 +339,4 @@ When the selected adapter does not support async preload, preload methods report
|
|
|
291
339
|
- `clearAllSessionStorage(sessionKey)`:
|
|
292
340
|
remove TSDF entries for one session across the built-in `local-sync`, OPFS, and IndexedDB adapters.
|
|
293
341
|
|
|
294
|
-
Use these on logout, user switch, or explicit privacy actions.
|
|
342
|
+
Use these on logout, user switch, or explicit privacy actions. They clear every store of the session, so do not use them to clean up after a deleted store: declare it in `removedStores` instead (see [Deleting a store](#deleting-a-store)).
|