tsdf 18.2.0 → 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.
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CapHC7zC.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CcdWYuhc.js";
2
2
  export { opfsPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-6OuHQ3d-.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-amwSWm_p.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-DDjEjIqQ.js";
1
+ import { t as AsyncStorageAdapter } from "./types-2UJIjziu.js";
2
2
 
3
3
  //#region src/persistentStorage/opfsPersistentStorage.d.ts
4
4
  declare const opfsPersistentStorage: AsyncStorageAdapter;
@@ -1,4 +1,4 @@
1
- import { $ as parseAsyncStorageRecordKey, J as getNamespaceId, Y as getPayloadRecordKey, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, y as emitTSDFDebugLog } from "./asyncStorageAdapter-YuIJ7hwm.js";
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) throw new Error("[TSDF] OPFS is unavailable in this environment.");
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
- const root = await this.#getRootDir();
474
- return sessionKey === void 0 ? await this.#listDirectoryEntries(root, OPFS_ROOT_DIR, cacheContext) : [{
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 });
@@ -359,7 +359,9 @@ type DerivedQueryContext = {
359
359
  /**
360
360
  * What caused derivation to run.
361
361
  * `sticky-offline` means a query that was derived offline is still sticking
362
- * to the local derived view after reconnect, until explicit invalidation.
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).
363
365
  */
364
366
  deriveSource: DerivedQuerySource;
365
367
  };
@@ -411,6 +413,28 @@ type OfflineUploadProgress = {
411
413
  loadedBytes?: number; /** Total byte count, when available from the transport. */
412
414
  totalBytes?: number;
413
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
+ };
414
438
  /** Public metadata for a file staged for offline mutation replay. */
415
439
  type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
416
440
  /** Stable upload id used by offline operation inputs. */id: string; /** Session key that owns this upload. */
@@ -427,6 +451,12 @@ type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
427
451
  lastError?: {
428
452
  message: string;
429
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;
430
460
  };
431
461
  /** Persisted offline upload record including the staged file object. */
432
462
  type OfflineStoredUploadRecord<TResolvedRef extends ValidPayload = ValidPayload> = OfflineUpload<TResolvedRef> & {
@@ -447,7 +477,17 @@ type OfflineUploadAdapter = {
447
477
  type OfflineUploadTransportContext = {
448
478
  /** Stable upload id being transported. */id: string; /** Session key that owns this upload. */
449
479
  sessionKey: string; /** File to upload. */
450
- file: File; /** Reports upload progress back to TSDF. */
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. */
451
491
  onProgress: (progress: OfflineUploadProgress) => void;
452
492
  };
453
493
  /** Upload handling config for an offline session. */
@@ -786,14 +826,8 @@ type OfflineSession<TUploadRef extends ValidPayload = ValidPayload> = {
786
826
  getOfflineUploads: () => readonly OfflineUpload<TUploadRef>[]; /** Resolves a staged upload id to its latest final ref, uploading first if needed. */
787
827
  resolveOfflineUpload: (id: string) => Promise<TUploadRef>; /** Resolves multiple staged upload ids to their latest final refs. */
788
828
  resolveOfflineUploads: (ids: readonly string[]) => Promise<Record<string, TUploadRef>>; /** Saves a session-scoped upload locally for later dependency resolution or ref usage. */
789
- saveOfflineUpload: (args: {
790
- id: string;
791
- file: Blob | File;
792
- }) => Promise<void>; /** Replaces a previously stored session-scoped upload. */
793
- replaceOfflineUpload: (args: {
794
- id: string;
795
- file: Blob | File;
796
- }) => 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. */
797
831
  loadOfflineUpload: (id: string) => Promise<File | null>; /** Deletes a stored upload when it is no longer referenced. */
798
832
  deleteOfflineUpload: (id: string) => Promise<void>; /** React hook subscribing to the session's global offline status. */
799
833
  useOfflineStatus: () => GlobalOfflineStatus; /** React hook subscribing to the session's aggregated offline entities. */
@@ -1515,6 +1549,44 @@ declare class OfflineResolutionConflictParseError extends Error {
1515
1549
  validationError?: SchemaValidationError;
1516
1550
  });
1517
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
+ }
1518
1590
  //#endregion
1519
1591
  //#region src/persistentStorage/types.d.ts
1520
1592
  /** Logical namespaces used by managed async persistent storage. */
@@ -1587,7 +1659,15 @@ type AsyncStorageDiscoveredScope = {
1587
1659
  };
1588
1660
  /** Low-level async backend contract implemented by custom storage drivers. */
1589
1661
  type AsyncStorageDriver = {
1590
- /** Mutable debug logger used by concrete adapters to emit operation timings. */debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
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. */
1591
1671
  logger?: TSDFDebugLogger; /** Read a single raw record from a logical namespace. */
1592
1672
  get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
1593
1673
  set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
@@ -1751,4 +1831,4 @@ type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPay
1751
1831
  /** Persistent storage config for ListQueryStore. */
1752
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>;
1753
1833
  //#endregion
1754
- export { OfflineResolutionRecord as $, StoreError as $t, DefineListQueryOfflineOperations as A, DerivedQuerySource as At, OfflineEntityMutationKind as B, OptimisticListUpdate as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, ListQueryUseMultipleItemsQuery as Ft, OfflineMutationQueueingPolicy as G, TSFDListQuery as Gt, OfflineMutationInput as H, QueryFetchPayload as Ht, ListQueryOfflineOperationDefinition as I, ListQueryUseMultipleListQueriesQuery as It, OfflineReplayRetryConfig as J, TSFDUseListQueryReturn as Jt, OfflineOperationKind as K, TSFDListQueryState as Kt, OfflineAccumulationConfig as L, OffsetPaginationConfig as Lt, DocumentOfflineOperationDefinition as M, FetchListFnReturnItem as Mt, GlobalOfflineEntity as N, FieldsInput as Nt, DefineCollectionOfflineOperations as O, DerivedQueriesConfig as Ot, GlobalOfflineStatus as P, FieldsOption as Pt, OfflineResolutionConflictParseErrorCode as Q, PayloadDebounce as Qt, OfflineAccumulationMergeContext as R, OnListQueryInvalidate as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, QueryStatus as Ut, OfflineMutationDescriptor as V, PartialResourcesConfig as Vt, OfflineMutationQueueingConfig as W, TSDFItemQuery as Wt, OfflineResolutionActionForOperation as X, MaybeTSDFResult as Xt, OfflineResolutionAction as Y, TSFDUsePendingOfflineItemsReturn as Yt, OfflineResolutionConflictParseError as Z, MutationSkipped as Zt, ListQueryOfflineOperationsConfig as _, TSDFDebugLogger as _n, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, ValidPayload as an, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, mutationSkipped as cn, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, RequestSchedulerEvents as dn, OfflineTempEntityConfig as dt, StoreFetchError as en, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, ScheduleFetchOptions as fn, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, TSDFDebugLogLevel as gn, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, TSDFDebugLogEntry as hn, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, UnwrapTSDFResult as in, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, FetchListFnReturn as jt, DefineDocumentOfflineOperations as k, DerivedQueryContext as kt, AsyncStorageNamespaceGetResult as l, FetchType as ln, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, TSDFDebugLogArea as mn, OperationResult as mt, AsyncStorageDiscoveredScope as n, StoreMutationErrorOptions as nn, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, ValidStoreState as on, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, ScheduleFetchResults as pn, OperationConflict as pt, OfflineQueueEntry as q, TSFDUseListItemReturn as qt, AsyncStorageDriver as r, TSDFStatus as rn, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, fetchTypePriority as sn, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, StoreMutationError as tn, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, RequestSchedulerEventData as un, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, TSDFFocusDebugOperation as vn, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, TSDFLoggerOptions as yn, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, OnListQueryItemInvalidate as zt };
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 };
@@ -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.
@@ -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)).
@@ -52,6 +52,7 @@ Options:
52
52
  | `debugLogger` | No | Enables verbose development-only browser-tab sync, focus revalidation, and persistent-storage debug logs. Pass `true` or a logger function. |
53
53
  | `logger` | No | Enables low-volume production-safe logs such as persistent-storage quota cleanup. Defaults to console logging; pass `false` to disable or a function to customize. |
54
54
  | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
55
+ | `removedStores` | No | Stores deleted from the app whose persisted data TSDF removes once, in every session. See [Deleting a store](./persistent-storage.md#deleting-a-store). |
55
56
 
56
57
  The session key is used by browser-tab sync, persistent storage, and offline state. Stores with the same `id` but different session keys are isolated.
57
58
 
@@ -92,7 +93,7 @@ storeManager.onTransportReconnect();
92
93
 
93
94
  - `getAllStoreIds()` returns registered logical store ids.
94
95
  - `resetAll(ignoreStores)` resets all registered stores except the ignored ids.
95
- - `onTransportReconnect()` signals a shared real-time transport reconnect to all registered stores.
96
+ - `onTransportReconnect()` signals a shared real-time transport reconnect to all registered stores. It is ignored while the offline session is in offline mode: stores revalidate by themselves when they recover (see [Revalidation After Recovering](./offline.md#revalidation-after-recovering)).
96
97
 
97
98
  Call each store's `dispose()` when the store instance is permanently discarded so it can unregister listeners and manager state.
98
99
 
@@ -111,7 +112,7 @@ const storeManager = createStoreManager({
111
112
  });
112
113
  ```
113
114
 
114
- Manager offline methods are safe to call even when no offline session is configured. In that case they return empty/default state, and upload helpers return `Result.err(...)` where applicable.
115
+ Manager offline methods are safe to call even when no offline session is configured. In that case they return empty/default state, and upload helpers and `resolveOfflineResolution(...)` return `Result.err(...)` where applicable.
115
116
 
116
117
  ## Offline Status APIs
117
118
 
@@ -137,23 +138,44 @@ Runtime controls:
137
138
  - `setOfflineRuntimeConfig(update)` returns a `Result<void, Error>`
138
139
  - `resetOfflineRuntimeConfig()` restores the static `offlineSession` controls
139
140
 
141
+ Resolution actions:
142
+
143
+ - `resolveOfflineResolution(resolutionId, 'retry' | 'discard')` applies a generic action to any resolution of the session by delegating to the registered store that owns it, so session-wide UI does not need the store instance or the operation name
144
+
145
+ ```ts
146
+ const result = await storeManager.resolveOfflineResolution(
147
+ resolution.id,
148
+ 'discard',
149
+ );
150
+ if (!result.ok) console.warn(result.error.code, result.error.message);
151
+ ```
152
+
153
+ It resolves to a `Result<void, OfflineResolutionActionError>` instead of throwing. `error.code` tells why the action was not applied: `resolution-not-found`, `store-not-registered` (the owning store was not created with this manager), `retry-not-supported` (conflict records), `resolution-blocked`, `offline-not-configured`, or `action-failed`. See [Offline](./offline.md#resolving-from-a-session-wide-ui) for details. `requeue` and `commit` stay on the owning store's `resolveOfflineResolution(...)`.
154
+
140
155
  ## Upload APIs
141
156
 
142
157
  When `offlineSession.uploads` is configured, the manager also owns session-scoped upload storage and resolution:
143
158
 
144
159
  ```ts
145
- await storeManager.saveOfflineUpload({ id: 'avatar', file });
160
+ await storeManager.saveOfflineUpload({
161
+ id: 'avatar',
162
+ file,
163
+ // Optional per-upload data for the session `upload` transport.
164
+ metadata: { kind: 'profile', userId },
165
+ });
146
166
  const resolved = await storeManager.resolveOfflineUpload('avatar');
147
167
  ```
148
168
 
149
169
  Upload methods:
150
170
 
151
- - `saveOfflineUpload({ id, file })`
152
- - `replaceOfflineUpload({ id, file })`
171
+ - `saveOfflineUpload({ id, file, metadata? })`
172
+ - `replaceOfflineUpload({ id, file, metadata? })` keeps the saved metadata unless new `metadata` is passed
153
173
  - `loadOfflineUpload(id)`
154
174
  - `deleteOfflineUpload(id)`
155
175
  - `resolveOfflineUpload(id)`
156
176
  - `resolveOfflineUploads(ids)`
157
177
  - `useOfflineUploads()`
158
178
 
179
+ `metadata` is a JSON-serializable `ValidPayload` persisted with the upload. The `upload` transport receives it in its context and `getOfflineUploads()` / `useOfflineUploads()` expose it on each `OfflineUpload`. See [Offline: Upload metadata](./offline.md#upload-metadata).
180
+
159
181
  Most upload methods return `Result` objects so UI can branch on `result.ok` without catching thrown errors.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "18.2.0",
3
+ "version": "18.3.0",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",