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.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as serializeJsonForStorage, B as getSessionProtectedKeysSnapshot, C as createShouldIgnoreItemPredicate, D as keepEntriesWithinByteBudget, E as isQuotaExceededError, F as isModeEffectivelyActive, G as parseCompactLocalStorageEntry, H as getNavigatorLockManager, I as isOfflineModeStatusValue, L as offlineItemEntityRefSchema, M as compactOfflineStatusSnapshotSchema, N as defaultOfflineRuntimeConfig, O as keepEntriesWithinByteBudgetDuringIdle, P as getIsOfflineModeFromStatus, R as offlineResolutionRecordSchema, S as getDefaultMaxBytesForScope, T as getSerializedStringSize, U as warnIfNavigatorLockUnavailable, V as setSessionProtectedKeysSnapshot, W as createCompactLocalStorageEntry, Y as getPayloadRecordKey, _ as getOfflineSessionStatusStorageKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, c as isAsyncStorageMetadataOfflineProtected, d as registerAsyncStartupStoreCleanup, et as parsePersistedAsyncNamespaceKind, f as removeAsyncStorageNamespaceEntriesIfUnchanged, g as OFFLINE_SESSION_STATUS_STORE_NAME, h as parseAsyncStorageNamespaceKind, it as scheduleIdleCleanup, j as OfflineResolutionConflictParseError, k as removeAsyncMaintenanceEntriesIfUnchanged, l as mergeManagedAsyncStorageCustomMetadata, m as unregisterAsyncStartupStoreCleanup, nt as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, o as getAsyncStorageMaintenanceRemoveBatchSize, p as serializeProtectedRef$1, r as buildPersistedStaticPolicy, rt as createIdleCleanupContext, s as getProtectedKeysFromMetadata, tt as serializeProtectedRef, u as readAsyncStorageNamespaceIndexStateUsingDriver, v as logPersistentStorageQuotaCleanup, w as createTimedKeySet, x as resolveTSDFLogger, y as emitTSDFDebugLog, z as clearSessionProtectedKeysSnapshot } from "./asyncStorageAdapter-YuIJ7hwm.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-6OuHQ3d-.js";
1
+ import { A as removeAsyncMaintenanceEntriesIfUnchanged, B as offlineResolutionRecordSchema, C as getDefaultMaxBytesForScope, D as isQuotaExceededError, E as getSerializedStringSize, F as defaultOfflineRuntimeConfig, G as warnIfNavigatorLockUnavailable, H as getSessionProtectedKeysSnapshot, I as getIsOfflineModeFromStatus, K as createCompactLocalStorageEntry, L as isModeEffectivelyActive, M as OfflineResolutionActionError, N as OfflineResolutionConflictParseError, O as keepEntriesWithinByteBudget, P as compactOfflineStatusSnapshotSchema, R as isOfflineModeStatusValue, S as resolveTSDFLogger, T as createTimedKeySet, U as setSessionProtectedKeysSnapshot, V as clearSessionProtectedKeysSnapshot, W as getNavigatorLockManager, Z as getPayloadRecordKey, _ as OFFLINE_SESSION_STATUS_STORE_NAME, a as estimateManagedAsyncStorageEntrySizeBytes, at as createIdleCleanupContext, b as emitTSDFDebugLog, c as getRemovableStoresAsyncStorage, d as readAsyncStorageNamespaceIndexStateUsingDriver, f as registerAsyncStartupStoreCleanup, g as parseAsyncStorageNamespaceKind, h as unregisterAsyncStartupStoreCleanup, it as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, j as serializeJsonForStorage, k as keepEntriesWithinByteBudgetDuringIdle, l as isAsyncStorageMetadataOfflineProtected, m as serializeProtectedRef$1, nt as parsePersistedAsyncNamespaceKind, o as getAsyncStorageMaintenanceRemoveBatchSize, ot as scheduleIdleCleanup, p as removeAsyncStorageNamespaceEntriesIfUnchanged, q as parseCompactLocalStorageEntry, r as buildPersistedStaticPolicy, rt as serializeProtectedRef, s as getProtectedKeysFromMetadata, st as scheduleInitialMaintenanceCleanup, u as mergeManagedAsyncStorageCustomMetadata, v as getOfflineSessionStatusStorageKey, w as createShouldIgnoreItemPredicate, x as getTSDFDebugTimingMs, y as logPersistentStorageQuotaCleanup, z as offlineItemEntityRefSchema } from "./asyncStorageAdapter-NrI38v4g.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-amwSWm_p.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
5
  import { deepEqual } from "@ls-stack/utils/deepEqual";
@@ -255,6 +255,8 @@ function createCompactListQueryLocalStorageEntry(entry) {
255
255
  //#region src/persistentStorage/localStorageMetadata.ts
256
256
  const METADATA_KEY_PREFIX = "tsdf._m.";
257
257
  const GLOBAL_MAINTENANCE_KEY = `${METADATA_KEY_PREFIX}g`;
258
+ /** `removedStores` entries whose persisted data was already removed. */
259
+ const REMOVED_STORES_CLEANUP_KEY = `${METADATA_KEY_PREFIX}rs`;
258
260
  const MANIFEST_KEY_PREFIX = `${METADATA_KEY_PREFIX}r.`;
259
261
  const MANIFEST_KEY_SUFFIX = ".m";
260
262
  const SINGLE_MANIFEST_KEY_PREFIX = `${MANIFEST_KEY_PREFIX}s:`;
@@ -522,6 +524,28 @@ function getManagedLocalStorageRuntimeConfig() {
522
524
  }
523
525
  const managedLocalStorageManifestSchema = rc_object({ e: rc_unknown });
524
526
  const managedLocalStorageGlobalMaintenanceSchema = rc_object({ lca: rc_number.orNull() });
527
+ /** Removed store ids already cleaned, keyed by the adapter's storage id. */
528
+ const removedStoresCleanupSchema = rc_record(rc_array(rc_string));
529
+ /**
530
+ * Reads which removed stores were already cleaned from each adapter. Throws
531
+ * when `localStorage` is unavailable.
532
+ */
533
+ function readRemovedStoresCleanupMarker() {
534
+ return readParsedMetadataJson(REMOVED_STORES_CLEANUP_KEY, removedStoresCleanupSchema, directManagedLocalStorageIo) ?? {};
535
+ }
536
+ /**
537
+ * Losing this marker only makes the next startup check the removed stores
538
+ * again, so the write skips quota recovery (which would evict other stores'
539
+ * cached data) and ignores any failure.
540
+ */
541
+ function writeRemovedStoresCleanupMarker(marker) {
542
+ try {
543
+ localStorage.setItem(REMOVED_STORES_CLEANUP_KEY, JSON.stringify(marker));
544
+ } catch {
545
+ return;
546
+ }
547
+ notifyManagedLocalStorageMutation(REMOVED_STORES_CLEANUP_KEY);
548
+ }
525
549
  function readCompactListQueryEntry(payloadKey, io) {
526
550
  return parseCompactListQueryLocalStorageEntry(io.getItem(payloadKey));
527
551
  }
@@ -605,6 +629,7 @@ function classifyTsdfLocalStorageKey(key) {
605
629
  if (!key.startsWith("tsdf.")) return null;
606
630
  if (key === GLOBAL_MAINTENANCE_KEY) return { kind: "global-maintenance" };
607
631
  if (key === "tsdf._am.g") return { kind: "async-global-maintenance" };
632
+ if (key === REMOVED_STORES_CLEANUP_KEY) return { kind: "removed-stores-cleanup" };
608
633
  const manifestLocation = parseManagedLocalStorageManifestKey(key);
609
634
  if (manifestLocation !== null) return {
610
635
  kind: "manifest",
@@ -939,6 +964,28 @@ function manifestBelongsToSession(manifestKey, sessionKey) {
939
964
  const sessionPrefix = `${sessionKey}.`;
940
965
  return manifestKey.startsWith(`${SINGLE_MANIFEST_KEY_PREFIX}${sessionPrefix}`) || manifestKey.startsWith(`${NAMESPACE_MANIFEST_KEY_PREFIX}${sessionPrefix}`);
941
966
  }
967
+ /**
968
+ * Returns the store owning a manifest key, as its `tsdf.<sessionKey>.<storeId>`
969
+ * storage key and store id. Store ids never contain `.`, so both are read from
970
+ * the end of the key, which keeps session keys containing `.` intact. Offline
971
+ * runtime manifests (session status) have no owning store.
972
+ */
973
+ function parseManagedLocalStorageManifestOwner(manifestKey) {
974
+ const location = parseManagedLocalStorageManifestKey(manifestKey);
975
+ if (location === null) return null;
976
+ let storageKey = location.kind === "single" ? location.payloadKey : null;
977
+ if (location.kind === "namespace") {
978
+ const namespaceRoot = location.storagePrefix.endsWith(".") ? location.storagePrefix.slice(0, -1) : location.storagePrefix;
979
+ storageKey = namespaceRoot.slice(0, namespaceRoot.lastIndexOf("."));
980
+ }
981
+ if (storageKey === null || isOfflineRelatedPayloadKey(storageKey)) return null;
982
+ const storeNameStart = storageKey.lastIndexOf(".") + 1;
983
+ if (storeNameStart <= 5) return null;
984
+ return {
985
+ storageKey,
986
+ storeName: storageKey.slice(storeNameStart)
987
+ };
988
+ }
942
989
  function getSessionKeyFromStorageIdentity(identity) {
943
990
  if (!identity.startsWith("tsdf.")) return null;
944
991
  const withoutPrefix = identity.slice(5);
@@ -1045,6 +1092,9 @@ async function runGlobalTsdfLocalStorageCleanup(runLocked, context) {
1045
1092
  case "async-global-maintenance":
1046
1093
  if (readParsedMetadataJson(key, managedLocalStorageGlobalMaintenanceSchema, io) === null) removeMetadataJson(key, io);
1047
1094
  break;
1095
+ case "removed-stores-cleanup":
1096
+ if (readParsedMetadataJson(key, removedStoresCleanupSchema, io) === null) removeMetadataJson(key, io);
1097
+ break;
1048
1098
  case "manifest":
1049
1099
  manifestTargets.push({
1050
1100
  cleanEntries: shouldRunGenericCleanupForManifestLocation(classification.manifestLocation),
@@ -1678,6 +1728,7 @@ let localStorageMaintenanceRunning = false;
1678
1728
  let localStorageMaintenanceGeneration = 0;
1679
1729
  let localStorageGlobalMaintenanceRequested = false;
1680
1730
  let scheduledLocalStorageMaintenanceManifestKeys = /* @__PURE__ */ new Set();
1731
+ let storesWithHandledLocalStorageLeftovers = /* @__PURE__ */ new Set();
1681
1732
  const scheduledAsyncMaintenance = /* @__PURE__ */ new Map();
1682
1733
  function createPersistentStorageDebugContext(adapter, storeName, debugLogger, entryPrefix, key, namespaceKind) {
1683
1734
  return {
@@ -1753,6 +1804,71 @@ function ensureAsyncNamespaceKind(entryPrefix) {
1753
1804
  if (persistedKind !== null) return persistedKind;
1754
1805
  throw new Error(`[tsdf] Unsupported async namespace kind: ${entryPrefix}`);
1755
1806
  }
1807
+ /** Namespaces holding work the user did offline that was not sent yet. */
1808
+ const UNSENT_OFFLINE_WORK_ENTRY_PREFIXES = ["oq", "oc"];
1809
+ /** Manifest-backed namespaces that only hold refetchable or derived data. */
1810
+ const DISPOSABLE_ENTRY_PREFIXES = [
1811
+ "ci",
1812
+ "li",
1813
+ "oe"
1814
+ ];
1815
+ /**
1816
+ * Removes what a store left in `localStorage` before it moved to an async
1817
+ * adapter. Nothing reads, refreshes or releases those entries anymore: without
1818
+ * this, they would only go away through the global expiry sweep, which never
1819
+ * runs once no store uses `'local-sync'` and never removes offline-protected
1820
+ * entries.
1821
+ *
1822
+ * Also removes the data of stores the app declared as removed
1823
+ * (`removedStores`), which nothing reads anymore either.
1824
+ *
1825
+ * Returns how many queued offline mutations and pending resolutions the store
1826
+ * had. With `keepUnsentOfflineWork`, a store that still has any is left
1827
+ * untouched (the cached data backs that queued work); otherwise they are
1828
+ * removed with everything else.
1829
+ *
1830
+ * Must run inside the managed `localStorage` lock, so a tab still running the
1831
+ * previous version cannot queue work between the check and the removal.
1832
+ */
1833
+ function removeStoreLeftoversFromLocalStorage(storageKey, keepUnsentOfflineWork) {
1834
+ let unsentRecordsCount = 0;
1835
+ for (const entryPrefix of UNSENT_OFFLINE_WORK_ENTRY_PREFIXES) unsentRecordsCount += localPersistentStorage.listManifestEntries(`${storageKey}.${entryPrefix}.`).length;
1836
+ if (keepUnsentOfflineWork && unsentRecordsCount > 0) return unsentRecordsCount;
1837
+ const singleManifestKey = localPersistentStorage.getManifestKeyForSingle(storageKey);
1838
+ if (localPersistentStorage.readRaw(singleManifestKey) !== null) localPersistentStorage.clearManifest(singleManifestKey);
1839
+ for (const entryPrefix of [...DISPOSABLE_ENTRY_PREFIXES, ...UNSENT_OFFLINE_WORK_ENTRY_PREFIXES]) localPersistentStorage.removeByPrefix(`${storageKey}.${entryPrefix}.`);
1840
+ for (const queryStorageKey of localPersistentStorage.listRawKeys(`${storageKey}.lq.`)) localPersistentStorage.remove(queryStorageKey);
1841
+ return unsentRecordsCount;
1842
+ }
1843
+ /**
1844
+ * Creates the per-handle check that detects `localStorage` entries left by a
1845
+ * store that now persists through an async adapter.
1846
+ *
1847
+ * The check runs once per session key and reads one `localStorage` key: the
1848
+ * manifest this handle would own under `'local-sync'`. Stores that never used
1849
+ * `localStorage` stop there; only a hit schedules the actual cleanup.
1850
+ */
1851
+ function createLocalStorageLeftoversCheck(storeName, getManifestKey, onPersistentStorageError) {
1852
+ let checkedSessionKey = null;
1853
+ return (sessionKey) => {
1854
+ if (checkedSessionKey === sessionKey) return;
1855
+ checkedSessionKey = sessionKey;
1856
+ const storageKey = getStorageKey(sessionKey, storeName);
1857
+ try {
1858
+ if (localStorage.getItem(getManifestKey(storageKey)) === null) return;
1859
+ } catch {
1860
+ return;
1861
+ }
1862
+ if (storesWithHandledLocalStorageLeftovers.has(storageKey)) return;
1863
+ storesWithHandledLocalStorageLeftovers.add(storageKey);
1864
+ scheduleIdleCleanup(() => {
1865
+ runLocalStorageMutation(() => removeStoreLeftoversFromLocalStorage(storageKey, true)).then((unsentRecordsCount) => {
1866
+ if (unsentRecordsCount === 0) return;
1867
+ onPersistentStorageError?.(/* @__PURE__ */ new Error(`[tsdf] Store "${storeName}" now uses an async persistentStorage adapter, but localStorage still holds ${unsentRecordsCount} unsent offline record(s) (queued mutations or pending resolutions) it wrote through 'local-sync'. They were kept, but they are only replayed while the store uses 'local-sync': roll the store back to 'local-sync' to replay them. This is reported on every page load until then.`));
1868
+ }).catch(handleManagedLocalStorageBackgroundError);
1869
+ });
1870
+ };
1871
+ }
1756
1872
  /**
1757
1873
  * Schedules managed localStorage maintenance during idle time.
1758
1874
  *
@@ -1880,6 +1996,7 @@ function createPersistentStorageHandle(config, { asyncValueCodec, getManifestMet
1880
1996
  const effectiveAsyncValueCodec = asyncValueCodec ?? valueCodec;
1881
1997
  const localCodec = toLocalStorageValueCodec(valueCodec);
1882
1998
  let debounceTimer = null;
1999
+ const checkLocalStorageLeftovers = createLocalStorageLeftoversCheck(config.storeName, (storageKey) => localPersistentStorage.getManifestKeyForSingle(storageKey), onPersistentStorageError);
1883
2000
  scheduleAdapterExpirationScan(adapter);
1884
2001
  function getKey() {
1885
2002
  const sessionKey = config.getSessionKey();
@@ -1890,6 +2007,7 @@ function createPersistentStorageHandle(config, { asyncValueCodec, getManifestMet
1890
2007
  if (asyncAdapter === null) return null;
1891
2008
  const sessionKey = config.getSessionKey();
1892
2009
  if (sessionKey === false) return null;
2010
+ checkLocalStorageLeftovers(sessionKey);
1893
2011
  asyncAdapter.debugLogger = config.debugLogger;
1894
2012
  asyncAdapter.logger = config.logger;
1895
2013
  return asyncAdapter.openNamespace({
@@ -2091,6 +2209,7 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2091
2209
  const debugContext = import.meta.env.DEV ? createPersistentStorageDebugContext(adapter, config.storeName, config.debugLogger, config.entryPrefix, void 0, asyncNamespaceKind) : void 0;
2092
2210
  const effectiveAsyncValueCodec = asyncValueCodec ?? valueCodec;
2093
2211
  const localCodec = toLocalStorageValueCodec(valueCodec);
2212
+ const checkLocalStorageLeftovers = config.entryPrefix === "lq" ? null : createLocalStorageLeftoversCheck(config.storeName, (storageKey) => localPersistentStorage.getManifestKeyForPrefix(`${storageKey}.${config.entryPrefix}.`), onPersistentStorageError);
2094
2213
  scheduleAdapterExpirationScan(adapter);
2095
2214
  function getPrefix() {
2096
2215
  const sessionKey = config.getSessionKey();
@@ -2101,6 +2220,7 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2101
2220
  if (asyncAdapter === null) return null;
2102
2221
  const sessionKey = config.getSessionKey();
2103
2222
  if (sessionKey === false) return null;
2223
+ checkLocalStorageLeftovers?.(sessionKey);
2104
2224
  asyncAdapter.debugLogger = config.debugLogger;
2105
2225
  asyncAdapter.logger = config.logger;
2106
2226
  return {
@@ -2789,7 +2909,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2789
2909
  }
2790
2910
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2791
2911
  async function clearAllSessionStorage(sessionKey) {
2792
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Rh3o1FAG.js");
2912
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Daewq7dv.js");
2793
2913
  await Promise.all([
2794
2914
  clearSessionStorage(sessionKey, "local-sync"),
2795
2915
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -4140,7 +4260,7 @@ function stripStoredUploadFile(record) {
4140
4260
  const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, ...upload } = record;
4141
4261
  return upload;
4142
4262
  }
4143
- function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt) {
4263
+ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt, metadata) {
4144
4264
  const file = normalizeUploadFile(fileInput, id);
4145
4265
  const now = Date.now();
4146
4266
  const createdAt = createdAtInput ?? now;
@@ -4159,6 +4279,7 @@ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, crea
4159
4279
  ...progress !== void 0 ? { progress } : {},
4160
4280
  ...lastError !== void 0 ? { lastError } : {},
4161
4281
  ...lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt } : {},
4282
+ ...metadata !== void 0 ? { metadata } : {},
4162
4283
  file,
4163
4284
  lastModified: file.lastModified
4164
4285
  };
@@ -4194,6 +4315,59 @@ const defaultStatusBySession = /* @__PURE__ */ new Map();
4194
4315
  const registry = /* @__PURE__ */ new Map();
4195
4316
  const uploadsConfigByOfflineSession = /* @__PURE__ */ new WeakMap();
4196
4317
  const appVersionByOfflineSession = /* @__PURE__ */ new WeakMap();
4318
+ const offlineRecoveryListeners = /* @__PURE__ */ new Set();
4319
+ /**
4320
+ * The stores (by name) that cannot be revalidated against the server yet, or
4321
+ * `null` when no store of the session can:
4322
+ *
4323
+ * - offline, or with queued mutations still to replay: anything fetched now
4324
+ * may predate the replayed mutations, in any store
4325
+ * - a store with changes waiting for a manual resolution: a refetch would
4326
+ * replace the local changes the user still has to decide on
4327
+ */
4328
+ function getStoresAwaitingRecovery(state) {
4329
+ if (state.status.isOfflineMode || state.hasQueuedMutations) return null;
4330
+ const storeNames = /* @__PURE__ */ new Set();
4331
+ for (const entity of state.entities) {
4332
+ if (entity.pendingMutations > 0) return null;
4333
+ if (entity.requiresResolution) storeNames.add(entity.storeName);
4334
+ }
4335
+ for (const resolution of state.resolutions) storeNames.add(resolution.storeName);
4336
+ return storeNames;
4337
+ }
4338
+ /**
4339
+ * Subscribes to stores recovering in this tab (any session key; listeners
4340
+ * filter by the key they care about). A store recovers when its session is
4341
+ * back online with its queued mutations replayed and the store has no change
4342
+ * left waiting for a manual resolution: from then on its cached data can be
4343
+ * revalidated against the server.
4344
+ * @internal
4345
+ */
4346
+ function subscribeToOfflineRecovery(listener) {
4347
+ offlineRecoveryListeners.add(listener);
4348
+ return () => {
4349
+ offlineRecoveryListeners.delete(listener);
4350
+ };
4351
+ }
4352
+ /**
4353
+ * Whether the session is in offline mode in this tab, without creating or
4354
+ * reconfiguring its coordinator (a session nothing tracks is online).
4355
+ *
4356
+ * While it is, also re-checks connectivity: callers ask on a hint that the
4357
+ * connection may be back (a transport reconnect, a window focus), and some
4358
+ * setups have nothing else that ends offline mode (a custom `getIsOffline`
4359
+ * without browser events, a classified network failure without a recovery
4360
+ * check). Leaving offline mode notifies the recovery listeners, which
4361
+ * revalidate the stores, so callers skip their own revalidation either way.
4362
+ * @internal
4363
+ */
4364
+ function recheckIsSessionInOfflineMode(sessionKey) {
4365
+ if (sessionKey === false) return false;
4366
+ const coordinator = registry.get(sessionKey);
4367
+ if (!coordinator?.getStatus().isOfflineMode) return false;
4368
+ coordinator.recheckNetworkState();
4369
+ return true;
4370
+ }
4197
4371
  const DEFAULT_UPLOAD_CONCURRENCY = 3;
4198
4372
  const OFFLINE_UPLOAD_RETENTION_MS = 10080 * 60 * 1e3;
4199
4373
  const OFFLINE_UPLOAD_RETENTION_STABLE_ONLINE_MS = 5e3;
@@ -4421,6 +4595,7 @@ var SessionOfflineCoordinator = class {
4421
4595
  #classificationToken = 0;
4422
4596
  #retriableFailureToken = 0;
4423
4597
  #networkStateToken = 0;
4598
+ #isRecheckingNetworkState = false;
4424
4599
  #lastRemoteSnapshotAt = 0;
4425
4600
  #recoveryTimer = null;
4426
4601
  #scheduledRecoveryMode = null;
@@ -4467,10 +4642,19 @@ var SessionOfflineCoordinator = class {
4467
4642
  status: bootstrappedLocalSnapshot?.status ?? resolveDefaultStatus(sessionKey, { bootstrapStatusFromLocalStorage: shouldBootstrapFromStorage }),
4468
4643
  entities: [],
4469
4644
  resolutions: [],
4470
- uploads: []
4645
+ uploads: [],
4646
+ hasQueuedMutations: false
4471
4647
  })
4472
4648
  });
4473
4649
  this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
4650
+ this.store.subscribe(({ prev, current }) => {
4651
+ if (prev.entities === current.entities && prev.resolutions === current.resolutions && prev.hasQueuedMutations === current.hasQueuedMutations && prev.status.isOfflineMode === current.status.isOfflineMode) return;
4652
+ const awaitingStores = getStoresAwaitingRecovery(current);
4653
+ if (awaitingStores === null) return;
4654
+ const prevAwaitingStores = getStoresAwaitingRecovery(prev);
4655
+ if (prevAwaitingStores?.size === 0) return;
4656
+ for (const listener of offlineRecoveryListeners) listener(sessionKey, (storeName) => !awaitingStores.has(storeName) && (prevAwaitingStores === null || prevAwaitingStores.has(storeName)));
4657
+ });
4474
4658
  this.#browserTabs = createBrowserTabsCoordinatorWithPriority("offline", `session:${sessionKey}`, () => this.sessionKey, (message) => {
4475
4659
  if (message.kind === "tab-status") {
4476
4660
  this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
@@ -4521,7 +4705,7 @@ var SessionOfflineCoordinator = class {
4521
4705
  if (this.#uploadsConfig) try {
4522
4706
  const uploads = await this.#uploadsConfig.adapter.list(this.sessionKey);
4523
4707
  if (hydrationToken === this.#hydrationToken) {
4524
- this.#uploads = new Map(uploads.map((upload) => [upload.id, upload]));
4708
+ this.#uploads = new Map([...uploads.map((upload) => [upload.id, upload]), ...this.#uploads]);
4525
4709
  this.#syncUploadsState();
4526
4710
  this.#scheduleUploadOnlineSessionStabilization();
4527
4711
  this.#refreshUploadRetention();
@@ -4537,12 +4721,12 @@ var SessionOfflineCoordinator = class {
4537
4721
  if (import.meta.env.DEV && options.debugLogger !== void 0) this.#debugLogger = options.debugLogger;
4538
4722
  if (options.uploads !== void 0) {
4539
4723
  if (import.meta.env.DEV && this.#uploadsConfig !== void 0 && !sameUploadsConfig(this.#uploadsConfig, options.uploads)) throw new Error(`[tsdf] Incompatible offline upload configuration for session "${this.sessionKey}"`);
4540
- this.#uploadsConfig = options.uploads;
4541
- registerOfflineUploadAdapterForSession(this.sessionKey, options.uploads.adapter);
4542
- this.#uploadQueue = createAsyncQueue({
4724
+ if (!sameUploadsConfig(this.#uploadsConfig, options.uploads)) this.#uploadQueue = createAsyncQueue({
4543
4725
  autoStart: true,
4544
4726
  concurrency: options.uploads.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY
4545
4727
  });
4728
+ this.#uploadsConfig = options.uploads;
4729
+ registerOfflineUploadAdapterForSession(this.sessionKey, options.uploads.adapter);
4546
4730
  this.hydrate();
4547
4731
  }
4548
4732
  if (!this.#hasCanonicalConfig && options.config) {
@@ -4639,17 +4823,18 @@ var SessionOfflineCoordinator = class {
4639
4823
  }
4640
4824
  async saveUpload(args) {
4641
4825
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
4826
+ if (this.#uploadPromisesById.has(args.id)) throw new Error(`Cannot change upload "${args.id}" while it is queued or uploading`);
4642
4827
  const existing = this.#uploads.get(args.id);
4643
- const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt());
4828
+ const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt(), args.metadata);
4644
4829
  await this.#saveUploadRecord(nextRecord);
4645
4830
  }
4646
4831
  async replaceUpload(args) {
4647
- const existing = this.#uploads.get(args.id);
4648
- if (existing?.state === "uploading") throw new Error(`Cannot replace upload "${args.id}" while uploading`);
4832
+ const existing = await this.#getUploadRecord(args.id);
4649
4833
  await this.saveUpload({
4650
4834
  id: args.id,
4651
4835
  file: args.file,
4652
- source: existing?.source ?? "manual"
4836
+ source: existing?.source ?? "manual",
4837
+ metadata: args.metadata ?? existing?.metadata
4653
4838
  });
4654
4839
  }
4655
4840
  async loadUpload(id) {
@@ -4803,6 +4988,18 @@ var SessionOfflineCoordinator = class {
4803
4988
  this.setNetworkActive(false, { classified: false });
4804
4989
  return false;
4805
4990
  }
4991
+ /**
4992
+ * Re-checks connectivity on a hint that it may be back. Hints from several
4993
+ * stores (e.g. their window-focus handlers) share a re-check still in flight
4994
+ * instead of calling `getIsOffline` once per store.
4995
+ */
4996
+ recheckNetworkState() {
4997
+ if (this.#isRecheckingNetworkState) return;
4998
+ this.#isRecheckingNetworkState = true;
4999
+ this.refreshNetworkState().finally(() => {
5000
+ this.#isRecheckingNetworkState = false;
5001
+ });
5002
+ }
4806
5003
  async refreshNetworkState() {
4807
5004
  const token = ++this.#networkStateToken;
4808
5005
  const detectedOffline = this.#getCurrentOfflineState();
@@ -4913,6 +5110,8 @@ var SessionOfflineCoordinator = class {
4913
5110
  if (existing) return existing;
4914
5111
  if (!this.#uploadsConfig) return null;
4915
5112
  const loaded = await this.#uploadsConfig.adapter.load(this.sessionKey, id);
5113
+ const current = this.#uploads.get(id);
5114
+ if (current) return current;
4916
5115
  if (loaded) {
4917
5116
  this.#uploads.set(id, loaded);
4918
5117
  this.#syncUploadsState();
@@ -5063,6 +5262,7 @@ var SessionOfflineCoordinator = class {
5063
5262
  id,
5064
5263
  sessionKey: this.sessionKey,
5065
5264
  file,
5265
+ metadata: queuedRecord.metadata,
5066
5266
  onProgress: (progress) => {
5067
5267
  this.#updateUploadState({
5068
5268
  id,
@@ -5115,7 +5315,9 @@ var SessionOfflineCoordinator = class {
5115
5315
  const allResolutions = [];
5116
5316
  const referencedUploadIds = /* @__PURE__ */ new Set();
5117
5317
  const nextProtectedKeysByAdapter = /* @__PURE__ */ new Map();
5318
+ let hasQueuedMutations = false;
5118
5319
  for (const contribution of this.#storeContributions.values()) {
5320
+ if (contribution.replayHead !== null) hasQueuedMutations = true;
5119
5321
  allEntities.push(...contribution.entities);
5120
5322
  allResolutions.push(...contribution.resolutions);
5121
5323
  for (const uploadId of contribution.referencedUploadIds) referencedUploadIds.add(uploadId);
@@ -5178,7 +5380,8 @@ var SessionOfflineCoordinator = class {
5178
5380
  }
5179
5381
  this.store.setPartialState({
5180
5382
  entities,
5181
- resolutions
5383
+ resolutions,
5384
+ hasQueuedMutations
5182
5385
  }, { action: "offline-session-aggregate" });
5183
5386
  this.#persistSessionSnapshot();
5184
5387
  this.#publishSnapshot();
@@ -5218,7 +5421,8 @@ var SessionOfflineCoordinator = class {
5218
5421
  status,
5219
5422
  entities: this.store.state.entities,
5220
5423
  resolutions: this.store.state.resolutions,
5221
- uploads: this.store.state.uploads
5424
+ uploads: this.store.state.uploads,
5425
+ hasQueuedMutations: this.store.state.hasQueuedMutations
5222
5426
  });
5223
5427
  }
5224
5428
  #applyRemoteSnapshot(message) {
@@ -5231,7 +5435,8 @@ var SessionOfflineCoordinator = class {
5231
5435
  }),
5232
5436
  entities: message.entities,
5233
5437
  resolutions: message.resolutions,
5234
- uploads: message.uploads
5438
+ uploads: message.uploads,
5439
+ hasQueuedMutations: message.hasQueuedMutations
5235
5440
  }, { action: "offline-session-remote" });
5236
5441
  this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5237
5442
  this.#persistSessionSnapshot();
@@ -5480,21 +5685,23 @@ function createOfflineSession(args) {
5480
5685
  if (!coordinator) throw new Error(`[tsdf] Offline uploads are not configured for inactive session scope "${inactiveScope}"`);
5481
5686
  return castResolvedUploadRefs(await coordinator.resolveUploadIds(ids));
5482
5687
  },
5483
- saveOfflineUpload: ({ id, file }) => {
5688
+ saveOfflineUpload: ({ id, file, metadata }) => {
5484
5689
  const coordinator = getActiveCoordinator();
5485
5690
  if (!coordinator) return Promise.resolve();
5486
5691
  return coordinator.saveUpload({
5487
5692
  id,
5488
5693
  file,
5694
+ metadata,
5489
5695
  source: "manual"
5490
5696
  });
5491
5697
  },
5492
- replaceOfflineUpload: ({ id, file }) => {
5698
+ replaceOfflineUpload: ({ id, file, metadata }) => {
5493
5699
  const coordinator = getActiveCoordinator();
5494
5700
  if (!coordinator) return Promise.resolve();
5495
5701
  return coordinator.replaceUpload({
5496
5702
  id,
5497
- file
5703
+ file,
5704
+ metadata
5498
5705
  });
5499
5706
  },
5500
5707
  loadOfflineUpload: (id) => {
@@ -5824,8 +6031,31 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
5824
6031
  function resolveMutationQueueingPolicy(cause) {
5825
6032
  return ensureActiveSession()?.session.getRuntimeConfig().mutationQueueing[cause] ?? "allow";
5826
6033
  }
5827
- function getInitialOfflineMutationAction(current) {
5828
- if (!current.session.getStatus().isOfflineMode) return "run";
6034
+ function getOperationRawEntityRefs(operation, operationName, validatedInput) {
6035
+ return typeof operation.getEntityRefs === "function" ? operation.getEntityRefs({ input: validatedInput }) : storeAdapter.getEntityRefs?.({
6036
+ operationName,
6037
+ input: validatedInput
6038
+ }) ?? [];
6039
+ }
6040
+ /**
6041
+ * Whether mutations queued earlier for the entities this mutation affects
6042
+ * or depends on (`dependsOn`), or that depend on an entity this mutation
6043
+ * affects, are still waiting to reach the server (queued, replaying or
6044
+ * unconfirmed).
6045
+ */
6046
+ function hasQueuedWorkForSameEntities(prepared) {
6047
+ if (queueEntries.size === 0) return false;
6048
+ const affectedEntityRefs = prepared.entityRefs ?? resolveNormalizedRefs(getOperationRawEntityRefs(prepared.operation, prepared.operationName, prepared.validatedInput));
6049
+ const entityRefs = [...affectedEntityRefs, ...prepared.operation.dependsOn ? resolveNormalizedRefs(prepared.operation.dependsOn({ input: prepared.validatedInput })) : []];
6050
+ for (const entry of queueEntries.values()) {
6051
+ for (const queuedEntityRef of entry.entityRefs) if (entityRefs.some((entityRef) => isSameEntityRef(entityRef, queuedEntityRef))) return true;
6052
+ const queuedDependencyKeys = getDependencyBlockerEntityKeys(entry);
6053
+ if (affectedEntityRefs.some((entityRef) => queuedDependencyKeys.has(entityRef.entityKey))) return true;
6054
+ }
6055
+ return false;
6056
+ }
6057
+ function getInitialOfflineMutationAction(current, prepared) {
6058
+ if (!current.session.getStatus().isOfflineMode) return hasQueuedWorkForSameEntities(prepared) ? "queue" : "run";
5829
6059
  const cause = getActiveMutationQueueingCause(current);
5830
6060
  if (cause === null) return "run";
5831
6061
  if (isMutationQueueingAllowed(cause)) return "queue";
@@ -6303,6 +6533,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6303
6533
  entityKind: entity.entityKind
6304
6534
  })));
6305
6535
  const nextReplayEntry = getSortedEntries()[0] ?? null;
6536
+ storeAdapter.syncEntityOverlays?.({
6537
+ sessionKey: sessionState.sessionKey,
6538
+ entities
6539
+ });
6306
6540
  sessionState.session.syncStoreData(storeName, {
6307
6541
  adapter,
6308
6542
  entities,
@@ -6316,10 +6550,6 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6316
6550
  createdAt: nextReplayEntry.createdAt
6317
6551
  }
6318
6552
  });
6319
- storeAdapter.syncEntityOverlays?.({
6320
- sessionKey: sessionState.sessionKey,
6321
- entities
6322
- });
6323
6553
  syncEntityNamespace(sessionState, entities);
6324
6554
  }
6325
6555
  async function syncEntityNamespace(current, entities) {
@@ -6802,6 +7032,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6802
7032
  const parentEntityKeys = getTempLifecycleEntityKeys(args.resolution);
6803
7033
  if (parentEntityKeys.length === 0) {
6804
7034
  refreshDerivedState(args.current);
7035
+ revalidateDiscardedWork([args.resolution], /* @__PURE__ */ new Set());
6805
7036
  return;
6806
7037
  }
6807
7038
  const descendantQueueEntries = /* @__PURE__ */ new Map();
@@ -6820,6 +7051,36 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6820
7051
  for (const resolution of descendantResolutions.values()) rollbackTempCreatePendingEntity(resolution);
6821
7052
  rollbackTempCreatePendingEntity(args.resolution);
6822
7053
  refreshDerivedState(args.current);
7054
+ const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7055
+ const removedTempEntityKeys = new Set(parentEntityKeys);
7056
+ for (const workItem of discardedWork) for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedTempEntityKeys.add(entityKey);
7057
+ revalidateDiscardedWork(discardedWork, removedTempEntityKeys);
7058
+ }
7059
+ /**
7060
+ * Refetches the entities discarded queued work referenced (its optimistic
7061
+ * changes cannot be rolled back locally), except the removed temp entities
7062
+ * and the entities other changes still wait for a decision on: a refetch
7063
+ * would replace those changes. The recovery revalidation refetches them
7064
+ * once the last one is handled.
7065
+ */
7066
+ function revalidateDiscardedWork(discardedWork, removedTempEntityKeys) {
7067
+ const entities = [];
7068
+ const skippedEntityKeys = new Set(removedTempEntityKeys);
7069
+ for (const resolution of resolutions.values()) for (const ref of resolution.entityRefs) skippedEntityKeys.add(ref.entityKey);
7070
+ for (const workItem of discardedWork) for (const ref of workItem.entityRefs) {
7071
+ if (skippedEntityKeys.has(ref.entityKey)) continue;
7072
+ skippedEntityKeys.add(ref.entityKey);
7073
+ entities.push({
7074
+ ...ref,
7075
+ payload: getPayloadForEntityRef({
7076
+ operationName: workItem.operation,
7077
+ input: workItem.input,
7078
+ entityKey: ref.entityKey
7079
+ })
7080
+ });
7081
+ }
7082
+ if (entities.length === 0) return;
7083
+ storeAdapter.revalidateDiscardedEntities?.(entities, resolutions.size > 0);
6823
7084
  }
6824
7085
  function collectRetryResolutionChain(args) {
6825
7086
  if (args.scope === "self") return [args.resolution];
@@ -6909,10 +7170,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6909
7170
  if (storeType === "document" && (tempEntity || tempEntities)) throw new Error(`Document offline operation "${operationName}" does not support tempEntity or tempEntities`);
6910
7171
  if ((tempEntity || tempEntities) && "onSuccessExecute" in operation) throw new Error(`Offline operation "${operationName}" cannot configure onSuccessExecute when tempEntity or tempEntities is present`);
6911
7172
  if (operation.accumulation && upload !== void 0) throw new Error(`Offline operation "${operationName}" cannot configure direct uploads together with accumulation`);
6912
- const rawEntityRefs = typeof operation.getEntityRefs === "function" ? operation.getEntityRefs({ input: validatedInput }) : storeAdapter.getEntityRefs?.({
6913
- operationName,
6914
- input: validatedInput
6915
- }) ?? [];
7173
+ const rawEntityRefs = getOperationRawEntityRefs(operation, operationName, validatedInput);
6916
7174
  const resolvedEntityRefs = resolveNormalizedRefs(rawEntityRefs);
6917
7175
  const hasTempLifecycle = tempEntity !== void 0 || tempEntities !== void 0;
6918
7176
  const entityRefs = hasTempLifecycle && preparedTempIds !== void 0 && preparedEntityRefs !== void 0 ? preparedEntityRefs : resolvedEntityRefs;
@@ -6963,9 +7221,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6963
7221
  });
6964
7222
  const validatedMergedInput = validateWithSchema(operation.inputSchema, mergedInput);
6965
7223
  if (validatedMergedInput === null) throw new Error(`Invalid accumulated offline operation input for "${operationName}"`);
7224
+ const mergedDependencyUploadIds = getDependencyUploadIds({
7225
+ operationName,
7226
+ input: validatedMergedInput
7227
+ });
6966
7228
  const nextEntry = {
6967
7229
  ...existingEntry,
6968
7230
  input: validatedMergedInput,
7231
+ dependencyUploadIds: mergedDependencyUploadIds.length > 0 ? mergedDependencyUploadIds : void 0,
6969
7232
  updatedAt: now
6970
7233
  };
6971
7234
  workingQueue.set(nextEntry.id, nextEntry);
@@ -6975,7 +7238,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6975
7238
  tempIds,
6976
7239
  pendingEntities,
6977
7240
  nextEntry,
6978
- removedEntries: [existingEntry]
7241
+ removedEntries: [existingEntry],
7242
+ accumulatedEntry: existingEntry
6979
7243
  };
6980
7244
  }
6981
7245
  }
@@ -7020,12 +7284,15 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7020
7284
  const { queueOrders, nextQueueOrderValue } = previewQueueOrders(1);
7021
7285
  const queueOrder = queueOrders[0];
7022
7286
  if (queueOrder === void 0) throw new Error("Missing queue order for prepared offline mutation");
7023
- const plannedMutation = await planPreparedMutation({
7024
- current,
7025
- preparedMutation,
7026
- queueOrder,
7027
- workingQueue: new Map(queueEntries)
7028
- });
7287
+ let plannedMutation;
7288
+ do
7289
+ plannedMutation = await planPreparedMutation({
7290
+ current,
7291
+ preparedMutation,
7292
+ queueOrder,
7293
+ workingQueue: new Map(queueEntries)
7294
+ });
7295
+ while (plannedMutation.accumulatedEntry && queueEntries.get(plannedMutation.accumulatedEntry.id) !== plannedMutation.accumulatedEntry);
7029
7296
  const persistedMutations = [];
7030
7297
  const persistedUploadIds = [];
7031
7298
  const appliedPendingMutations = [];
@@ -7253,7 +7520,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7253
7520
  parentEntry: entryToUse,
7254
7521
  parentResolution: buildRetryExhaustedResolutionRecord(current, entryToUse, lastError)
7255
7522
  });
7256
- return;
7523
+ continue;
7257
7524
  }
7258
7525
  await persistEntry(entryToUse, current);
7259
7526
  return;
@@ -7281,7 +7548,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7281
7548
  });
7282
7549
  await current.session.refreshNetworkState();
7283
7550
  return {
7284
- initialAction: getInitialOfflineMutationAction(current),
7551
+ initialAction: getInitialOfflineMutationAction(current, prepared),
7285
7552
  queueMutation: () => queuePreparedMutations(prepared),
7286
7553
  handleDirectSuccess: () => clearOfflineStatusOnSuccess(prepared.currentSessionKey),
7287
7554
  classifyError: async (error) => {
@@ -7381,13 +7648,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7381
7648
  return;
7382
7649
  }
7383
7650
  if (action === "requeue") {
7384
- await removeResolution(resolutionId, current, true);
7385
- await queuePreparedMutations(prepareMutationWithSession(current, {
7651
+ const preparedMutation = prepareMutationWithSession(current, {
7386
7652
  operation: operationName,
7387
7653
  input: resolutionAction?.input,
7388
7654
  tempIds: resolutionRecord.tempIds,
7389
7655
  entityRefs: resolutionRecord.entityRefs
7390
- }));
7656
+ });
7657
+ await removeResolution(resolutionId, current, true);
7658
+ await queuePreparedMutations(preparedMutation);
7391
7659
  return;
7392
7660
  }
7393
7661
  if (action === "commit") {
@@ -7405,6 +7673,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7405
7673
  }
7406
7674
  throw new Error("Invalid offline resolution action");
7407
7675
  }
7676
+ async function resolveOfflineResolutionWithGenericAction(resolutionId, action) {
7677
+ await hydrateIfNeeded();
7678
+ const resolutionRecord = ensureActiveSession() ? resolutions.get(resolutionId) : void 0;
7679
+ if (!resolutionRecord) return "resolution-not-found";
7680
+ if (action === "retry" && resolutionRecord.kind !== "retry-exhausted") return "retry-not-supported";
7681
+ if (isPersistedResolutionBlocked(resolutionRecord)) return "resolution-blocked";
7682
+ await resolveOfflineResolution(resolutionId, resolutionRecord.operation, { action });
7683
+ }
7408
7684
  async function evaluateOfflineFetchError(error, operationName) {
7409
7685
  const current = ensureActiveSession();
7410
7686
  if (!current) return;
@@ -7447,6 +7723,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7447
7723
  getOfflineResolutions,
7448
7724
  parseOfflineResolutionConflict: parseConflictPayloadForResolution,
7449
7725
  resolveOfflineResolution,
7726
+ resolveOfflineResolutionWithGenericAction,
7450
7727
  prepareForFetch,
7451
7728
  getSessionStatus,
7452
7729
  shouldTreatFetchAsOffline,
@@ -8313,6 +8590,115 @@ var RequestScheduler = class {
8313
8590
  }
8314
8591
  };
8315
8592
  //#endregion
8593
+ //#region src/persistentStorage/removedStoresCleanup.ts
8594
+ /**
8595
+ * Removes the stores' data from `localStorage` in every session, found
8596
+ * through their manifests. Must run inside the managed `localStorage` lock.
8597
+ */
8598
+ function removeStoresFromLocalStorage(storeNames) {
8599
+ const storeNameByStorageKey = /* @__PURE__ */ new Map();
8600
+ for (const key of localPersistentStorage.listRawKeys("tsdf.")) {
8601
+ const owner = parseManagedLocalStorageManifestOwner(key);
8602
+ if (owner === null || !storeNames.has(owner.storeName)) continue;
8603
+ storeNameByStorageKey.set(owner.storageKey, owner.storeName);
8604
+ }
8605
+ const unsentRecordsByStore = /* @__PURE__ */ new Map();
8606
+ for (const [storageKey, storeName] of storeNameByStorageKey) {
8607
+ const unsentRecords = removeStoreLeftoversFromLocalStorage(storageKey, false);
8608
+ unsentRecordsByStore.set(storeName, (unsentRecordsByStore.get(storeName) ?? 0) + unsentRecords);
8609
+ }
8610
+ return unsentRecordsByStore;
8611
+ }
8612
+ /** Marker key of the `'local-sync'` adapter. */
8613
+ const LOCAL_SYNC_STORAGE_ID = "local-sync";
8614
+ async function runRemovedStoresCleanup(removedStores, reportError) {
8615
+ let cleanedMarker;
8616
+ try {
8617
+ cleanedMarker = new Map(Object.entries(readRemovedStoresCleanupMarker()));
8618
+ } catch {
8619
+ return;
8620
+ }
8621
+ const cleanups = /* @__PURE__ */ new Map();
8622
+ const unsupportedStoreNames = /* @__PURE__ */ new Set();
8623
+ for (const { adapter, id } of removedStores) {
8624
+ const asyncStorage = adapter === "local-sync" ? null : getRemovableStoresAsyncStorage(adapter);
8625
+ if (adapter !== "local-sync" && asyncStorage === null) {
8626
+ unsupportedStoreNames.add(id);
8627
+ continue;
8628
+ }
8629
+ const storageId = asyncStorage?.storageId ?? LOCAL_SYNC_STORAGE_ID;
8630
+ let cleanup = cleanups.get(storageId);
8631
+ if (cleanup === void 0) {
8632
+ cleanup = {
8633
+ storageId,
8634
+ storeNames: /* @__PURE__ */ new Set(),
8635
+ run: asyncStorage?.removeStores ?? ((storeNames) => localPersistentStorage.runLocked(() => ({
8636
+ unsentRecordsByStore: removeStoresFromLocalStorage(storeNames),
8637
+ failure: null
8638
+ })))
8639
+ };
8640
+ cleanups.set(storageId, cleanup);
8641
+ }
8642
+ cleanup.storeNames.add(id);
8643
+ }
8644
+ if (unsupportedStoreNames.size > 0) reportError(/* @__PURE__ */ new Error(`[tsdf] Removed store(s) ${formatStoreNames(unsupportedStoreNames)} use an async adapter TSDF cannot clean: it must be created with createAsyncStorageAdapter from a driver that has a storageId.`));
8645
+ const nextMarker = /* @__PURE__ */ new Map();
8646
+ const pendingCleanups = [];
8647
+ for (const cleanup of cleanups.values()) {
8648
+ const cleanedStoreNames = new Set(cleanedMarker.get(cleanup.storageId));
8649
+ const done = [];
8650
+ const pending = /* @__PURE__ */ new Set();
8651
+ for (const storeName of cleanup.storeNames) if (cleanedStoreNames.has(storeName)) done.push(storeName);
8652
+ else pending.add(storeName);
8653
+ if (done.length > 0) nextMarker.set(cleanup.storageId, done);
8654
+ if (pending.size > 0) pendingCleanups.push({
8655
+ cleanup,
8656
+ storeNames: pending
8657
+ });
8658
+ }
8659
+ let markerChanged = countMarkerEntries(nextMarker) !== countMarkerEntries(cleanedMarker);
8660
+ for (const { cleanup, storeNames } of pendingCleanups) {
8661
+ let result;
8662
+ try {
8663
+ result = await cleanup.run(storeNames);
8664
+ } catch (error) {
8665
+ reportError(error);
8666
+ continue;
8667
+ }
8668
+ for (const [storeName, unsentRecords] of result.unsentRecordsByStore) {
8669
+ if (unsentRecords === 0) continue;
8670
+ reportError(/* @__PURE__ */ new Error(`[tsdf] Removed store "${storeName}" still had ${unsentRecords} unsent offline record(s) (queued mutations or pending resolutions). They were deleted with the rest of its persisted data: no store can replay them anymore.`));
8671
+ }
8672
+ if (result.failure !== null) {
8673
+ reportError(result.failure);
8674
+ continue;
8675
+ }
8676
+ nextMarker.set(cleanup.storageId, [...nextMarker.get(cleanup.storageId) ?? [], ...storeNames]);
8677
+ markerChanged = true;
8678
+ }
8679
+ if (markerChanged) writeRemovedStoresCleanupMarker(Object.fromEntries(nextMarker));
8680
+ }
8681
+ function countMarkerEntries(marker) {
8682
+ let count = 0;
8683
+ for (const storeNames of marker.values()) count += storeNames.length;
8684
+ return count;
8685
+ }
8686
+ function formatStoreNames(storeNames) {
8687
+ return [...storeNames].map((storeName) => `"${storeName}"`).join(", ");
8688
+ }
8689
+ /**
8690
+ * Removes the persisted data of stores deleted from the app, once per store and
8691
+ * adapter, during idle time after startup. Every later startup only reads the
8692
+ * small marker listing the pairs already handled.
8693
+ */
8694
+ function scheduleRemovedStoresCleanup(removedStores, onPersistentStorageError) {
8695
+ if (removedStores.length === 0) return;
8696
+ const reportError = onPersistentStorageError ?? handleManagedLocalStorageBackgroundError;
8697
+ scheduleInitialMaintenanceCleanup(() => {
8698
+ runRemovedStoresCleanup(removedStores, reportError).catch(reportError);
8699
+ });
8700
+ }
8701
+ //#endregion
8316
8702
  //#region src/storeManager.ts
8317
8703
  const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 2400 * 1e3;
8318
8704
  const DEFAULT_BASE_COALESCING_WINDOW_MS = 16;
@@ -8350,6 +8736,7 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
8350
8736
  getOfflineStatus,
8351
8737
  getOfflineEntities: () => EMPTY_OFFLINE_ENTITIES,
8352
8738
  getOfflineResolutions: () => EMPTY_OFFLINE_RESOLUTIONS,
8739
+ resolveOfflineResolution: (resolutionId) => Promise.resolve(Result.err(new OfflineResolutionActionError("offline-not-configured", resolutionId))),
8353
8740
  getOfflineUploads: () => emptyUploads,
8354
8741
  resolveOfflineUpload: () => Promise.resolve(Result.err(/* @__PURE__ */ new Error("[tsdf] Offline uploads are not configured for this manager"))),
8355
8742
  resolveOfflineUploads: () => Promise.resolve(Result.err(/* @__PURE__ */ new Error("[tsdf] Offline uploads are not configured for this manager"))),
@@ -8367,6 +8754,16 @@ function createStoreManager(options) {
8367
8754
  const appVersion = options.getAppVersion?.();
8368
8755
  const debugLogger = import.meta.env.DEV ? resolveTSDFLogger(options.debugLogger) : void 0;
8369
8756
  const logger = resolveTSDFLogger(options.logger ?? true);
8757
+ const removedStores = options.removedStores ?? [];
8758
+ if (import.meta.env.DEV) for (const { id } of removedStores) assertValidPersistentStoreName(id);
8759
+ const registry = {
8760
+ appVersion,
8761
+ unsubscribeFromOfflineRecovery: void 0,
8762
+ removedStoreIds: new Set(removedStores.map(({ id }) => id)),
8763
+ browserTabsPresence: void 0,
8764
+ nextStoreRegistrationId: 0,
8765
+ stores: /* @__PURE__ */ new Map()
8766
+ };
8370
8767
  let resolvedOfflineSession;
8371
8768
  if (options.offlineSession) {
8372
8769
  const createOfflineSessionOptions = {
@@ -8389,6 +8786,22 @@ function createStoreManager(options) {
8389
8786
  getOfflineStatus: () => resolvedOfflineSession.getOfflineStatus(),
8390
8787
  getOfflineEntities: () => resolvedOfflineSession.getOfflineEntities(),
8391
8788
  getOfflineResolutions: () => resolvedOfflineSession.getOfflineResolutions(),
8789
+ resolveOfflineResolution: async (resolutionId, action) => {
8790
+ const storeName = resolvedOfflineSession.getOfflineResolutions().find((resolution) => resolution.id === resolutionId)?.storeName;
8791
+ if (storeName === void 0) return Result.err(new OfflineResolutionActionError("resolution-not-found", resolutionId));
8792
+ let resolveInStore;
8793
+ for (const registeredStore of registry.stores.values()) if (registeredStore.id === storeName) {
8794
+ resolveInStore = registeredStore.resolveOfflineResolution;
8795
+ break;
8796
+ }
8797
+ if (!resolveInStore) return Result.err(new OfflineResolutionActionError("store-not-registered", resolutionId, storeName));
8798
+ try {
8799
+ const failure = await resolveInStore(resolutionId, action);
8800
+ return failure ? Result.err(new OfflineResolutionActionError(failure, resolutionId, storeName)) : Result.ok(void 0);
8801
+ } catch (error) {
8802
+ return Result.err(new OfflineResolutionActionError("action-failed", resolutionId, storeName, normalizeStoreManagerOfflineError(error)));
8803
+ }
8804
+ },
8392
8805
  getOfflineUploads: () => resolvedOfflineSession.getOfflineUploads(),
8393
8806
  resolveOfflineUpload: (id) => resultify(() => resolvedOfflineSession.resolveOfflineUpload(id), normalizeStoreManagerOfflineError),
8394
8807
  resolveOfflineUploads: (ids) => resultify(() => resolvedOfflineSession.resolveOfflineUploads(ids), normalizeStoreManagerOfflineError),
@@ -8401,12 +8814,6 @@ function createStoreManager(options) {
8401
8814
  useOfflineResolutions: () => resolvedOfflineSession.useOfflineResolutions(),
8402
8815
  useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
8403
8816
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
8404
- const registry = {
8405
- appVersion,
8406
- browserTabsPresence: void 0,
8407
- nextStoreRegistrationId: 0,
8408
- stores: /* @__PURE__ */ new Map()
8409
- };
8410
8817
  const storeManager = {
8411
8818
  getSessionKey: options.getSessionKey,
8412
8819
  errorNormalizer: options.errorNormalizer,
@@ -8429,6 +8836,7 @@ function createStoreManager(options) {
8429
8836
  }
8430
8837
  },
8431
8838
  onTransportReconnect: () => {
8839
+ if (recheckIsSessionInOfflineMode(storeManager.getSessionKey())) return;
8432
8840
  for (const registeredStore of [...registry.stores.values()]) registeredStore.onTransportReconnect();
8433
8841
  },
8434
8842
  ...offlineApi
@@ -8437,6 +8845,7 @@ function createStoreManager(options) {
8437
8845
  storeManager.logger = logger;
8438
8846
  storeManagerRegistry.set(storeManager, registry);
8439
8847
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
8848
+ scheduleRemovedStoresCleanup(removedStores, options.onPersistentStorageError);
8440
8849
  return storeManager;
8441
8850
  }
8442
8851
  function getRegistryOrThrow(storeManager) {
@@ -8446,6 +8855,7 @@ function getRegistryOrThrow(storeManager) {
8446
8855
  }
8447
8856
  function registerStoreWithManager(storeManager, store) {
8448
8857
  const registry = getRegistryOrThrow(storeManager);
8858
+ if (registry.removedStoreIds.has(store.id)) throw new Error(`[tsdf] Store id "${store.id}" is listed in the storeManager's removedStores, which removes its persisted data. Remove it from removedStores to use the id again.`);
8449
8859
  let hasDuplicateId = false;
8450
8860
  for (const registeredStore of registry.stores.values()) if (registeredStore.id === store.id) {
8451
8861
  hasDuplicateId = true;
@@ -8455,9 +8865,15 @@ function registerStoreWithManager(storeManager, store) {
8455
8865
  const registrationId = registry.nextStoreRegistrationId;
8456
8866
  registry.nextStoreRegistrationId += 1;
8457
8867
  registry.stores.set(registrationId, store);
8868
+ if (!registry.unsubscribeFromOfflineRecovery) registry.unsubscribeFromOfflineRecovery = subscribeToOfflineRecovery((sessionKey, hasStoreRecovered) => {
8869
+ if (storeManager.getSessionKey() !== sessionKey) return;
8870
+ for (const registeredStore of [...registry.stores.values()]) if (hasStoreRecovered(registeredStore.id)) registeredStore.onOfflineRecovery();
8871
+ });
8458
8872
  return () => {
8459
8873
  registry.stores.delete(registrationId);
8460
8874
  if (registry.stores.size === 0) {
8875
+ registry.unsubscribeFromOfflineRecovery?.();
8876
+ registry.unsubscribeFromOfflineRecovery = void 0;
8461
8877
  registry.browserTabsPresence?.close();
8462
8878
  registry.browserTabsPresence = void 0;
8463
8879
  }
@@ -8630,7 +9046,7 @@ async function performMutationWithLifecycle(startMutation, mutation, onError, op
8630
9046
  //#endregion
8631
9047
  //#region src/utils/storeFocusLifecycle.ts
8632
9048
  /** @internal */
8633
- function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate, onWindowFocusReevaluateDelayedRTU, debug) {
9049
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onReconnectRevalidate, onWindowFocusReevaluateDelayedRTU, getIsOfflineMode, debug) {
8634
9050
  let cleanupFocusListener = null;
8635
9051
  let cleanupReconnectFocusListener = null;
8636
9052
  let reconnectCooldownTimeoutId = null;
@@ -8664,8 +9080,9 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
8664
9080
  });
8665
9081
  } : void 0;
8666
9082
  function runTransportReconnectRevalidate() {
9083
+ if (getIsOfflineMode()) return;
8667
9084
  lastTransportReconnectRevalidateAt = Date.now();
8668
- onTransportReconnectRevalidate();
9085
+ onReconnectRevalidate();
8669
9086
  }
8670
9087
  function ensureReconnectFocusListener() {
8671
9088
  if (cleanupReconnectFocusListener) return;
@@ -8719,6 +9136,13 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
8719
9136
  });
8720
9137
  return;
8721
9138
  }
9139
+ if (getIsOfflineMode()) {
9140
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
9141
+ reason: "offline-mode",
9142
+ status: "skipped"
9143
+ });
9144
+ return;
9145
+ }
8722
9146
  logWindowFocusRevalidate?.("window focus revalidation triggered", {
8723
9147
  policy: typeof revalidateOnWindowFocus === "function" ? "dynamic" : "enabled",
8724
9148
  status: "triggered"
@@ -8747,9 +9171,23 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
8747
9171
  }
8748
9172
  scheduleTrailingTransportReconnectRevalidate();
8749
9173
  }
9174
+ function onOfflineRecovery() {
9175
+ if (!usesRealTimeUpdates || transportReconnectCooldownMs <= 0) {
9176
+ flushTransportReconnectRevalidate();
9177
+ return;
9178
+ }
9179
+ if (hasPendingReconnectRevalidateOnFocus) return;
9180
+ scheduleTrailingTransportReconnectRevalidate();
9181
+ }
9182
+ function flushPendingReconnectRevalidate() {
9183
+ if (reconnectCooldownTimeoutId === null) return;
9184
+ flushTransportReconnectRevalidate();
9185
+ }
8750
9186
  reset();
8751
9187
  return {
8752
9188
  onTransportReconnect,
9189
+ onOfflineRecovery,
9190
+ flushPendingReconnectRevalidate,
8753
9191
  reset,
8754
9192
  dispose
8755
9193
  };
@@ -9445,6 +9883,7 @@ function createCollectionStore(storeOptions) {
9445
9883
  });
9446
9884
  offlineOverlayStore.initializeStore();
9447
9885
  let offlineOverlaySessionKey = null;
9886
+ const unsentCreationItemKeys = /* @__PURE__ */ new Set();
9448
9887
  const itemCacheRuntime = createLruCacheRuntime();
9449
9888
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
9450
9889
  const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
@@ -9482,6 +9921,7 @@ function createCollectionStore(storeOptions) {
9482
9921
  function clearOfflineOverlays(nextSessionKey = null) {
9483
9922
  offlineOverlaySessionKey = nextSessionKey;
9484
9923
  offlineOverlayStore.setState({});
9924
+ unsentCreationItemKeys.clear();
9485
9925
  }
9486
9926
  function rebindOfflineOverlays(itemKeyRewrites) {
9487
9927
  rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
@@ -9546,8 +9986,18 @@ function createCollectionStore(storeOptions) {
9546
9986
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
9547
9987
  rebindOfflineOverlays(itemKeyRewrites);
9548
9988
  },
9989
+ revalidateDiscardedEntities: (entities) => {
9990
+ focusLifecycle.flushPendingReconnectRevalidate();
9991
+ for (const { entityKey, payload } of entities) {
9992
+ const item = store.state[entityKey];
9993
+ if (item) invalidateItem(item.payload, "highPriority");
9994
+ else if (item === null && payload !== void 0) scheduleFetch("highPriority", __LEGIT_CAST__(payload));
9995
+ }
9996
+ },
9549
9997
  syncEntityOverlays: ({ entities, sessionKey }) => {
9550
9998
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
9999
+ unsentCreationItemKeys.clear();
10000
+ for (const entity of entities) if (entity.tempId !== void 0) unsentCreationItemKeys.add(entity.entityKey);
9551
10001
  const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
9552
10002
  offlineOverlayStore.produceState((draft) => {
9553
10003
  for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
@@ -9958,6 +10408,7 @@ function createCollectionStore(storeOptions) {
9958
10408
  for (const { itemKey } of itemsKey) {
9959
10409
  const item = store.state[itemKey];
9960
10410
  if (!item) continue;
10411
+ if (unsentCreationItemKeys.has(itemKey)) continue;
9961
10412
  if ((item.refetchOnMount ? fetchTypePriority[item.refetchOnMount] : -1) >= fetchTypePriority[priority]) continue;
9962
10413
  store.produceState((draft) => {
9963
10414
  const draftItem = draft[itemKey];
@@ -10212,14 +10663,17 @@ function createCollectionStore(storeOptions) {
10212
10663
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
10213
10664
  return result;
10214
10665
  }
10666
+ function getIsOfflineMode() {
10667
+ return recheckIsSessionInOfflineMode(storeManager.getSessionKey());
10668
+ }
10215
10669
  const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
10216
10670
  invalidateItem(() => true, "lowPriority");
10217
10671
  }, () => {
10218
- invalidateItem(() => true, "realtimeUpdate");
10672
+ invalidateItem(() => true, usesRealTimeUpdates ? "realtimeUpdate" : "highPriority");
10219
10673
  }, () => {
10220
10674
  for (const scheduler of batchKeySchedulers.values()) scheduler.reevaluateDelayedRTU();
10221
10675
  for (const scheduler of perItemSchedulers.values()) scheduler.reevaluateDelayedRTU();
10222
- }, import.meta.env.DEV ? {
10676
+ }, getIsOfflineMode, import.meta.env.DEV ? {
10223
10677
  debugLogger: storeManager.debugLogger,
10224
10678
  storeId: id,
10225
10679
  storeType: "collection"
@@ -10350,7 +10804,9 @@ function createCollectionStore(storeOptions) {
10350
10804
  const unregisterStoreFromManager = registerStoreWithManager(storeManager, {
10351
10805
  id,
10352
10806
  reset,
10353
- onTransportReconnect
10807
+ onTransportReconnect,
10808
+ onOfflineRecovery: focusLifecycle.onOfflineRecovery,
10809
+ resolveOfflineResolution: offlineController?.resolveOfflineResolutionWithGenericAction
10354
10810
  });
10355
10811
  return {
10356
10812
  store,
@@ -10653,6 +11109,10 @@ function createDocumentStore(storeOptions) {
10653
11109
  entityKey: DOC_TARGET_KEY,
10654
11110
  entityKind: "document"
10655
11111
  }],
11112
+ revalidateDiscardedEntities: () => {
11113
+ focusLifecycle.flushPendingReconnectRevalidate();
11114
+ invalidateData("highPriority");
11115
+ },
10656
11116
  getProtectedCacheKeys: () => {
10657
11117
  const sessionKey = getSessionKeyForRuntime();
10658
11118
  if (sessionKey === false) return [];
@@ -10855,13 +11315,16 @@ function createDocumentStore(storeOptions) {
10855
11315
  usesRealTimeUpdates
10856
11316
  });
10857
11317
  if (initialStatus !== "idle" || initialData !== null || initialError !== null) scheduler.setLastFetchStartTimeForRequest(DOC_REQUEST_ID, testOptions?.initialLastFetchStartTime ?? 0);
11318
+ function getIsOfflineMode() {
11319
+ return recheckIsSessionInOfflineMode(storeManager.getSessionKey());
11320
+ }
10858
11321
  const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
10859
11322
  invalidateData("lowPriority");
10860
11323
  }, () => {
10861
- invalidateData("realtimeUpdate");
11324
+ invalidateData(usesRealTimeUpdates ? "realtimeUpdate" : "highPriority");
10862
11325
  }, () => {
10863
11326
  scheduler.reevaluateDelayedRTU();
10864
- }, import.meta.env.DEV ? {
11327
+ }, getIsOfflineMode, import.meta.env.DEV ? {
10865
11328
  debugLogger: storeManager.debugLogger,
10866
11329
  storeId: id,
10867
11330
  storeType: "document"
@@ -11195,7 +11658,9 @@ function createDocumentStore(storeOptions) {
11195
11658
  const unregisterStoreFromManager = registerStoreWithManager(storeManager, {
11196
11659
  id,
11197
11660
  reset,
11198
- onTransportReconnect
11661
+ onTransportReconnect,
11662
+ onOfflineRecovery: focusLifecycle.onOfflineRecovery,
11663
+ resolveOfflineResolution: offlineController?.resolveOfflineResolutionWithGenericAction
11199
11664
  });
11200
11665
  return {
11201
11666
  store,
@@ -14415,7 +14880,7 @@ const GET_ALL = () => true;
14415
14880
  //#endregion
14416
14881
  //#region src/listQueryStore/createMutationApi.ts
14417
14882
  /** @internal */
14418
- function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler, onItemMutationsEnd) {
14883
+ function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler, onItemMutationsEnd, unsentCreationItemKeys) {
14419
14884
  const storeEvents = evtmitter();
14420
14885
  const deferredOptimisticQueryInvalidationsStack = [];
14421
14886
  const optimisticMutationQueryContextStack = [];
@@ -14640,6 +15105,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14640
15105
  const itemsKey = getItemsKeyArray(itemPayload);
14641
15106
  const staleInvalidateFieldsByItemKey = /* @__PURE__ */ new Map();
14642
15107
  for (const { itemKey } of itemsKey) {
15108
+ if (unsentCreationItemKeys.has(itemKey)) continue;
14643
15109
  const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
14644
15110
  const staleInvalidateFields = effectiveLoadedFields === "*" ? invalidateFields : invalidateFields.filter((field) => effectiveLoadedFields?.includes(field) ?? false);
14645
15111
  if (staleInvalidateFields.length < invalidateFields.length) {
@@ -14701,6 +15167,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14701
15167
  for (const { itemKey, payload } of itemsKey) {
14702
15168
  const item = store.state.itemQueries[itemKey];
14703
15169
  if (!item) continue;
15170
+ if (unsentCreationItemKeys.has(itemKey)) continue;
14704
15171
  const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
14705
15172
  const itemWasFullyLoaded = partialResources && effectiveLoadedFields === "*";
14706
15173
  const existingPendingFields = itemPendingInvalidationFields.get(itemKey);
@@ -16252,7 +16719,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16252
16719
  return storeState.map((result, index) => {
16253
16720
  const queryConfig = queriesWithId[index];
16254
16721
  if (result.status !== "loading" && result.status !== "idle") return result;
16255
- if (queryConfig && readFallbackQueryState && !(derivedQueries && (isOfflineMode || stickyDerivedQueryKeys.has(queryConfig.key)))) {
16722
+ if (queryConfig && readFallbackQueryState && !store.state.queries[queryConfig.key]?.wasLoaded && !(derivedQueries && (isOfflineMode || stickyDerivedQueryKeys.has(queryConfig.key)))) {
16256
16723
  const fallbackQuery = readFallbackQueryState(queryConfig.key);
16257
16724
  if (fallbackQuery && readFallbackItemState) {
16258
16725
  const visibleItemKeys = getVisibleQueryItemKeys(result.queryKey, fallbackQuery.items);
@@ -16304,7 +16771,8 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16304
16771
  isOfflineMode,
16305
16772
  offlineEntitiesByKey,
16306
16773
  selectVisibleItems,
16307
- stickyDerivedQueryKeys
16774
+ stickyDerivedQueryKeys,
16775
+ store
16308
16776
  ]);
16309
16777
  const autoFetchSignals = store.useSelector(useCallback((state) => {
16310
16778
  if (!partialResources) return [];
@@ -16703,6 +17171,7 @@ function createListQueryStore(storeOptions) {
16703
17171
  });
16704
17172
  offlineOverlayStore.initializeStore();
16705
17173
  let offlineOverlaySessionKey = null;
17174
+ const unsentCreationItemKeys = /* @__PURE__ */ new Set();
16706
17175
  const itemCacheRuntime = createLruCacheRuntime();
16707
17176
  const queryCacheRuntime = createLruCacheRuntime();
16708
17177
  const offsetPagination = storeOptions.offsetPagination;
@@ -17053,7 +17522,7 @@ function createListQueryStore(storeOptions) {
17053
17522
  events.emit("invalidateItem", event);
17054
17523
  }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler, () => {
17055
17524
  revalidateAfterIgnoredConfirmedSnapshots();
17056
- });
17525
+ }, unsentCreationItemKeys);
17057
17526
  if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
17058
17527
  normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
17059
17528
  const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
@@ -17115,8 +17584,23 @@ function createListQueryStore(storeOptions) {
17115
17584
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
17116
17585
  rebindOfflineOverlays(itemKeyRewrites);
17117
17586
  },
17587
+ revalidateDiscardedEntities: (entities, hasPendingResolutions) => {
17588
+ focusLifecycle.flushPendingReconnectRevalidate();
17589
+ invalidateQueryAndItems({
17590
+ itemPayload: filterAndMap(entities, (ref) => store.state.itemQueries[ref.entityKey]?.payload ?? false),
17591
+ queryPayload: hasPendingResolutions ? false : () => true,
17592
+ type: "highPriority"
17593
+ });
17594
+ if (!fetchItemFn) return;
17595
+ for (const { entityKey, payload } of entities) {
17596
+ if (store.state.itemQueries[entityKey] !== null || payload === void 0) continue;
17597
+ scheduleItemFetch("highPriority", __LEGIT_CAST__(payload), { fields: "*" });
17598
+ }
17599
+ },
17118
17600
  syncEntityOverlays: ({ entities, sessionKey }) => {
17119
17601
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
17602
+ unsentCreationItemKeys.clear();
17603
+ for (const entity of entities) if (entity.entityKind === "item" && entity.tempId !== void 0) unsentCreationItemKeys.add(entity.entityKey);
17120
17604
  const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
17121
17605
  offlineOverlayStore.produceState((draft) => {
17122
17606
  for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
@@ -17199,6 +17683,7 @@ function createListQueryStore(storeOptions) {
17199
17683
  function clearOfflineOverlays(nextSessionKey = null) {
17200
17684
  offlineOverlaySessionKey = nextSessionKey;
17201
17685
  offlineOverlayStore.setState({});
17686
+ unsentCreationItemKeys.clear();
17202
17687
  }
17203
17688
  function rebindOfflineOverlays(itemKeyRewrites) {
17204
17689
  rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
@@ -17476,6 +17961,9 @@ function createListQueryStore(storeOptions) {
17476
17961
  function useFindItem$1(findItemFn, options = {}) {
17477
17962
  return useFindItem(findItemFn, options, store, registerActiveStandaloneItems, touchItems);
17478
17963
  }
17964
+ function getIsOfflineMode() {
17965
+ return recheckIsSessionInOfflineMode(storeManager.getSessionKey());
17966
+ }
17479
17967
  const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
17480
17968
  invalidateQueryAndItems({
17481
17969
  all: true,
@@ -17484,9 +17972,9 @@ function createListQueryStore(storeOptions) {
17484
17972
  }, () => {
17485
17973
  invalidateQueryAndItems({
17486
17974
  all: true,
17487
- type: "realtimeUpdate"
17975
+ type: usesRealTimeUpdates ? "realtimeUpdate" : "highPriority"
17488
17976
  });
17489
- }, reevaluateDelayedRTUs, import.meta.env.DEV ? {
17977
+ }, reevaluateDelayedRTUs, getIsOfflineMode, import.meta.env.DEV ? {
17490
17978
  debugLogger: storeManager.debugLogger,
17491
17979
  storeId: id,
17492
17980
  storeType: "listQuery"
@@ -17661,7 +18149,9 @@ function createListQueryStore(storeOptions) {
17661
18149
  const unregisterStoreFromManager = registerStoreWithManager(storeManager, {
17662
18150
  id,
17663
18151
  reset,
17664
- onTransportReconnect
18152
+ onTransportReconnect,
18153
+ onOfflineRecovery: focusLifecycle.onOfflineRecovery,
18154
+ resolveOfflineResolution: offlineController?.resolveOfflineResolutionWithGenericAction
17665
18155
  });
17666
18156
  return {
17667
18157
  store,
@@ -17768,7 +18258,8 @@ const storedUploadMetadataRecordSchema = rc_object({
17768
18258
  p: uploadProgressSchema.optionalKey(),
17769
18259
  e: lastErrorSchema.optionalKey(),
17770
18260
  g: rc_number.optionalKey(),
17771
- l: rc_number
18261
+ l: rc_number,
18262
+ d: validPayloadSchema.optionalKey()
17772
18263
  });
17773
18264
  function serializeStoredUploadMetadataRecord(record) {
17774
18265
  return JSON.stringify({
@@ -17785,7 +18276,8 @@ function serializeStoredUploadMetadataRecord(record) {
17785
18276
  ...record.progress !== void 0 ? { p: record.progress } : {},
17786
18277
  ...record.lastError !== void 0 ? { e: record.lastError } : {},
17787
18278
  ...record.lastOnlineSessionStartedAt !== void 0 ? { g: record.lastOnlineSessionStartedAt } : {},
17788
- l: record.lastModified
18279
+ l: record.lastModified,
18280
+ ...record.metadata !== void 0 ? { d: record.metadata } : {}
17789
18281
  });
17790
18282
  }
17791
18283
  function parseStoredUploadMetadataRecord(raw) {
@@ -17805,7 +18297,8 @@ function parseStoredUploadMetadataRecord(raw) {
17805
18297
  ...compactRecord.p !== void 0 ? { progress: compactRecord.p } : {},
17806
18298
  ...compactRecord.e !== void 0 ? { lastError: compactRecord.e } : {},
17807
18299
  ...compactRecord.g !== void 0 ? { lastOnlineSessionStartedAt: compactRecord.g } : {},
17808
- lastModified: compactRecord.l
18300
+ lastModified: compactRecord.l,
18301
+ ...compactRecord.d !== void 0 ? { metadata: compactRecord.d } : {}
17809
18302
  };
17810
18303
  }
17811
18304
  var OpfsOfflineUploadDriver = class {