tsdf 18.2.0 → 18.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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),
@@ -3866,7 +3986,11 @@ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWin
3866
3986
  }
3867
3987
  //#endregion
3868
3988
  //#region src/utils/browserTabsSync.ts
3869
- const PROTOCOL_VERSION = 1;
3989
+ /**
3990
+ * Bump when a message shape changes: tabs running another tsdf release then
3991
+ * ignore each other instead of misreading messages.
3992
+ */
3993
+ const PROTOCOL_VERSION = 2;
3870
3994
  const CHANNEL_PREFIX = "tsdf";
3871
3995
  function createBrowserTabsChannelName(storeType, storeKey, appVersion) {
3872
3996
  return `${CHANNEL_PREFIX}${appVersion === void 0 ? "" : `:app:${encodeURIComponent(appVersion)}`}:${storeType}:${storeKey}`;
@@ -4137,10 +4261,10 @@ function parseSyncMessage(message, storeType) {
4137
4261
  //#endregion
4138
4262
  //#region src/persistentStorage/offlineUploadsShared.ts
4139
4263
  function stripStoredUploadFile(record) {
4140
- const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, ...upload } = record;
4264
+ const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, storeName: _storeName, ...upload } = record;
4141
4265
  return upload;
4142
4266
  }
4143
- function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt) {
4267
+ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt, metadata, storeName) {
4144
4268
  const file = normalizeUploadFile(fileInput, id);
4145
4269
  const now = Date.now();
4146
4270
  const createdAt = createdAtInput ?? now;
@@ -4159,8 +4283,10 @@ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, crea
4159
4283
  ...progress !== void 0 ? { progress } : {},
4160
4284
  ...lastError !== void 0 ? { lastError } : {},
4161
4285
  ...lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt } : {},
4286
+ ...metadata !== void 0 ? { metadata } : {},
4162
4287
  file,
4163
- lastModified: file.lastModified
4288
+ lastModified: file.lastModified,
4289
+ ...storeName !== void 0 ? { storeName } : {}
4164
4290
  };
4165
4291
  }
4166
4292
  function normalizeUploadFile(file, fallbackName) {
@@ -4194,6 +4320,59 @@ const defaultStatusBySession = /* @__PURE__ */ new Map();
4194
4320
  const registry = /* @__PURE__ */ new Map();
4195
4321
  const uploadsConfigByOfflineSession = /* @__PURE__ */ new WeakMap();
4196
4322
  const appVersionByOfflineSession = /* @__PURE__ */ new WeakMap();
4323
+ const offlineRecoveryListeners = /* @__PURE__ */ new Set();
4324
+ /**
4325
+ * The stores (by name) that cannot be revalidated against the server yet, or
4326
+ * `null` when no store of the session can:
4327
+ *
4328
+ * - offline, or with queued mutations still to replay: anything fetched now
4329
+ * may predate the replayed mutations, in any store
4330
+ * - a store with changes waiting for a manual resolution: a refetch would
4331
+ * replace the local changes the user still has to decide on
4332
+ */
4333
+ function getStoresAwaitingRecovery(state) {
4334
+ if (state.status.isOfflineMode || state.hasQueuedMutations) return null;
4335
+ const storeNames = /* @__PURE__ */ new Set();
4336
+ for (const entity of state.entities) {
4337
+ if (entity.pendingMutations > 0) return null;
4338
+ if (entity.requiresResolution) storeNames.add(entity.storeName);
4339
+ }
4340
+ for (const resolution of state.resolutions) storeNames.add(resolution.storeName);
4341
+ return storeNames;
4342
+ }
4343
+ /**
4344
+ * Subscribes to stores recovering in this tab (any session key; listeners
4345
+ * filter by the key they care about). A store recovers when its session is
4346
+ * back online with its queued mutations replayed and the store has no change
4347
+ * left waiting for a manual resolution: from then on its cached data can be
4348
+ * revalidated against the server.
4349
+ * @internal
4350
+ */
4351
+ function subscribeToOfflineRecovery(listener) {
4352
+ offlineRecoveryListeners.add(listener);
4353
+ return () => {
4354
+ offlineRecoveryListeners.delete(listener);
4355
+ };
4356
+ }
4357
+ /**
4358
+ * Whether the session is in offline mode in this tab, without creating or
4359
+ * reconfiguring its coordinator (a session nothing tracks is online).
4360
+ *
4361
+ * While it is, also re-checks connectivity: callers ask on a hint that the
4362
+ * connection may be back (a transport reconnect, a window focus), and some
4363
+ * setups have nothing else that ends offline mode (a custom `getIsOffline`
4364
+ * without browser events, a classified network failure without a recovery
4365
+ * check). Leaving offline mode notifies the recovery listeners, which
4366
+ * revalidate the stores, so callers skip their own revalidation either way.
4367
+ * @internal
4368
+ */
4369
+ function recheckIsSessionInOfflineMode(sessionKey) {
4370
+ if (sessionKey === false) return false;
4371
+ const coordinator = registry.get(sessionKey);
4372
+ if (!coordinator?.getStatus().isOfflineMode) return false;
4373
+ coordinator.recheckNetworkState();
4374
+ return true;
4375
+ }
4197
4376
  const DEFAULT_UPLOAD_CONCURRENCY = 3;
4198
4377
  const OFFLINE_UPLOAD_RETENTION_MS = 10080 * 60 * 1e3;
4199
4378
  const OFFLINE_UPLOAD_RETENTION_STABLE_ONLINE_MS = 5e3;
@@ -4402,6 +4581,12 @@ var SessionOfflineCoordinator = class {
4402
4581
  store;
4403
4582
  #registrations = /* @__PURE__ */ new Map();
4404
4583
  #storeContributions = /* @__PURE__ */ new Map();
4584
+ /**
4585
+ * Latest entities and resolutions other tabs reported for their stores. Only
4586
+ * used for stores this tab has not attached, e.g. a store only another tab
4587
+ * created.
4588
+ */
4589
+ #remoteStoreItems = /* @__PURE__ */ new Map();
4405
4590
  #adapters = /* @__PURE__ */ new Set();
4406
4591
  #sessionHandle;
4407
4592
  #browserTabs;
@@ -4421,11 +4606,14 @@ var SessionOfflineCoordinator = class {
4421
4606
  #classificationToken = 0;
4422
4607
  #retriableFailureToken = 0;
4423
4608
  #networkStateToken = 0;
4609
+ #isRecheckingNetworkState = false;
4424
4610
  #lastRemoteSnapshotAt = 0;
4425
4611
  #recoveryTimer = null;
4426
4612
  #scheduledRecoveryMode = null;
4427
4613
  #recoveryAttempt = 0;
4428
4614
  #classifiedNetworkActive = false;
4615
+ /** Tabs of this session that sent anything on the session channel. */
4616
+ #otherTabIds = /* @__PURE__ */ new Set();
4429
4617
  #networkEnabledOverride;
4430
4618
  #outageEnabledOverride;
4431
4619
  #mutationQueueingOverrides;
@@ -4467,18 +4655,65 @@ var SessionOfflineCoordinator = class {
4467
4655
  status: bootstrappedLocalSnapshot?.status ?? resolveDefaultStatus(sessionKey, { bootstrapStatusFromLocalStorage: shouldBootstrapFromStorage }),
4468
4656
  entities: [],
4469
4657
  resolutions: [],
4470
- uploads: []
4658
+ uploads: [],
4659
+ hasQueuedMutations: false
4471
4660
  })
4472
4661
  });
4473
4662
  this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
4663
+ this.store.subscribe(({ prev, current }) => {
4664
+ if (prev.entities === current.entities && prev.resolutions === current.resolutions && prev.hasQueuedMutations === current.hasQueuedMutations && prev.status.isOfflineMode === current.status.isOfflineMode) return;
4665
+ const awaitingStores = getStoresAwaitingRecovery(current);
4666
+ if (awaitingStores === null) return;
4667
+ const prevAwaitingStores = getStoresAwaitingRecovery(prev);
4668
+ if (prevAwaitingStores?.size === 0) return;
4669
+ for (const listener of offlineRecoveryListeners) listener(sessionKey, (storeName) => !awaitingStores.has(storeName) && (prevAwaitingStores === null || prevAwaitingStores.has(storeName)));
4670
+ });
4474
4671
  this.#browserTabs = createBrowserTabsCoordinatorWithPriority("offline", `session:${sessionKey}`, () => this.sessionKey, (message) => {
4672
+ const isNewTab = !this.#otherTabIds.has(message.tabId);
4673
+ this.#otherTabIds.add(message.tabId);
4475
4674
  if (message.kind === "tab-status") {
4476
4675
  this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
4676
+ if (isNewTab) {
4677
+ this.#browserTabs.priority.publishLocalStatus();
4678
+ this.#publishSnapshot();
4679
+ }
4477
4680
  this.#refreshLeadership();
4478
4681
  return;
4479
4682
  }
4683
+ if (message.kind === "offline-queue-entry") {
4684
+ this.#registrations.get(message.storeName)?.onRemoteQueueEntryChange?.(message.entryId, message.entry);
4685
+ return;
4686
+ }
4687
+ if (message.kind === "offline-resolution") {
4688
+ this.#registrations.get(message.storeName)?.onRemoteResolutionChange?.(message.resolutionId, message.resolution);
4689
+ return;
4690
+ }
4691
+ if (message.kind === "offline-temp-reconciled") {
4692
+ this.#registrations.get(message.storeName)?.onRemoteTempReconciled?.(message.tempId, message.finalPayload);
4693
+ return;
4694
+ }
4695
+ if (message.kind === "offline-work-discarded") {
4696
+ this.#registrations.get(message.storeName)?.onRemoteWorkDiscarded?.(message.discardedWork, message.removedTempEntityKeys);
4697
+ return;
4698
+ }
4480
4699
  this.#applyRemoteSnapshot(message);
4481
- }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, void 0, void 0, void 0, options.appVersion);
4700
+ }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, (noteFocusChange) => {
4701
+ if (!isWindowAvailable()) return () => {};
4702
+ const onChange = () => {
4703
+ noteFocusChange();
4704
+ this.#refreshLeadership();
4705
+ };
4706
+ window.addEventListener("focus", onChange);
4707
+ window.addEventListener("blur", onChange);
4708
+ window.addEventListener("pagehide", onChange);
4709
+ document.addEventListener("visibilitychange", onChange);
4710
+ return () => {
4711
+ window.removeEventListener("focus", onChange);
4712
+ window.removeEventListener("blur", onChange);
4713
+ window.removeEventListener("pagehide", onChange);
4714
+ document.removeEventListener("visibilitychange", onChange);
4715
+ };
4716
+ }, void 0, void 0, options.appVersion);
4482
4717
  this.#refreshLeadership();
4483
4718
  if (shouldBootstrapFromStorage) this.hydrate();
4484
4719
  if (this.#hasCanonicalConfig) this.#refreshNetworkConfig();
@@ -4521,7 +4756,7 @@ var SessionOfflineCoordinator = class {
4521
4756
  if (this.#uploadsConfig) try {
4522
4757
  const uploads = await this.#uploadsConfig.adapter.list(this.sessionKey);
4523
4758
  if (hydrationToken === this.#hydrationToken) {
4524
- this.#uploads = new Map(uploads.map((upload) => [upload.id, upload]));
4759
+ this.#uploads = new Map([...uploads.map((upload) => [upload.id, upload]), ...this.#uploads]);
4525
4760
  this.#syncUploadsState();
4526
4761
  this.#scheduleUploadOnlineSessionStabilization();
4527
4762
  this.#refreshUploadRetention();
@@ -4537,12 +4772,12 @@ var SessionOfflineCoordinator = class {
4537
4772
  if (import.meta.env.DEV && options.debugLogger !== void 0) this.#debugLogger = options.debugLogger;
4538
4773
  if (options.uploads !== void 0) {
4539
4774
  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({
4775
+ if (!sameUploadsConfig(this.#uploadsConfig, options.uploads)) this.#uploadQueue = createAsyncQueue({
4543
4776
  autoStart: true,
4544
4777
  concurrency: options.uploads.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY
4545
4778
  });
4779
+ this.#uploadsConfig = options.uploads;
4780
+ registerOfflineUploadAdapterForSession(this.sessionKey, options.uploads.adapter);
4546
4781
  this.hydrate();
4547
4782
  }
4548
4783
  if (!this.#hasCanonicalConfig && options.config) {
@@ -4578,18 +4813,66 @@ var SessionOfflineCoordinator = class {
4578
4813
  return () => {
4579
4814
  this.#registrations.delete(registration.storeName);
4580
4815
  this.#storeContributions.delete(registration.storeName);
4816
+ this.#remoteStoreItems.delete(registration.storeName);
4581
4817
  this.#refreshAggregates();
4582
4818
  this.#notifyGreenCycle();
4583
4819
  if (this.#registrations.size === 0) this.#stopRecoveryProbe();
4584
4820
  };
4585
4821
  }
4586
- syncStoreData(storeName, contribution) {
4822
+ syncStoreData(storeName, contribution, isRemoteChange = false) {
4587
4823
  if (this.#disposed) return;
4588
4824
  const replayHeadChanged = !replayHeadsEqual(this.#storeContributions.get(storeName)?.replayHead, contribution.replayHead);
4589
4825
  this.#storeContributions.set(storeName, contribution);
4590
- this.#refreshAggregates();
4826
+ this.#refreshAggregates(!isRemoteChange);
4591
4827
  if (replayHeadChanged) this.#notifyGreenCycle();
4592
4828
  }
4829
+ /** Tells the other tabs that this tab saved or removed (`null`) a queue entry. */
4830
+ publishQueueEntryChange(storeName, entryId, entry) {
4831
+ if (this.#disposed) return;
4832
+ this.#browserTabs.coordinator.publish({
4833
+ kind: "offline-queue-entry",
4834
+ storeName,
4835
+ entryId,
4836
+ entry
4837
+ });
4838
+ }
4839
+ /** Tells the other tabs that this tab saved or removed (`null`) a resolution. */
4840
+ publishResolutionChange(storeName, resolutionId, resolution) {
4841
+ if (this.#disposed) return;
4842
+ this.#browserTabs.coordinator.publish({
4843
+ kind: "offline-resolution",
4844
+ storeName,
4845
+ resolutionId,
4846
+ resolution
4847
+ });
4848
+ }
4849
+ /** Tells the other tabs that this tab reconciled a temp entity. */
4850
+ publishTempReconciled(storeName, tempId, finalPayload) {
4851
+ if (this.#disposed) return;
4852
+ this.#browserTabs.coordinator.publish({
4853
+ kind: "offline-temp-reconciled",
4854
+ storeName,
4855
+ tempId,
4856
+ finalPayload
4857
+ });
4858
+ }
4859
+ /** Tells the other tabs that this tab discarded queued work of a store. */
4860
+ publishWorkDiscarded(storeName, discardedWork, removedTempEntityKeys) {
4861
+ if (this.#disposed) return;
4862
+ this.#browserTabs.coordinator.publish({
4863
+ kind: "offline-work-discarded",
4864
+ storeName,
4865
+ discardedWork,
4866
+ removedTempEntityKeys
4867
+ });
4868
+ }
4869
+ /**
4870
+ * Whether another tab of this session was seen. While `false`, this tab is
4871
+ * the only one changing the queue, so it can skip the cross-tab safeguards.
4872
+ */
4873
+ hasOtherTabs() {
4874
+ return this.#otherTabIds.size > 0;
4875
+ }
4593
4876
  canReplayEntry(args) {
4594
4877
  const nextReplayHead = [...this.#storeContributions.values()].map((contribution) => contribution.replayHead).filter((head) => head !== null).sort(compareReplayHeads)[0];
4595
4878
  if (!nextReplayHead) return true;
@@ -4639,17 +4922,19 @@ var SessionOfflineCoordinator = class {
4639
4922
  }
4640
4923
  async saveUpload(args) {
4641
4924
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
4925
+ if (this.#uploadPromisesById.has(args.id)) throw new Error(`Cannot change upload "${args.id}" while it is queued or uploading`);
4642
4926
  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());
4927
+ 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, args.storeName);
4644
4928
  await this.#saveUploadRecord(nextRecord);
4645
4929
  }
4646
4930
  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`);
4931
+ const existing = await this.#getUploadRecord(args.id);
4649
4932
  await this.saveUpload({
4650
4933
  id: args.id,
4651
4934
  file: args.file,
4652
- source: existing?.source ?? "manual"
4935
+ source: existing?.source ?? "manual",
4936
+ metadata: args.metadata ?? existing?.metadata,
4937
+ storeName: existing?.storeName
4653
4938
  });
4654
4939
  }
4655
4940
  async loadUpload(id) {
@@ -4803,6 +5088,18 @@ var SessionOfflineCoordinator = class {
4803
5088
  this.setNetworkActive(false, { classified: false });
4804
5089
  return false;
4805
5090
  }
5091
+ /**
5092
+ * Re-checks connectivity on a hint that it may be back. Hints from several
5093
+ * stores (e.g. their window-focus handlers) share a re-check still in flight
5094
+ * instead of calling `getIsOffline` once per store.
5095
+ */
5096
+ recheckNetworkState() {
5097
+ if (this.#isRecheckingNetworkState) return;
5098
+ this.#isRecheckingNetworkState = true;
5099
+ this.refreshNetworkState().finally(() => {
5100
+ this.#isRecheckingNetworkState = false;
5101
+ });
5102
+ }
4806
5103
  async refreshNetworkState() {
4807
5104
  const token = ++this.#networkStateToken;
4808
5105
  const detectedOffline = this.#getCurrentOfflineState();
@@ -4913,6 +5210,8 @@ var SessionOfflineCoordinator = class {
4913
5210
  if (existing) return existing;
4914
5211
  if (!this.#uploadsConfig) return null;
4915
5212
  const loaded = await this.#uploadsConfig.adapter.load(this.sessionKey, id);
5213
+ const current = this.#uploads.get(id);
5214
+ if (current) return current;
4916
5215
  if (loaded) {
4917
5216
  this.#uploads.set(id, loaded);
4918
5217
  this.#syncUploadsState();
@@ -5063,6 +5362,7 @@ var SessionOfflineCoordinator = class {
5063
5362
  id,
5064
5363
  sessionKey: this.sessionKey,
5065
5364
  file,
5365
+ metadata: queuedRecord.metadata,
5066
5366
  onProgress: (progress) => {
5067
5367
  this.#updateUploadState({
5068
5368
  id,
@@ -5103,31 +5403,51 @@ var SessionOfflineCoordinator = class {
5103
5403
  async #cleanupUnusedMutationUploads() {
5104
5404
  const uploadsConfig = this.#uploadsConfig;
5105
5405
  if (!uploadsConfig) return;
5106
- const removableIds = [...this.#uploads.values()].filter((upload) => upload.source === "mutation").map((upload) => upload.id).filter((id) => !this.#referencedUploadIds.has(id) && !this.#uploadPromisesById.has(id));
5406
+ const removableIds = [...this.#uploads.values()].filter((upload) => upload.source === "mutation" && (upload.storeName !== void 0 ? this.#registrations.has(upload.storeName) : [...this.#registrations.keys()].some((storeName) => upload.id.startsWith(`${storeName}:`)))).map((upload) => upload.id).filter((id) => !this.#referencedUploadIds.has(id) && !this.#uploadPromisesById.has(id));
5107
5407
  if (removableIds.length === 0) return;
5108
5408
  for (const id of removableIds) this.#uploads.delete(id);
5109
5409
  await Promise.all(removableIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
5110
5410
  this.#syncUploadsState();
5111
5411
  this.#refreshUploadRetention();
5112
5412
  }
5113
- #refreshAggregates() {
5413
+ /**
5414
+ * The session-wide lists: this tab's own stores, plus what other tabs
5415
+ * reported for the stores this tab has not attached.
5416
+ */
5417
+ #buildItemLists() {
5114
5418
  const allEntities = [];
5115
5419
  const allResolutions = [];
5116
- const referencedUploadIds = /* @__PURE__ */ new Set();
5117
- const nextProtectedKeysByAdapter = /* @__PURE__ */ new Map();
5420
+ let hasQueuedMutations = false;
5118
5421
  for (const contribution of this.#storeContributions.values()) {
5422
+ if (contribution.replayHead !== null) hasQueuedMutations = true;
5119
5423
  allEntities.push(...contribution.entities);
5120
5424
  allResolutions.push(...contribution.resolutions);
5425
+ }
5426
+ for (const [storeName, items] of this.#remoteStoreItems) {
5427
+ if (this.#storeContributions.has(storeName)) continue;
5428
+ if (items.hasQueuedMutations) hasQueuedMutations = true;
5429
+ allEntities.push(...items.entities);
5430
+ allResolutions.push(...items.resolutions);
5431
+ }
5432
+ return {
5433
+ entities: dedupeById(allEntities),
5434
+ resolutions: dedupeById(allResolutions),
5435
+ hasQueuedMutations
5436
+ };
5437
+ }
5438
+ #refreshAggregates(publish = true) {
5439
+ const referencedUploadIds = /* @__PURE__ */ new Set();
5440
+ const nextProtectedKeysByAdapter = /* @__PURE__ */ new Map();
5441
+ for (const contribution of this.#storeContributions.values()) {
5121
5442
  for (const uploadId of contribution.referencedUploadIds) referencedUploadIds.add(uploadId);
5122
5443
  const existing = nextProtectedKeysByAdapter.get(contribution.adapter) ?? [];
5123
5444
  existing.push(...contribution.protectedKeys);
5124
5445
  nextProtectedKeysByAdapter.set(contribution.adapter, existing);
5125
5446
  }
5126
- const entities = dedupeById(allEntities);
5127
- const resolutions = dedupeById(allResolutions);
5447
+ const { entities, resolutions, hasQueuedMutations } = this.#buildItemLists();
5128
5448
  for (const [adapter, keys] of nextProtectedKeysByAdapter) nextProtectedKeysByAdapter.set(adapter, [...new Set(keys)].sort());
5129
5449
  const nextProtectedKeys = [...new Set([...nextProtectedKeysByAdapter.values()].flat())].sort();
5130
- const adaptersToSync = new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]);
5450
+ const adaptersToSync = publish ? new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]) : /* @__PURE__ */ new Set();
5131
5451
  const debugLogger = this.#debugLogger;
5132
5452
  const sessionKey = this.sessionKey;
5133
5453
  const emitSyncProtectedKeysLog = (adapterKind, status, count, startTime, error) => {
@@ -5170,7 +5490,7 @@ var SessionOfflineCoordinator = class {
5170
5490
  });
5171
5491
  }
5172
5492
  }
5173
- this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
5493
+ if (publish) this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
5174
5494
  this.#referencedUploadIds = referencedUploadIds;
5175
5495
  if (!arraysEqual(this.#protectedKeys, nextProtectedKeys)) {
5176
5496
  this.#protectedKeys = nextProtectedKeys;
@@ -5178,11 +5498,12 @@ var SessionOfflineCoordinator = class {
5178
5498
  }
5179
5499
  this.store.setPartialState({
5180
5500
  entities,
5181
- resolutions
5501
+ resolutions,
5502
+ hasQueuedMutations
5182
5503
  }, { action: "offline-session-aggregate" });
5183
5504
  this.#persistSessionSnapshot();
5184
- this.#publishSnapshot();
5185
- if (this.#uploadsConfig && this.#uploads.size > 0 && this.#storeContributions.size === this.#registrations.size) this.#cleanupUnusedMutationUploads();
5505
+ if (publish) this.#publishSnapshot();
5506
+ if (publish && this.#uploadsConfig && this.#uploads.size > 0 && this.#storeContributions.size === this.#registrations.size) this.#cleanupUnusedMutationUploads();
5186
5507
  }
5187
5508
  #stampLocalStatus(status) {
5188
5509
  return {
@@ -5213,29 +5534,50 @@ var SessionOfflineCoordinator = class {
5213
5534
  #publishSnapshot() {
5214
5535
  if (this.#disposed) return;
5215
5536
  const status = this.store.state.status;
5537
+ const contributions = [...this.#storeContributions.values()];
5216
5538
  this.#browserTabs.coordinator.publish({
5217
5539
  kind: "offline-session-snapshot",
5218
5540
  status,
5219
- entities: this.store.state.entities,
5220
- resolutions: this.store.state.resolutions,
5221
- uploads: this.store.state.uploads
5541
+ storeNames: [...this.#storeContributions.keys()],
5542
+ entities: contributions.flatMap((contribution) => contribution.entities),
5543
+ resolutions: contributions.flatMap((contribution) => contribution.resolutions),
5544
+ uploads: this.store.state.uploads,
5545
+ queuedStoreNames: [...this.#storeContributions].filter(([, contribution]) => contribution.replayHead !== null).map(([storeName]) => storeName)
5222
5546
  });
5223
5547
  }
5224
5548
  #applyRemoteSnapshot(message) {
5225
- if (message.sentAt < this.#lastRemoteSnapshotAt) return;
5549
+ for (const storeName of message.storeNames) this.#remoteStoreItems.set(storeName, {
5550
+ entities: message.entities.filter((entity) => entity.storeName === storeName),
5551
+ resolutions: message.resolutions.filter((resolution) => resolution.storeName === storeName),
5552
+ hasQueuedMutations: message.queuedStoreNames.includes(storeName)
5553
+ });
5554
+ if (message.sentAt < this.#lastRemoteSnapshotAt) {
5555
+ this.store.setPartialState(this.#buildItemLists(), { action: "offline-session-remote" });
5556
+ this.#persistSessionSnapshot();
5557
+ return;
5558
+ }
5226
5559
  this.#lastRemoteSnapshotAt = message.sentAt;
5560
+ const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5561
+ const wasReplayBlocked = this.isReplayBlocked();
5562
+ const isDetectedOffline = this.#isNetworkEnabled() && (this.store.state.status.network.active && !this.#classifiedNetworkActive || !this.#browserReportsOnline());
5227
5563
  this.store.setState({
5228
- status: this.#restampHydratedStatus(message.status, {
5564
+ status: this.#restampHydratedStatus(isDetectedOffline ? {
5565
+ ...message.status,
5566
+ network: {
5567
+ ...message.status.network,
5568
+ active: true
5569
+ }
5570
+ } : message.status, {
5229
5571
  isLeader: this.isLeader(),
5230
5572
  updatedAt: Date.now()
5231
5573
  }),
5232
- entities: message.entities,
5233
- resolutions: message.resolutions,
5574
+ ...this.#buildItemLists(),
5234
5575
  uploads: message.uploads
5235
5576
  }, { action: "offline-session-remote" });
5236
- this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5577
+ if (!isDetectedOffline) this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5237
5578
  this.#persistSessionSnapshot();
5238
5579
  this.#refreshLeadership();
5580
+ this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5239
5581
  }
5240
5582
  #shouldPersistSessionSnapshot() {
5241
5583
  return this.store.state.status.isOfflineMode || this.store.state.entities.length > 0 || this.store.state.resolutions.length > 0 || this.#protectedKeys.length > 0;
@@ -5480,21 +5822,23 @@ function createOfflineSession(args) {
5480
5822
  if (!coordinator) throw new Error(`[tsdf] Offline uploads are not configured for inactive session scope "${inactiveScope}"`);
5481
5823
  return castResolvedUploadRefs(await coordinator.resolveUploadIds(ids));
5482
5824
  },
5483
- saveOfflineUpload: ({ id, file }) => {
5825
+ saveOfflineUpload: ({ id, file, metadata }) => {
5484
5826
  const coordinator = getActiveCoordinator();
5485
5827
  if (!coordinator) return Promise.resolve();
5486
5828
  return coordinator.saveUpload({
5487
5829
  id,
5488
5830
  file,
5831
+ metadata,
5489
5832
  source: "manual"
5490
5833
  });
5491
5834
  },
5492
- replaceOfflineUpload: ({ id, file }) => {
5835
+ replaceOfflineUpload: ({ id, file, metadata }) => {
5493
5836
  const coordinator = getActiveCoordinator();
5494
5837
  if (!coordinator) return Promise.resolve();
5495
5838
  return coordinator.replaceUpload({
5496
5839
  id,
5497
- file
5840
+ file,
5841
+ metadata
5498
5842
  });
5499
5843
  },
5500
5844
  loadOfflineUpload: (id) => {
@@ -5613,6 +5957,12 @@ function useOfflineStoreResolutions(args) {
5613
5957
  //#region src/persistentStorage/offline/storeController.ts
5614
5958
  const DEFAULT_REPLAY_RETRY_MAX_FAILURES = 3;
5615
5959
  const DEFAULT_REPLAY_RETRY_INTERVAL_MS = 5e3;
5960
+ /**
5961
+ * Time given to a tab to learn about the queue changes of the tab that just
5962
+ * replayed, before it may replay itself.
5963
+ */
5964
+ const REPLAY_HANDOFF_SETTLE_MS = 500;
5965
+ const REPLAY_LOCK_UNAVAILABLE_WARNING = "[TSDF] navigator.locks is unavailable; with several tabs open, a queued offline mutation can be sent more than once.";
5616
5966
  const BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE = "Blocked by unresolved dependency";
5617
5967
  const compactOfflineEntitySchema = rc_object({
5618
5968
  k: rc_string,
@@ -5802,12 +6152,16 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
5802
6152
  let replayRetryTimer = null;
5803
6153
  let hydratedSessionKey = null;
5804
6154
  let hydratedPromise = null;
6155
+ let releaseReplayLock = null;
6156
+ let heldReplayLockName = null;
6157
+ let replayLockReleaseTimer = null;
5805
6158
  let nextQueueOrder = 0;
5806
6159
  const replayRetryMaxFailures = sessionConfig.replayRetry?.maxFailures ?? DEFAULT_REPLAY_RETRY_MAX_FAILURES;
5807
6160
  const replayRetryIntervalMs = sessionConfig.replayRetry?.intervalMs ?? DEFAULT_REPLAY_RETRY_INTERVAL_MS;
5808
6161
  const queueEntries = /* @__PURE__ */ new Map();
5809
6162
  const resolutions = /* @__PURE__ */ new Map();
5810
6163
  const countedReplayFailures = /* @__PURE__ */ new Map();
6164
+ const entryIdsFromAnotherTab = /* @__PURE__ */ new Set();
5811
6165
  const resolvedEntityRefBySerializedRef = /* @__PURE__ */ new Map();
5812
6166
  function getActiveMutationQueueingCause(current) {
5813
6167
  const status = current.session.getStatus();
@@ -5824,8 +6178,31 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
5824
6178
  function resolveMutationQueueingPolicy(cause) {
5825
6179
  return ensureActiveSession()?.session.getRuntimeConfig().mutationQueueing[cause] ?? "allow";
5826
6180
  }
5827
- function getInitialOfflineMutationAction(current) {
5828
- if (!current.session.getStatus().isOfflineMode) return "run";
6181
+ function getOperationRawEntityRefs(operation, operationName, validatedInput) {
6182
+ return typeof operation.getEntityRefs === "function" ? operation.getEntityRefs({ input: validatedInput }) : storeAdapter.getEntityRefs?.({
6183
+ operationName,
6184
+ input: validatedInput
6185
+ }) ?? [];
6186
+ }
6187
+ /**
6188
+ * Whether mutations queued earlier for the entities this mutation affects
6189
+ * or depends on (`dependsOn`), or that depend on an entity this mutation
6190
+ * affects, are still waiting to reach the server (queued, replaying or
6191
+ * unconfirmed).
6192
+ */
6193
+ function hasQueuedWorkForSameEntities(prepared) {
6194
+ if (queueEntries.size === 0) return false;
6195
+ const affectedEntityRefs = prepared.entityRefs ?? resolveNormalizedRefs(getOperationRawEntityRefs(prepared.operation, prepared.operationName, prepared.validatedInput));
6196
+ const entityRefs = [...affectedEntityRefs, ...prepared.operation.dependsOn ? resolveNormalizedRefs(prepared.operation.dependsOn({ input: prepared.validatedInput })) : []];
6197
+ for (const entry of queueEntries.values()) {
6198
+ for (const queuedEntityRef of entry.entityRefs) if (entityRefs.some((entityRef) => isSameEntityRef(entityRef, queuedEntityRef))) return true;
6199
+ const queuedDependencyKeys = getDependencyBlockerEntityKeys(entry);
6200
+ if (affectedEntityRefs.some((entityRef) => queuedDependencyKeys.has(entityRef.entityKey))) return true;
6201
+ }
6202
+ return false;
6203
+ }
6204
+ function getInitialOfflineMutationAction(current, prepared) {
6205
+ if (!current.session.getStatus().isOfflineMode) return hasQueuedWorkForSameEntities(prepared) ? "queue" : "run";
5829
6206
  const cause = getActiveMutationQueueingCause(current);
5830
6207
  if (cause === null) return "run";
5831
6208
  if (isMutationQueueingAllowed(cause)) return "queue";
@@ -5891,8 +6268,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
5891
6268
  activeSession?.unregister?.();
5892
6269
  activeSession = null;
5893
6270
  resetReplayRetryState();
6271
+ if (!replayScheduled) releaseHeldReplayLock();
5894
6272
  resolvedEntityRefBySerializedRef.clear();
5895
6273
  queueEntries.clear();
6274
+ entryIdsFromAnotherTab.clear();
5896
6275
  resolutions.clear();
5897
6276
  nextQueueOrder = 0;
5898
6277
  hydratedSessionKey = null;
@@ -6050,6 +6429,36 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6050
6429
  },
6051
6430
  onOfflineCycle: () => {
6052
6431
  resetReplayRetryState();
6432
+ },
6433
+ onRemoteQueueEntryChange: (entryId, entry) => {
6434
+ applyRecordChangeFromAnotherTab(() => {
6435
+ if (entry) {
6436
+ nextQueueOrder = Math.max(nextQueueOrder, getQueueOrder(entry) + 1);
6437
+ if (!operations[entry.operation]) return;
6438
+ queueEntries.set(entryId, entry);
6439
+ entryIdsFromAnotherTab.add(entryId);
6440
+ return;
6441
+ }
6442
+ queueEntries.delete(entryId);
6443
+ entryIdsFromAnotherTab.delete(entryId);
6444
+ countedReplayFailures.delete(entryId);
6445
+ if (queueEntries.size === 0) clearReplayRetryTimer();
6446
+ });
6447
+ },
6448
+ onRemoteResolutionChange: (resolutionId, resolution) => {
6449
+ applyRecordChangeFromAnotherTab(() => {
6450
+ if (resolution && rc_parse(resolution, offlineResolutionRecordSchema).ok && operations[resolution.operation]) resolutions.set(resolutionId, resolution);
6451
+ else resolutions.delete(resolutionId);
6452
+ });
6453
+ },
6454
+ onRemoteWorkDiscarded: (discardedWork, removedTempEntityKeys) => {
6455
+ applyRecordChangeFromAnotherTab(() => {
6456
+ revalidateDiscardedWork(discardedWork, new Set(removedTempEntityKeys));
6457
+ });
6458
+ },
6459
+ onRemoteTempReconciled: (tempId, finalPayload) => {
6460
+ rememberResolvedEntityRef(tempId, finalPayload);
6461
+ storeAdapter.applyTempReconciliationFromAnotherTab?.(tempId, finalPayload);
6053
6462
  }
6054
6463
  }),
6055
6464
  queueNamespace,
@@ -6068,6 +6477,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6068
6477
  const [loadedQueueEntries, loadedResolutionEntries] = await Promise.all([loadNamespaceRecords(current.queueNamespace), loadNamespaceRecords(current.resolutionNamespace)]);
6069
6478
  if (!isActiveSessionState(current)) return;
6070
6479
  queueEntries.clear();
6480
+ entryIdsFromAnotherTab.clear();
6071
6481
  resolutions.clear();
6072
6482
  for (const entry of loadedQueueEntries.values()) queueEntries.set(entry.id, entry);
6073
6483
  for (const resolution of loadedResolutionEntries.values()) {
@@ -6089,6 +6499,25 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6089
6499
  });
6090
6500
  return hydratedPromise;
6091
6501
  }
6502
+ /**
6503
+ * Applies to this tab's in-memory queue a record change made by another tab,
6504
+ * so the leader replays entries queued by any tab and every tab stops
6505
+ * showing (and can never replay) an entry another tab already replayed.
6506
+ */
6507
+ function applyRecordChangeFromAnotherTab(applyChange, changeSession = activeSession) {
6508
+ const current = activeSession;
6509
+ if (!current || current !== changeSession) return;
6510
+ if (hydratedPromise) {
6511
+ const applyAfterHydration = () => {
6512
+ applyRecordChangeFromAnotherTab(applyChange, current);
6513
+ };
6514
+ hydratedPromise.then(applyAfterHydration, applyAfterHydration);
6515
+ return;
6516
+ }
6517
+ if (hydratedSessionKey !== current.sessionKey) return;
6518
+ applyChange();
6519
+ refreshDerivedState(current, true);
6520
+ }
6092
6521
  function parseConflictPayloadForOperation(operationName, conflict) {
6093
6522
  const operation = operations[operationName];
6094
6523
  if (!operation) return Result.err(new OfflineResolutionConflictParseError({
@@ -6217,7 +6646,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6217
6646
  };
6218
6647
  }).sort(compareResolutionRecords));
6219
6648
  }
6220
- function refreshDerivedState(current) {
6649
+ function refreshDerivedState(current, isRemoteChange) {
6221
6650
  const session = current ?? ensureActiveSession();
6222
6651
  if (!session || !isActiveSessionState(session)) return;
6223
6652
  const sessionState = session;
@@ -6303,6 +6732,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6303
6732
  entityKind: entity.entityKind
6304
6733
  })));
6305
6734
  const nextReplayEntry = getSortedEntries()[0] ?? null;
6735
+ storeAdapter.syncEntityOverlays?.({
6736
+ sessionKey: sessionState.sessionKey,
6737
+ entities
6738
+ });
6306
6739
  sessionState.session.syncStoreData(storeName, {
6307
6740
  adapter,
6308
6741
  entities,
@@ -6315,12 +6748,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6315
6748
  queueOrder: getQueueOrder(nextReplayEntry),
6316
6749
  createdAt: nextReplayEntry.createdAt
6317
6750
  }
6318
- });
6319
- storeAdapter.syncEntityOverlays?.({
6320
- sessionKey: sessionState.sessionKey,
6321
- entities
6322
- });
6323
- syncEntityNamespace(sessionState, entities);
6751
+ }, isRemoteChange);
6752
+ if (!isRemoteChange) syncEntityNamespace(sessionState, entities);
6324
6753
  }
6325
6754
  async function syncEntityNamespace(current, entities) {
6326
6755
  await current.entityNamespace.replaceAll(entities.map((entity) => ({
@@ -6382,6 +6811,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6382
6811
  if (entry.operation !== args.operationName) continue;
6383
6812
  if (entry.syncState !== "pending") continue;
6384
6813
  if (entry.attempts > 0) continue;
6814
+ if (entryIdsFromAnotherTab.has(entry.id)) continue;
6385
6815
  if (entry.tempIds && entry.tempIds.length > 0) continue;
6386
6816
  if (normalizeEntityRefs(entry.entityRefs) !== normalizedEntityRefs) continue;
6387
6817
  if (!candidate || compareQueueEntries(entry, candidate) < 0) candidate = entry;
@@ -6582,6 +7012,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6582
7012
  };
6583
7013
  resolutions.set(rewrittenResolution.id, rewrittenResolution);
6584
7014
  await args.current.resolutionNamespace.save(rewrittenResolution.id, rewrittenResolution);
7015
+ args.current.session.publishResolutionChange(storeName, rewrittenResolution.id, rewrittenResolution);
6585
7016
  entityRefRewrites.push({
6586
7017
  previousEntityRefs: resolution.entityRefs,
6587
7018
  nextEntityRefs: rewrittenResolution.entityRefs
@@ -6620,6 +7051,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6620
7051
  const tempId = args.tempIds[0];
6621
7052
  if (tempId === void 0) return;
6622
7053
  const reconciliation = tempEntity.reconcileServerEntity(args.result, tempId);
7054
+ args.current.session.publishTempReconciled(storeName, tempId, reconciliation.finalPayload);
6623
7055
  storeAdapter.reconcileTempEntity({
6624
7056
  operationName: args.operationName,
6625
7057
  input: args.input,
@@ -6647,6 +7079,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6647
7079
  }))
6648
7080
  });
6649
7081
  for (const reconciliation of reconciliations) {
7082
+ args.current.session.publishTempReconciled(storeName, reconciliation.tempId, reconciliation.finalPayload);
6650
7083
  storeAdapter.reconcileTempEntity({
6651
7084
  operationName: args.operationName,
6652
7085
  input: args.input,
@@ -6667,6 +7100,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6667
7100
  if (!session) return;
6668
7101
  if (isActiveSessionState(session)) queueEntries.set(entry.id, entry);
6669
7102
  await session.queueNamespace.save(entry.id, entry);
7103
+ session.session.publishQueueEntryChange(storeName, entry.id, entry);
6670
7104
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6671
7105
  }
6672
7106
  function runSuccessfulExecuteSync(args) {
@@ -6684,9 +7118,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6684
7118
  if (!session) return;
6685
7119
  if (isActiveSessionState(session)) {
6686
7120
  queueEntries.delete(entryId);
7121
+ entryIdsFromAnotherTab.delete(entryId);
6687
7122
  countedReplayFailures.delete(entryId);
6688
7123
  if (queueEntries.size === 0) clearReplayRetryTimer();
6689
7124
  }
7125
+ session.session.publishQueueEntryChange(storeName, entryId, null);
6690
7126
  await session.queueNamespace.remove(entryId);
6691
7127
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6692
7128
  }
@@ -6695,6 +7131,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6695
7131
  if (!session) return;
6696
7132
  if (isActiveSessionState(session)) resolutions.set(resolution.id, resolution);
6697
7133
  await session.resolutionNamespace.save(resolution.id, resolution);
7134
+ session.session.publishResolutionChange(storeName, resolution.id, resolution);
6698
7135
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6699
7136
  }
6700
7137
  async function removeResolution(resolutionId, current, skipRefresh) {
@@ -6702,6 +7139,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6702
7139
  if (!session) return;
6703
7140
  if (isActiveSessionState(session)) resolutions.delete(resolutionId);
6704
7141
  await session.resolutionNamespace.remove(resolutionId);
7142
+ session.session.publishResolutionChange(storeName, resolutionId, null);
6705
7143
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6706
7144
  }
6707
7145
  function collectTempCreateDescendants(args) {
@@ -6780,13 +7218,13 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6780
7218
  for (const entry of descendants.queueEntries) descendantQueueEntries.set(entry.id, entry);
6781
7219
  }
6782
7220
  for (const dependentEntry of descendantQueueEntries.values()) {
6783
- await removeEntry(dependentEntry.id, args.current, true);
6784
7221
  await persistResolution(buildRetryExhaustedResolutionRecord(args.current, dependentEntry, { message: BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE }), args.current, true);
7222
+ await removeEntry(dependentEntry.id, args.current, true);
6785
7223
  }
6786
7224
  }
6787
7225
  async function persistManualResolutionChain(args) {
6788
- await removeEntry(args.parentEntry.id, args.current, true);
6789
7226
  await persistResolution(args.parentResolution, args.current, true);
7227
+ await removeEntry(args.parentEntry.id, args.current, true);
6790
7228
  await promoteBlockedTempCreateDescendants({
6791
7229
  current: args.current,
6792
7230
  parentEntry: args.parentEntry,
@@ -6802,6 +7240,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6802
7240
  const parentEntityKeys = getTempLifecycleEntityKeys(args.resolution);
6803
7241
  if (parentEntityKeys.length === 0) {
6804
7242
  refreshDerivedState(args.current);
7243
+ revalidateDiscardedWorkInEveryTab(args.current, [args.resolution], /* @__PURE__ */ new Set());
6805
7244
  return;
6806
7245
  }
6807
7246
  const descendantQueueEntries = /* @__PURE__ */ new Map();
@@ -6820,6 +7259,49 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6820
7259
  for (const resolution of descendantResolutions.values()) rollbackTempCreatePendingEntity(resolution);
6821
7260
  rollbackTempCreatePendingEntity(args.resolution);
6822
7261
  refreshDerivedState(args.current);
7262
+ const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7263
+ const removedTempEntityKeys = new Set(parentEntityKeys);
7264
+ for (const workItem of discardedWork) for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedTempEntityKeys.add(entityKey);
7265
+ revalidateDiscardedWorkInEveryTab(args.current, discardedWork, removedTempEntityKeys);
7266
+ }
7267
+ /**
7268
+ * {@link revalidateDiscardedWork} in this tab and in the other tabs with the
7269
+ * store: each one may show the discarded optimistic changes.
7270
+ */
7271
+ function revalidateDiscardedWorkInEveryTab(current, discardedWork, removedTempEntityKeys) {
7272
+ revalidateDiscardedWork(discardedWork, removedTempEntityKeys);
7273
+ if (!discardedWork.some((workItem) => workItem.entityRefs.length > 0)) return;
7274
+ current.session.publishWorkDiscarded(storeName, discardedWork.map(({ operation, input, entityRefs }) => ({
7275
+ operation,
7276
+ input,
7277
+ entityRefs
7278
+ })), [...removedTempEntityKeys]);
7279
+ }
7280
+ /**
7281
+ * Refetches the entities discarded queued work referenced (its optimistic
7282
+ * changes cannot be rolled back locally), except the removed temp entities
7283
+ * and the entities other changes still wait for a decision on: a refetch
7284
+ * would replace those changes. The recovery revalidation refetches them
7285
+ * once the last one is handled.
7286
+ */
7287
+ function revalidateDiscardedWork(discardedWork, removedTempEntityKeys) {
7288
+ const entities = [];
7289
+ const skippedEntityKeys = new Set(removedTempEntityKeys);
7290
+ for (const resolution of resolutions.values()) for (const ref of resolution.entityRefs) skippedEntityKeys.add(ref.entityKey);
7291
+ for (const workItem of discardedWork) for (const ref of workItem.entityRefs) {
7292
+ if (skippedEntityKeys.has(ref.entityKey)) continue;
7293
+ skippedEntityKeys.add(ref.entityKey);
7294
+ entities.push({
7295
+ ...ref,
7296
+ payload: getPayloadForEntityRef({
7297
+ operationName: workItem.operation,
7298
+ input: workItem.input,
7299
+ entityKey: ref.entityKey
7300
+ })
7301
+ });
7302
+ }
7303
+ if (entities.length === 0) return;
7304
+ storeAdapter.revalidateDiscardedEntities?.(entities, resolutions.size > 0);
6823
7305
  }
6824
7306
  function collectRetryResolutionChain(args) {
6825
7307
  if (args.scope === "self") return [args.resolution];
@@ -6901,7 +7383,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6901
7383
  return result;
6902
7384
  }
6903
7385
  async function planPreparedMutation(args) {
6904
- const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue } = args;
7386
+ const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue, replacedResolutionId } = args;
6905
7387
  const tempEntity = operation.tempEntity;
6906
7388
  const tempEntities = operation.tempEntities;
6907
7389
  if (operation.accumulation && operation.supersedes) throw new Error(`Offline operation "${operationName}" cannot configure accumulation and supersedes together`);
@@ -6909,10 +7391,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6909
7391
  if (storeType === "document" && (tempEntity || tempEntities)) throw new Error(`Document offline operation "${operationName}" does not support tempEntity or tempEntities`);
6910
7392
  if ((tempEntity || tempEntities) && "onSuccessExecute" in operation) throw new Error(`Offline operation "${operationName}" cannot configure onSuccessExecute when tempEntity or tempEntities is present`);
6911
7393
  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
- }) ?? [];
7394
+ const rawEntityRefs = getOperationRawEntityRefs(operation, operationName, validatedInput);
6916
7395
  const resolvedEntityRefs = resolveNormalizedRefs(rawEntityRefs);
6917
7396
  const hasTempLifecycle = tempEntity !== void 0 || tempEntities !== void 0;
6918
7397
  const entityRefs = hasTempLifecycle && preparedTempIds !== void 0 && preparedEntityRefs !== void 0 ? preparedEntityRefs : resolvedEntityRefs;
@@ -6932,7 +7411,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6932
7411
  entityRefs,
6933
7412
  tempIds,
6934
7413
  entries: workingQueue.values(),
6935
- resolutionEntries: resolutions.values()
7414
+ resolutionEntries: replacedResolutionId ? [...resolutions.values()].filter((resolution) => resolution.id !== replacedResolutionId) : resolutions.values()
6936
7415
  });
6937
7416
  if (duplicateTempEntityKey !== null) throw new Error(`Offline operation "${operationName}" cannot queue temp entity "${duplicateTempEntityKey}" more than once while it is still pending`);
6938
7417
  }
@@ -6963,9 +7442,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6963
7442
  });
6964
7443
  const validatedMergedInput = validateWithSchema(operation.inputSchema, mergedInput);
6965
7444
  if (validatedMergedInput === null) throw new Error(`Invalid accumulated offline operation input for "${operationName}"`);
7445
+ const mergedDependencyUploadIds = getDependencyUploadIds({
7446
+ operationName,
7447
+ input: validatedMergedInput
7448
+ });
6966
7449
  const nextEntry = {
6967
7450
  ...existingEntry,
6968
7451
  input: validatedMergedInput,
7452
+ dependencyUploadIds: mergedDependencyUploadIds.length > 0 ? mergedDependencyUploadIds : void 0,
6969
7453
  updatedAt: now
6970
7454
  };
6971
7455
  workingQueue.set(nextEntry.id, nextEntry);
@@ -6975,7 +7459,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6975
7459
  tempIds,
6976
7460
  pendingEntities,
6977
7461
  nextEntry,
6978
- removedEntries: [existingEntry]
7462
+ removedEntries: [existingEntry],
7463
+ accumulatedEntry: existingEntry
6979
7464
  };
6980
7465
  }
6981
7466
  }
@@ -7014,18 +7499,22 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7014
7499
  removedEntries: supersededEntries
7015
7500
  };
7016
7501
  }
7017
- async function queuePreparedMutations(preparedMutation) {
7502
+ async function queuePreparedMutations(preparedMutation, replacedResolutionId) {
7018
7503
  const current = ensureActiveSession();
7019
7504
  if (!current || current.sessionKey !== preparedMutation.currentSessionKey) throw new OfflineSessionUnavailableError();
7020
7505
  const { queueOrders, nextQueueOrderValue } = previewQueueOrders(1);
7021
7506
  const queueOrder = queueOrders[0];
7022
7507
  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
- });
7508
+ let plannedMutation;
7509
+ do
7510
+ plannedMutation = await planPreparedMutation({
7511
+ current,
7512
+ preparedMutation,
7513
+ queueOrder,
7514
+ workingQueue: new Map(queueEntries),
7515
+ replacedResolutionId
7516
+ });
7517
+ while (plannedMutation.accumulatedEntry && queueEntries.get(plannedMutation.accumulatedEntry.id) !== plannedMutation.accumulatedEntry);
7029
7518
  const persistedMutations = [];
7030
7519
  const persistedUploadIds = [];
7031
7520
  const appliedPendingMutations = [];
@@ -7047,7 +7536,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7047
7536
  return current.session.saveUpload({
7048
7537
  id: storedUploadId,
7049
7538
  file,
7050
- source: "mutation"
7539
+ source: "mutation",
7540
+ storeName
7051
7541
  });
7052
7542
  }));
7053
7543
  }
@@ -7112,19 +7602,84 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7112
7602
  }
7113
7603
  if (replayScheduled || replayRetryTimer !== null || current.session.getStatus().isOfflineMode || current.session.isReplayBlocked() || !current.session.isLeader() || queueEntries.size === 0) return;
7114
7604
  replayScheduled = true;
7605
+ const replaySession = current;
7115
7606
  replayQueue.resultifyAdd(async () => {
7116
7607
  try {
7117
- await drainReplay();
7608
+ await acquireReplayLock(replaySession);
7609
+ try {
7610
+ await drainReplay(replaySession);
7611
+ } finally {
7612
+ if (replaySession.session.hasOtherTabs()) replayLockReleaseTimer = setTimeout(releaseHeldReplayLock, REPLAY_HANDOFF_SETTLE_MS);
7613
+ else releaseHeldReplayLock();
7614
+ }
7118
7615
  } finally {
7119
7616
  replayScheduled = false;
7120
7617
  if (getSortedEntries()[0]?.syncState === "needs-confirmation") scheduleReplayRetry();
7618
+ if (!isActiveSessionState(replaySession)) ensureReplayScheduled();
7121
7619
  }
7122
7620
  });
7123
7621
  }
7124
- async function drainReplay() {
7622
+ /**
7623
+ * Leadership is decided from tab presence messages, so for a moment two tabs
7624
+ * can both consider themselves the leader (e.g. while it moves to the tab
7625
+ * that just got focus). This cross-tab lock makes sure only one of them
7626
+ * replays this store's queue at a time.
7627
+ */
7628
+ async function acquireReplayLock(current) {
7629
+ const lockManager = getNavigatorLockManager();
7630
+ if (lockManager === null) {
7631
+ if (current.session.hasOtherTabs()) warnIfNavigatorLockUnavailable(REPLAY_LOCK_UNAVAILABLE_WARNING);
7632
+ return;
7633
+ }
7634
+ if (replayLockReleaseTimer !== null) {
7635
+ clearTimeout(replayLockReleaseTimer);
7636
+ replayLockReleaseTimer = null;
7637
+ }
7638
+ const lockName = `tsdf:offline-replay:${current.sessionKey}:${storeName}`;
7639
+ if (heldReplayLockName === lockName) return;
7640
+ releaseHeldReplayLock();
7641
+ if (await requestReplayLock(lockManager, lockName, true)) return;
7642
+ await requestReplayLock(lockManager, lockName, false);
7643
+ await new Promise((resolve) => {
7644
+ setTimeout(resolve, REPLAY_HANDOFF_SETTLE_MS);
7645
+ });
7646
+ }
7647
+ /**
7648
+ * Resolves `true` once this tab holds the lock (until
7649
+ * `releaseHeldReplayLock`), or `false` when `ifAvailable` is set and another
7650
+ * tab holds it.
7651
+ */
7652
+ function requestReplayLock(lockManager, lockName, ifAvailable) {
7653
+ return new Promise((onSettled) => {
7654
+ lockManager.request(lockName, { ifAvailable }, (lock) => {
7655
+ if (lock === null) {
7656
+ onSettled(false);
7657
+ return;
7658
+ }
7659
+ return new Promise((release) => {
7660
+ heldReplayLockName = lockName;
7661
+ releaseReplayLock = release;
7662
+ onSettled(true);
7663
+ });
7664
+ }).catch(() => {
7665
+ onSettled(true);
7666
+ });
7667
+ });
7668
+ }
7669
+ function releaseHeldReplayLock() {
7670
+ if (replayLockReleaseTimer !== null) {
7671
+ clearTimeout(replayLockReleaseTimer);
7672
+ replayLockReleaseTimer = null;
7673
+ }
7674
+ releaseReplayLock?.();
7675
+ releaseReplayLock = null;
7676
+ heldReplayLockName = null;
7677
+ }
7678
+ async function drainReplay(replaySession) {
7125
7679
  while (true) {
7126
7680
  const current = ensureActiveSession();
7127
7681
  if (!current) return;
7682
+ if (current.sessionKey !== replaySession.sessionKey) return;
7128
7683
  if (current.session.getStatus().isOfflineMode || current.session.isReplayBlocked() || !current.session.isLeader()) return;
7129
7684
  const nextEntry = getSortedEntries()[0];
7130
7685
  if (!nextEntry) return;
@@ -7253,7 +7808,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7253
7808
  parentEntry: entryToUse,
7254
7809
  parentResolution: buildRetryExhaustedResolutionRecord(current, entryToUse, lastError)
7255
7810
  });
7256
- return;
7811
+ continue;
7257
7812
  }
7258
7813
  await persistEntry(entryToUse, current);
7259
7814
  return;
@@ -7281,7 +7836,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7281
7836
  });
7282
7837
  await current.session.refreshNetworkState();
7283
7838
  return {
7284
- initialAction: getInitialOfflineMutationAction(current),
7839
+ initialAction: getInitialOfflineMutationAction(current, prepared),
7285
7840
  queueMutation: () => queuePreparedMutations(prepared),
7286
7841
  handleDirectSuccess: () => clearOfflineStatusOnSuccess(prepared.currentSessionKey),
7287
7842
  classifyError: async (error) => {
@@ -7356,11 +7911,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7356
7911
  }) : null
7357
7912
  };
7358
7913
  });
7359
- for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
7360
7914
  for (const nextEntry of nextEntries) {
7361
7915
  if (!nextEntry.entry) continue;
7362
7916
  await persistEntry(nextEntry.entry, current, true);
7363
7917
  }
7918
+ for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
7364
7919
  storeAdapter.captureQueuedMutationOverlays?.({
7365
7920
  sessionKey: current.sessionKey,
7366
7921
  entityRefs: nextEntries.flatMap((nextEntry) => {
@@ -7381,13 +7936,13 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7381
7936
  return;
7382
7937
  }
7383
7938
  if (action === "requeue") {
7384
- await removeResolution(resolutionId, current, true);
7385
7939
  await queuePreparedMutations(prepareMutationWithSession(current, {
7386
7940
  operation: operationName,
7387
7941
  input: resolutionAction?.input,
7388
7942
  tempIds: resolutionRecord.tempIds,
7389
7943
  entityRefs: resolutionRecord.entityRefs
7390
- }));
7944
+ }), resolutionId);
7945
+ await removeResolution(resolutionId, current);
7391
7946
  return;
7392
7947
  }
7393
7948
  if (action === "commit") {
@@ -7405,6 +7960,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7405
7960
  }
7406
7961
  throw new Error("Invalid offline resolution action");
7407
7962
  }
7963
+ async function resolveOfflineResolutionWithGenericAction(resolutionId, action) {
7964
+ await hydrateIfNeeded();
7965
+ const resolutionRecord = ensureActiveSession() ? resolutions.get(resolutionId) : void 0;
7966
+ if (!resolutionRecord) return "resolution-not-found";
7967
+ if (action === "retry" && resolutionRecord.kind !== "retry-exhausted") return "retry-not-supported";
7968
+ if (isPersistedResolutionBlocked(resolutionRecord)) return "resolution-blocked";
7969
+ await resolveOfflineResolution(resolutionId, resolutionRecord.operation, { action });
7970
+ }
7408
7971
  async function evaluateOfflineFetchError(error, operationName) {
7409
7972
  const current = ensureActiveSession();
7410
7973
  if (!current) return;
@@ -7447,6 +8010,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7447
8010
  getOfflineResolutions,
7448
8011
  parseOfflineResolutionConflict: parseConflictPayloadForResolution,
7449
8012
  resolveOfflineResolution,
8013
+ resolveOfflineResolutionWithGenericAction,
7450
8014
  prepareForFetch,
7451
8015
  getSessionStatus,
7452
8016
  shouldTreatFetchAsOffline,
@@ -8313,6 +8877,115 @@ var RequestScheduler = class {
8313
8877
  }
8314
8878
  };
8315
8879
  //#endregion
8880
+ //#region src/persistentStorage/removedStoresCleanup.ts
8881
+ /**
8882
+ * Removes the stores' data from `localStorage` in every session, found
8883
+ * through their manifests. Must run inside the managed `localStorage` lock.
8884
+ */
8885
+ function removeStoresFromLocalStorage(storeNames) {
8886
+ const storeNameByStorageKey = /* @__PURE__ */ new Map();
8887
+ for (const key of localPersistentStorage.listRawKeys("tsdf.")) {
8888
+ const owner = parseManagedLocalStorageManifestOwner(key);
8889
+ if (owner === null || !storeNames.has(owner.storeName)) continue;
8890
+ storeNameByStorageKey.set(owner.storageKey, owner.storeName);
8891
+ }
8892
+ const unsentRecordsByStore = /* @__PURE__ */ new Map();
8893
+ for (const [storageKey, storeName] of storeNameByStorageKey) {
8894
+ const unsentRecords = removeStoreLeftoversFromLocalStorage(storageKey, false);
8895
+ unsentRecordsByStore.set(storeName, (unsentRecordsByStore.get(storeName) ?? 0) + unsentRecords);
8896
+ }
8897
+ return unsentRecordsByStore;
8898
+ }
8899
+ /** Marker key of the `'local-sync'` adapter. */
8900
+ const LOCAL_SYNC_STORAGE_ID = "local-sync";
8901
+ async function runRemovedStoresCleanup(removedStores, reportError) {
8902
+ let cleanedMarker;
8903
+ try {
8904
+ cleanedMarker = new Map(Object.entries(readRemovedStoresCleanupMarker()));
8905
+ } catch {
8906
+ return;
8907
+ }
8908
+ const cleanups = /* @__PURE__ */ new Map();
8909
+ const unsupportedStoreNames = /* @__PURE__ */ new Set();
8910
+ for (const { adapter, id } of removedStores) {
8911
+ const asyncStorage = adapter === "local-sync" ? null : getRemovableStoresAsyncStorage(adapter);
8912
+ if (adapter !== "local-sync" && asyncStorage === null) {
8913
+ unsupportedStoreNames.add(id);
8914
+ continue;
8915
+ }
8916
+ const storageId = asyncStorage?.storageId ?? LOCAL_SYNC_STORAGE_ID;
8917
+ let cleanup = cleanups.get(storageId);
8918
+ if (cleanup === void 0) {
8919
+ cleanup = {
8920
+ storageId,
8921
+ storeNames: /* @__PURE__ */ new Set(),
8922
+ run: asyncStorage?.removeStores ?? ((storeNames) => localPersistentStorage.runLocked(() => ({
8923
+ unsentRecordsByStore: removeStoresFromLocalStorage(storeNames),
8924
+ failure: null
8925
+ })))
8926
+ };
8927
+ cleanups.set(storageId, cleanup);
8928
+ }
8929
+ cleanup.storeNames.add(id);
8930
+ }
8931
+ 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.`));
8932
+ const nextMarker = /* @__PURE__ */ new Map();
8933
+ const pendingCleanups = [];
8934
+ for (const cleanup of cleanups.values()) {
8935
+ const cleanedStoreNames = new Set(cleanedMarker.get(cleanup.storageId));
8936
+ const done = [];
8937
+ const pending = /* @__PURE__ */ new Set();
8938
+ for (const storeName of cleanup.storeNames) if (cleanedStoreNames.has(storeName)) done.push(storeName);
8939
+ else pending.add(storeName);
8940
+ if (done.length > 0) nextMarker.set(cleanup.storageId, done);
8941
+ if (pending.size > 0) pendingCleanups.push({
8942
+ cleanup,
8943
+ storeNames: pending
8944
+ });
8945
+ }
8946
+ let markerChanged = countMarkerEntries(nextMarker) !== countMarkerEntries(cleanedMarker);
8947
+ for (const { cleanup, storeNames } of pendingCleanups) {
8948
+ let result;
8949
+ try {
8950
+ result = await cleanup.run(storeNames);
8951
+ } catch (error) {
8952
+ reportError(error);
8953
+ continue;
8954
+ }
8955
+ for (const [storeName, unsentRecords] of result.unsentRecordsByStore) {
8956
+ if (unsentRecords === 0) continue;
8957
+ 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.`));
8958
+ }
8959
+ if (result.failure !== null) {
8960
+ reportError(result.failure);
8961
+ continue;
8962
+ }
8963
+ nextMarker.set(cleanup.storageId, [...nextMarker.get(cleanup.storageId) ?? [], ...storeNames]);
8964
+ markerChanged = true;
8965
+ }
8966
+ if (markerChanged) writeRemovedStoresCleanupMarker(Object.fromEntries(nextMarker));
8967
+ }
8968
+ function countMarkerEntries(marker) {
8969
+ let count = 0;
8970
+ for (const storeNames of marker.values()) count += storeNames.length;
8971
+ return count;
8972
+ }
8973
+ function formatStoreNames(storeNames) {
8974
+ return [...storeNames].map((storeName) => `"${storeName}"`).join(", ");
8975
+ }
8976
+ /**
8977
+ * Removes the persisted data of stores deleted from the app, once per store and
8978
+ * adapter, during idle time after startup. Every later startup only reads the
8979
+ * small marker listing the pairs already handled.
8980
+ */
8981
+ function scheduleRemovedStoresCleanup(removedStores, onPersistentStorageError) {
8982
+ if (removedStores.length === 0) return;
8983
+ const reportError = onPersistentStorageError ?? handleManagedLocalStorageBackgroundError;
8984
+ scheduleInitialMaintenanceCleanup(() => {
8985
+ runRemovedStoresCleanup(removedStores, reportError).catch(reportError);
8986
+ });
8987
+ }
8988
+ //#endregion
8316
8989
  //#region src/storeManager.ts
8317
8990
  const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 2400 * 1e3;
8318
8991
  const DEFAULT_BASE_COALESCING_WINDOW_MS = 16;
@@ -8350,6 +9023,7 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
8350
9023
  getOfflineStatus,
8351
9024
  getOfflineEntities: () => EMPTY_OFFLINE_ENTITIES,
8352
9025
  getOfflineResolutions: () => EMPTY_OFFLINE_RESOLUTIONS,
9026
+ resolveOfflineResolution: (resolutionId) => Promise.resolve(Result.err(new OfflineResolutionActionError("offline-not-configured", resolutionId))),
8353
9027
  getOfflineUploads: () => emptyUploads,
8354
9028
  resolveOfflineUpload: () => Promise.resolve(Result.err(/* @__PURE__ */ new Error("[tsdf] Offline uploads are not configured for this manager"))),
8355
9029
  resolveOfflineUploads: () => Promise.resolve(Result.err(/* @__PURE__ */ new Error("[tsdf] Offline uploads are not configured for this manager"))),
@@ -8367,6 +9041,16 @@ function createStoreManager(options) {
8367
9041
  const appVersion = options.getAppVersion?.();
8368
9042
  const debugLogger = import.meta.env.DEV ? resolveTSDFLogger(options.debugLogger) : void 0;
8369
9043
  const logger = resolveTSDFLogger(options.logger ?? true);
9044
+ const removedStores = options.removedStores ?? [];
9045
+ if (import.meta.env.DEV) for (const { id } of removedStores) assertValidPersistentStoreName(id);
9046
+ const registry = {
9047
+ appVersion,
9048
+ unsubscribeFromOfflineRecovery: void 0,
9049
+ removedStoreIds: new Set(removedStores.map(({ id }) => id)),
9050
+ browserTabsPresence: void 0,
9051
+ nextStoreRegistrationId: 0,
9052
+ stores: /* @__PURE__ */ new Map()
9053
+ };
8370
9054
  let resolvedOfflineSession;
8371
9055
  if (options.offlineSession) {
8372
9056
  const createOfflineSessionOptions = {
@@ -8389,6 +9073,22 @@ function createStoreManager(options) {
8389
9073
  getOfflineStatus: () => resolvedOfflineSession.getOfflineStatus(),
8390
9074
  getOfflineEntities: () => resolvedOfflineSession.getOfflineEntities(),
8391
9075
  getOfflineResolutions: () => resolvedOfflineSession.getOfflineResolutions(),
9076
+ resolveOfflineResolution: async (resolutionId, action) => {
9077
+ const storeName = resolvedOfflineSession.getOfflineResolutions().find((resolution) => resolution.id === resolutionId)?.storeName;
9078
+ if (storeName === void 0) return Result.err(new OfflineResolutionActionError("resolution-not-found", resolutionId));
9079
+ let resolveInStore;
9080
+ for (const registeredStore of registry.stores.values()) if (registeredStore.id === storeName) {
9081
+ resolveInStore = registeredStore.resolveOfflineResolution;
9082
+ break;
9083
+ }
9084
+ if (!resolveInStore) return Result.err(new OfflineResolutionActionError("store-not-registered", resolutionId, storeName));
9085
+ try {
9086
+ const failure = await resolveInStore(resolutionId, action);
9087
+ return failure ? Result.err(new OfflineResolutionActionError(failure, resolutionId, storeName)) : Result.ok(void 0);
9088
+ } catch (error) {
9089
+ return Result.err(new OfflineResolutionActionError("action-failed", resolutionId, storeName, normalizeStoreManagerOfflineError(error)));
9090
+ }
9091
+ },
8392
9092
  getOfflineUploads: () => resolvedOfflineSession.getOfflineUploads(),
8393
9093
  resolveOfflineUpload: (id) => resultify(() => resolvedOfflineSession.resolveOfflineUpload(id), normalizeStoreManagerOfflineError),
8394
9094
  resolveOfflineUploads: (ids) => resultify(() => resolvedOfflineSession.resolveOfflineUploads(ids), normalizeStoreManagerOfflineError),
@@ -8401,12 +9101,6 @@ function createStoreManager(options) {
8401
9101
  useOfflineResolutions: () => resolvedOfflineSession.useOfflineResolutions(),
8402
9102
  useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
8403
9103
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
8404
- const registry = {
8405
- appVersion,
8406
- browserTabsPresence: void 0,
8407
- nextStoreRegistrationId: 0,
8408
- stores: /* @__PURE__ */ new Map()
8409
- };
8410
9104
  const storeManager = {
8411
9105
  getSessionKey: options.getSessionKey,
8412
9106
  errorNormalizer: options.errorNormalizer,
@@ -8429,6 +9123,7 @@ function createStoreManager(options) {
8429
9123
  }
8430
9124
  },
8431
9125
  onTransportReconnect: () => {
9126
+ if (recheckIsSessionInOfflineMode(storeManager.getSessionKey())) return;
8432
9127
  for (const registeredStore of [...registry.stores.values()]) registeredStore.onTransportReconnect();
8433
9128
  },
8434
9129
  ...offlineApi
@@ -8437,6 +9132,7 @@ function createStoreManager(options) {
8437
9132
  storeManager.logger = logger;
8438
9133
  storeManagerRegistry.set(storeManager, registry);
8439
9134
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
9135
+ scheduleRemovedStoresCleanup(removedStores, options.onPersistentStorageError);
8440
9136
  return storeManager;
8441
9137
  }
8442
9138
  function getRegistryOrThrow(storeManager) {
@@ -8446,6 +9142,7 @@ function getRegistryOrThrow(storeManager) {
8446
9142
  }
8447
9143
  function registerStoreWithManager(storeManager, store) {
8448
9144
  const registry = getRegistryOrThrow(storeManager);
9145
+ 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
9146
  let hasDuplicateId = false;
8450
9147
  for (const registeredStore of registry.stores.values()) if (registeredStore.id === store.id) {
8451
9148
  hasDuplicateId = true;
@@ -8455,9 +9152,15 @@ function registerStoreWithManager(storeManager, store) {
8455
9152
  const registrationId = registry.nextStoreRegistrationId;
8456
9153
  registry.nextStoreRegistrationId += 1;
8457
9154
  registry.stores.set(registrationId, store);
9155
+ if (!registry.unsubscribeFromOfflineRecovery) registry.unsubscribeFromOfflineRecovery = subscribeToOfflineRecovery((sessionKey, hasStoreRecovered) => {
9156
+ if (storeManager.getSessionKey() !== sessionKey) return;
9157
+ for (const registeredStore of [...registry.stores.values()]) if (hasStoreRecovered(registeredStore.id)) registeredStore.onOfflineRecovery();
9158
+ });
8458
9159
  return () => {
8459
9160
  registry.stores.delete(registrationId);
8460
9161
  if (registry.stores.size === 0) {
9162
+ registry.unsubscribeFromOfflineRecovery?.();
9163
+ registry.unsubscribeFromOfflineRecovery = void 0;
8461
9164
  registry.browserTabsPresence?.close();
8462
9165
  registry.browserTabsPresence = void 0;
8463
9166
  }
@@ -8630,7 +9333,7 @@ async function performMutationWithLifecycle(startMutation, mutation, onError, op
8630
9333
  //#endregion
8631
9334
  //#region src/utils/storeFocusLifecycle.ts
8632
9335
  /** @internal */
8633
- function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate, onWindowFocusReevaluateDelayedRTU, debug) {
9336
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onReconnectRevalidate, onWindowFocusReevaluateDelayedRTU, getIsOfflineMode, debug) {
8634
9337
  let cleanupFocusListener = null;
8635
9338
  let cleanupReconnectFocusListener = null;
8636
9339
  let reconnectCooldownTimeoutId = null;
@@ -8664,8 +9367,9 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
8664
9367
  });
8665
9368
  } : void 0;
8666
9369
  function runTransportReconnectRevalidate() {
9370
+ if (getIsOfflineMode()) return;
8667
9371
  lastTransportReconnectRevalidateAt = Date.now();
8668
- onTransportReconnectRevalidate();
9372
+ onReconnectRevalidate();
8669
9373
  }
8670
9374
  function ensureReconnectFocusListener() {
8671
9375
  if (cleanupReconnectFocusListener) return;
@@ -8719,6 +9423,13 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
8719
9423
  });
8720
9424
  return;
8721
9425
  }
9426
+ if (getIsOfflineMode()) {
9427
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
9428
+ reason: "offline-mode",
9429
+ status: "skipped"
9430
+ });
9431
+ return;
9432
+ }
8722
9433
  logWindowFocusRevalidate?.("window focus revalidation triggered", {
8723
9434
  policy: typeof revalidateOnWindowFocus === "function" ? "dynamic" : "enabled",
8724
9435
  status: "triggered"
@@ -8747,9 +9458,23 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
8747
9458
  }
8748
9459
  scheduleTrailingTransportReconnectRevalidate();
8749
9460
  }
9461
+ function onOfflineRecovery() {
9462
+ if (!usesRealTimeUpdates || transportReconnectCooldownMs <= 0) {
9463
+ flushTransportReconnectRevalidate();
9464
+ return;
9465
+ }
9466
+ if (hasPendingReconnectRevalidateOnFocus) return;
9467
+ scheduleTrailingTransportReconnectRevalidate();
9468
+ }
9469
+ function flushPendingReconnectRevalidate() {
9470
+ if (reconnectCooldownTimeoutId === null) return;
9471
+ flushTransportReconnectRevalidate();
9472
+ }
8750
9473
  reset();
8751
9474
  return {
8752
9475
  onTransportReconnect,
9476
+ onOfflineRecovery,
9477
+ flushPendingReconnectRevalidate,
8753
9478
  reset,
8754
9479
  dispose
8755
9480
  };
@@ -9445,6 +10170,7 @@ function createCollectionStore(storeOptions) {
9445
10170
  });
9446
10171
  offlineOverlayStore.initializeStore();
9447
10172
  let offlineOverlaySessionKey = null;
10173
+ const unsentCreationItemKeys = /* @__PURE__ */ new Set();
9448
10174
  const itemCacheRuntime = createLruCacheRuntime();
9449
10175
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
9450
10176
  const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
@@ -9482,6 +10208,7 @@ function createCollectionStore(storeOptions) {
9482
10208
  function clearOfflineOverlays(nextSessionKey = null) {
9483
10209
  offlineOverlaySessionKey = nextSessionKey;
9484
10210
  offlineOverlayStore.setState({});
10211
+ unsentCreationItemKeys.clear();
9485
10212
  }
9486
10213
  function rebindOfflineOverlays(itemKeyRewrites) {
9487
10214
  rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
@@ -9536,6 +10263,12 @@ function createCollectionStore(storeOptions) {
9536
10263
  finalPayload
9537
10264
  });
9538
10265
  },
10266
+ applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
10267
+ storeEvents.emit("tempEntityReconciled", {
10268
+ tempId: __LEGIT_CAST__(tempId),
10269
+ finalPayload: __LEGIT_CAST__(finalPayload)
10270
+ });
10271
+ },
9539
10272
  captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
9540
10273
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
9541
10274
  captureOfflineOverlays(entityRefs.flatMap((ref) => {
@@ -9546,8 +10279,18 @@ function createCollectionStore(storeOptions) {
9546
10279
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
9547
10280
  rebindOfflineOverlays(itemKeyRewrites);
9548
10281
  },
10282
+ revalidateDiscardedEntities: (entities) => {
10283
+ focusLifecycle.flushPendingReconnectRevalidate();
10284
+ for (const { entityKey, payload } of entities) {
10285
+ const item = store.state[entityKey];
10286
+ if (item) invalidateItem(item.payload, "highPriority");
10287
+ else if (item === null && payload !== void 0) scheduleFetch("highPriority", __LEGIT_CAST__(payload));
10288
+ }
10289
+ },
9549
10290
  syncEntityOverlays: ({ entities, sessionKey }) => {
9550
10291
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
10292
+ unsentCreationItemKeys.clear();
10293
+ for (const entity of entities) if (entity.tempId !== void 0) unsentCreationItemKeys.add(entity.entityKey);
9551
10294
  const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
9552
10295
  offlineOverlayStore.produceState((draft) => {
9553
10296
  for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
@@ -9958,6 +10701,7 @@ function createCollectionStore(storeOptions) {
9958
10701
  for (const { itemKey } of itemsKey) {
9959
10702
  const item = store.state[itemKey];
9960
10703
  if (!item) continue;
10704
+ if (unsentCreationItemKeys.has(itemKey)) continue;
9961
10705
  if ((item.refetchOnMount ? fetchTypePriority[item.refetchOnMount] : -1) >= fetchTypePriority[priority]) continue;
9962
10706
  store.produceState((draft) => {
9963
10707
  const draftItem = draft[itemKey];
@@ -10212,14 +10956,17 @@ function createCollectionStore(storeOptions) {
10212
10956
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
10213
10957
  return result;
10214
10958
  }
10959
+ function getIsOfflineMode() {
10960
+ return recheckIsSessionInOfflineMode(storeManager.getSessionKey());
10961
+ }
10215
10962
  const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
10216
10963
  invalidateItem(() => true, "lowPriority");
10217
10964
  }, () => {
10218
- invalidateItem(() => true, "realtimeUpdate");
10965
+ invalidateItem(() => true, usesRealTimeUpdates ? "realtimeUpdate" : "highPriority");
10219
10966
  }, () => {
10220
10967
  for (const scheduler of batchKeySchedulers.values()) scheduler.reevaluateDelayedRTU();
10221
10968
  for (const scheduler of perItemSchedulers.values()) scheduler.reevaluateDelayedRTU();
10222
- }, import.meta.env.DEV ? {
10969
+ }, getIsOfflineMode, import.meta.env.DEV ? {
10223
10970
  debugLogger: storeManager.debugLogger,
10224
10971
  storeId: id,
10225
10972
  storeType: "collection"
@@ -10350,7 +11097,9 @@ function createCollectionStore(storeOptions) {
10350
11097
  const unregisterStoreFromManager = registerStoreWithManager(storeManager, {
10351
11098
  id,
10352
11099
  reset,
10353
- onTransportReconnect
11100
+ onTransportReconnect,
11101
+ onOfflineRecovery: focusLifecycle.onOfflineRecovery,
11102
+ resolveOfflineResolution: offlineController?.resolveOfflineResolutionWithGenericAction
10354
11103
  });
10355
11104
  return {
10356
11105
  store,
@@ -10653,6 +11402,10 @@ function createDocumentStore(storeOptions) {
10653
11402
  entityKey: DOC_TARGET_KEY,
10654
11403
  entityKind: "document"
10655
11404
  }],
11405
+ revalidateDiscardedEntities: () => {
11406
+ focusLifecycle.flushPendingReconnectRevalidate();
11407
+ invalidateData("highPriority");
11408
+ },
10656
11409
  getProtectedCacheKeys: () => {
10657
11410
  const sessionKey = getSessionKeyForRuntime();
10658
11411
  if (sessionKey === false) return [];
@@ -10855,13 +11608,16 @@ function createDocumentStore(storeOptions) {
10855
11608
  usesRealTimeUpdates
10856
11609
  });
10857
11610
  if (initialStatus !== "idle" || initialData !== null || initialError !== null) scheduler.setLastFetchStartTimeForRequest(DOC_REQUEST_ID, testOptions?.initialLastFetchStartTime ?? 0);
11611
+ function getIsOfflineMode() {
11612
+ return recheckIsSessionInOfflineMode(storeManager.getSessionKey());
11613
+ }
10858
11614
  const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
10859
11615
  invalidateData("lowPriority");
10860
11616
  }, () => {
10861
- invalidateData("realtimeUpdate");
11617
+ invalidateData(usesRealTimeUpdates ? "realtimeUpdate" : "highPriority");
10862
11618
  }, () => {
10863
11619
  scheduler.reevaluateDelayedRTU();
10864
- }, import.meta.env.DEV ? {
11620
+ }, getIsOfflineMode, import.meta.env.DEV ? {
10865
11621
  debugLogger: storeManager.debugLogger,
10866
11622
  storeId: id,
10867
11623
  storeType: "document"
@@ -11195,7 +11951,9 @@ function createDocumentStore(storeOptions) {
11195
11951
  const unregisterStoreFromManager = registerStoreWithManager(storeManager, {
11196
11952
  id,
11197
11953
  reset,
11198
- onTransportReconnect
11954
+ onTransportReconnect,
11955
+ onOfflineRecovery: focusLifecycle.onOfflineRecovery,
11956
+ resolveOfflineResolution: offlineController?.resolveOfflineResolutionWithGenericAction
11199
11957
  });
11200
11958
  return {
11201
11959
  store,
@@ -14415,7 +15173,7 @@ const GET_ALL = () => true;
14415
15173
  //#endregion
14416
15174
  //#region src/listQueryStore/createMutationApi.ts
14417
15175
  /** @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) {
15176
+ 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
15177
  const storeEvents = evtmitter();
14420
15178
  const deferredOptimisticQueryInvalidationsStack = [];
14421
15179
  const optimisticMutationQueryContextStack = [];
@@ -14640,6 +15398,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14640
15398
  const itemsKey = getItemsKeyArray(itemPayload);
14641
15399
  const staleInvalidateFieldsByItemKey = /* @__PURE__ */ new Map();
14642
15400
  for (const { itemKey } of itemsKey) {
15401
+ if (unsentCreationItemKeys.has(itemKey)) continue;
14643
15402
  const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
14644
15403
  const staleInvalidateFields = effectiveLoadedFields === "*" ? invalidateFields : invalidateFields.filter((field) => effectiveLoadedFields?.includes(field) ?? false);
14645
15404
  if (staleInvalidateFields.length < invalidateFields.length) {
@@ -14701,6 +15460,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14701
15460
  for (const { itemKey, payload } of itemsKey) {
14702
15461
  const item = store.state.itemQueries[itemKey];
14703
15462
  if (!item) continue;
15463
+ if (unsentCreationItemKeys.has(itemKey)) continue;
14704
15464
  const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
14705
15465
  const itemWasFullyLoaded = partialResources && effectiveLoadedFields === "*";
14706
15466
  const existingPendingFields = itemPendingInvalidationFields.get(itemKey);
@@ -16252,7 +17012,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16252
17012
  return storeState.map((result, index) => {
16253
17013
  const queryConfig = queriesWithId[index];
16254
17014
  if (result.status !== "loading" && result.status !== "idle") return result;
16255
- if (queryConfig && readFallbackQueryState && !(derivedQueries && (isOfflineMode || stickyDerivedQueryKeys.has(queryConfig.key)))) {
17015
+ if (queryConfig && readFallbackQueryState && !store.state.queries[queryConfig.key]?.wasLoaded && !(derivedQueries && (isOfflineMode || stickyDerivedQueryKeys.has(queryConfig.key)))) {
16256
17016
  const fallbackQuery = readFallbackQueryState(queryConfig.key);
16257
17017
  if (fallbackQuery && readFallbackItemState) {
16258
17018
  const visibleItemKeys = getVisibleQueryItemKeys(result.queryKey, fallbackQuery.items);
@@ -16304,7 +17064,8 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16304
17064
  isOfflineMode,
16305
17065
  offlineEntitiesByKey,
16306
17066
  selectVisibleItems,
16307
- stickyDerivedQueryKeys
17067
+ stickyDerivedQueryKeys,
17068
+ store
16308
17069
  ]);
16309
17070
  const autoFetchSignals = store.useSelector(useCallback((state) => {
16310
17071
  if (!partialResources) return [];
@@ -16703,6 +17464,7 @@ function createListQueryStore(storeOptions) {
16703
17464
  });
16704
17465
  offlineOverlayStore.initializeStore();
16705
17466
  let offlineOverlaySessionKey = null;
17467
+ const unsentCreationItemKeys = /* @__PURE__ */ new Set();
16706
17468
  const itemCacheRuntime = createLruCacheRuntime();
16707
17469
  const queryCacheRuntime = createLruCacheRuntime();
16708
17470
  const offsetPagination = storeOptions.offsetPagination;
@@ -17053,7 +17815,7 @@ function createListQueryStore(storeOptions) {
17053
17815
  events.emit("invalidateItem", event);
17054
17816
  }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations, itemMutationCountsWithoutScheduler, () => {
17055
17817
  revalidateAfterIgnoredConfirmedSnapshots();
17056
- });
17818
+ }, unsentCreationItemKeys);
17057
17819
  if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
17058
17820
  normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
17059
17821
  const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
@@ -17076,34 +17838,10 @@ function createListQueryStore(storeOptions) {
17076
17838
  deleteItemState(__LEGIT_CAST__(tempId));
17077
17839
  },
17078
17840
  reconcileTempEntity: ({ tempId, reconciliation }) => {
17079
- const tempPayload = __LEGIT_CAST__(tempId);
17080
- const tempItemKey = getItemKey(tempPayload);
17081
- const currentItem = getItemState(tempPayload);
17082
- const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
17083
- if (finalData === void 0) return;
17084
- const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
17085
- const finalItemKey = getItemKey(finalPayload);
17086
- const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
17087
- queryKey,
17088
- index: query.items.indexOf(tempItemKey)
17089
- })).filter(({ index }) => index !== -1);
17090
- deleteItemState(tempPayload);
17091
- addItemToState(finalPayload, finalData);
17092
- storeEvents.emit("tempEntityReconciled", {
17093
- tempId: tempPayload,
17094
- finalPayload
17095
- });
17096
- if (queryMemberships.length === 0) return;
17097
- store.produceState((draft) => {
17098
- for (const { queryKey, index } of queryMemberships) {
17099
- const query = notNullish(draft.queries[queryKey]);
17100
- const existingIndex = query.items.indexOf(finalItemKey);
17101
- if (existingIndex !== -1) query.items.splice(existingIndex, 1);
17102
- query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
17103
- }
17104
- }, { action: "offline-reconcile-temp-item" });
17105
- touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
17106
- for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
17841
+ reconcileOfflineTempItem(tempId, reconciliation.finalPayload, reconciliation.finalData);
17842
+ },
17843
+ applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
17844
+ if (!runWithoutBroadcast(() => reconcileOfflineTempItem(tempId, finalPayload, void 0))) emitTempItemReconciled(tempId, finalPayload);
17107
17845
  },
17108
17846
  captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
17109
17847
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
@@ -17115,8 +17853,23 @@ function createListQueryStore(storeOptions) {
17115
17853
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
17116
17854
  rebindOfflineOverlays(itemKeyRewrites);
17117
17855
  },
17856
+ revalidateDiscardedEntities: (entities, hasPendingResolutions) => {
17857
+ focusLifecycle.flushPendingReconnectRevalidate();
17858
+ invalidateQueryAndItems({
17859
+ itemPayload: filterAndMap(entities, (ref) => store.state.itemQueries[ref.entityKey]?.payload ?? false),
17860
+ queryPayload: hasPendingResolutions ? false : () => true,
17861
+ type: "highPriority"
17862
+ });
17863
+ if (!fetchItemFn) return;
17864
+ for (const { entityKey, payload } of entities) {
17865
+ if (store.state.itemQueries[entityKey] !== null || payload === void 0) continue;
17866
+ scheduleItemFetch("highPriority", __LEGIT_CAST__(payload), { fields: "*" });
17867
+ }
17868
+ },
17118
17869
  syncEntityOverlays: ({ entities, sessionKey }) => {
17119
17870
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
17871
+ unsentCreationItemKeys.clear();
17872
+ for (const entity of entities) if (entity.entityKind === "item" && entity.tempId !== void 0) unsentCreationItemKeys.add(entity.entityKey);
17120
17873
  const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
17121
17874
  offlineOverlayStore.produceState((draft) => {
17122
17875
  for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
@@ -17185,6 +17938,44 @@ function createListQueryStore(storeOptions) {
17185
17938
  }
17186
17939
  for (const itemKey of itemsPendingFullInvalidation.keys()) if (store.state.itemLoadedFields[itemKey] === "*") itemsPendingFullInvalidation.delete(itemKey);
17187
17940
  }
17941
+ function emitTempItemReconciled(tempId, finalPayload) {
17942
+ storeEvents.emit("tempEntityReconciled", {
17943
+ tempId: __LEGIT_CAST__(tempId),
17944
+ finalPayload: __LEGIT_CAST__(finalPayload)
17945
+ });
17946
+ }
17947
+ /**
17948
+ * Replaces an offline temp item with its final one, in place in every query
17949
+ * that lists it. Returns `false` when there is no data for the final item.
17950
+ */
17951
+ function reconcileOfflineTempItem(tempId, finalPayloadValue, finalDataValue) {
17952
+ const tempPayload = __LEGIT_CAST__(tempId);
17953
+ const tempItemKey = getItemKey(tempPayload);
17954
+ const currentItem = getItemState(tempPayload);
17955
+ const finalData = finalDataValue !== void 0 ? __LEGIT_CAST__(finalDataValue) : currentItem ?? void 0;
17956
+ if (finalData === void 0) return false;
17957
+ const finalPayload = __LEGIT_CAST__(finalPayloadValue);
17958
+ const finalItemKey = getItemKey(finalPayload);
17959
+ const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
17960
+ queryKey,
17961
+ index: query.items.indexOf(tempItemKey)
17962
+ })).filter(({ index }) => index !== -1);
17963
+ deleteItemState(tempPayload);
17964
+ addItemToState(finalPayload, finalData);
17965
+ emitTempItemReconciled(tempId, finalPayloadValue);
17966
+ if (queryMemberships.length === 0) return true;
17967
+ store.produceState((draft) => {
17968
+ for (const { queryKey, index } of queryMemberships) {
17969
+ const query = notNullish(draft.queries[queryKey]);
17970
+ const existingIndex = query.items.indexOf(finalItemKey);
17971
+ if (existingIndex !== -1) query.items.splice(existingIndex, 1);
17972
+ query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
17973
+ }
17974
+ }, { action: "offline-reconcile-temp-item" });
17975
+ touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
17976
+ for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
17977
+ return true;
17978
+ }
17188
17979
  function cleanupItemStateMetadata(itemKey) {
17189
17980
  itemPendingInvalidationFields.delete(itemKey);
17190
17981
  itemsPendingFullInvalidation.delete(itemKey);
@@ -17199,6 +17990,7 @@ function createListQueryStore(storeOptions) {
17199
17990
  function clearOfflineOverlays(nextSessionKey = null) {
17200
17991
  offlineOverlaySessionKey = nextSessionKey;
17201
17992
  offlineOverlayStore.setState({});
17993
+ unsentCreationItemKeys.clear();
17202
17994
  }
17203
17995
  function rebindOfflineOverlays(itemKeyRewrites) {
17204
17996
  rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
@@ -17476,6 +18268,9 @@ function createListQueryStore(storeOptions) {
17476
18268
  function useFindItem$1(findItemFn, options = {}) {
17477
18269
  return useFindItem(findItemFn, options, store, registerActiveStandaloneItems, touchItems);
17478
18270
  }
18271
+ function getIsOfflineMode() {
18272
+ return recheckIsSessionInOfflineMode(storeManager.getSessionKey());
18273
+ }
17479
18274
  const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
17480
18275
  invalidateQueryAndItems({
17481
18276
  all: true,
@@ -17484,9 +18279,9 @@ function createListQueryStore(storeOptions) {
17484
18279
  }, () => {
17485
18280
  invalidateQueryAndItems({
17486
18281
  all: true,
17487
- type: "realtimeUpdate"
18282
+ type: usesRealTimeUpdates ? "realtimeUpdate" : "highPriority"
17488
18283
  });
17489
- }, reevaluateDelayedRTUs, import.meta.env.DEV ? {
18284
+ }, reevaluateDelayedRTUs, getIsOfflineMode, import.meta.env.DEV ? {
17490
18285
  debugLogger: storeManager.debugLogger,
17491
18286
  storeId: id,
17492
18287
  storeType: "listQuery"
@@ -17661,7 +18456,9 @@ function createListQueryStore(storeOptions) {
17661
18456
  const unregisterStoreFromManager = registerStoreWithManager(storeManager, {
17662
18457
  id,
17663
18458
  reset,
17664
- onTransportReconnect
18459
+ onTransportReconnect,
18460
+ onOfflineRecovery: focusLifecycle.onOfflineRecovery,
18461
+ resolveOfflineResolution: offlineController?.resolveOfflineResolutionWithGenericAction
17665
18462
  });
17666
18463
  return {
17667
18464
  store,
@@ -17768,7 +18565,9 @@ const storedUploadMetadataRecordSchema = rc_object({
17768
18565
  p: uploadProgressSchema.optionalKey(),
17769
18566
  e: lastErrorSchema.optionalKey(),
17770
18567
  g: rc_number.optionalKey(),
17771
- l: rc_number
18568
+ l: rc_number,
18569
+ d: validPayloadSchema.optionalKey(),
18570
+ s: rc_string.optionalKey()
17772
18571
  });
17773
18572
  function serializeStoredUploadMetadataRecord(record) {
17774
18573
  return JSON.stringify({
@@ -17785,7 +18584,9 @@ function serializeStoredUploadMetadataRecord(record) {
17785
18584
  ...record.progress !== void 0 ? { p: record.progress } : {},
17786
18585
  ...record.lastError !== void 0 ? { e: record.lastError } : {},
17787
18586
  ...record.lastOnlineSessionStartedAt !== void 0 ? { g: record.lastOnlineSessionStartedAt } : {},
17788
- l: record.lastModified
18587
+ l: record.lastModified,
18588
+ ...record.metadata !== void 0 ? { d: record.metadata } : {},
18589
+ ...record.storeName !== void 0 ? { s: record.storeName } : {}
17789
18590
  });
17790
18591
  }
17791
18592
  function parseStoredUploadMetadataRecord(raw) {
@@ -17805,7 +18606,9 @@ function parseStoredUploadMetadataRecord(raw) {
17805
18606
  ...compactRecord.p !== void 0 ? { progress: compactRecord.p } : {},
17806
18607
  ...compactRecord.e !== void 0 ? { lastError: compactRecord.e } : {},
17807
18608
  ...compactRecord.g !== void 0 ? { lastOnlineSessionStartedAt: compactRecord.g } : {},
17808
- lastModified: compactRecord.l
18609
+ lastModified: compactRecord.l,
18610
+ ...compactRecord.d !== void 0 ? { metadata: compactRecord.d } : {},
18611
+ ...compactRecord.s !== void 0 ? { storeName: compactRecord.s } : {}
17809
18612
  };
17810
18613
  }
17811
18614
  var OpfsOfflineUploadDriver = class {