tsdf 17.0.0-alpha.10 → 17.0.0-alpha.11

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 getNavigatorLockManager, C as isModeEffectivelyActive, D as clearSessionProtectedKeysSnapshot, E as offlineResolutionRecordSchema, H as serializeProtectedRef, L as getPayloadRecordKey, M as createCompactLocalStorageEntry, N as parseCompactLocalStorageEntry, O as getSessionProtectedKeysSnapshot, S as getIsOfflineModeFromStatus, T as offlineItemEntityRefSchema, U as scheduleIdleCleanup, V as parsePersistedAsyncNamespaceKind, _ as keepEntriesWithinByteBudget, a as estimateManagedAsyncStorageEntrySizeBytes, b as compactOfflineStatusSnapshotSchema, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as getSerializedStringSize, h as createTimedKeySet, j as warnIfNavigatorLockUnavailable, k as setSessionProtectedKeysSnapshot, l as registerAsyncStartupStoreCleanup, m as createShouldIgnoreItemPredicate, o as getProtectedKeysFromMetadata, p as getDefaultMaxBytesForScope, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as serializeJsonForStorage, w as isOfflineModeStatusValue, x as defaultOfflineRuntimeConfig, y as OfflineResolutionConflictParseError } from "./asyncStorageAdapter-BZSj1ZO5.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-BO_uDxe4.js";
1
+ import { A as getNavigatorLockManager, C as isModeEffectivelyActive, D as clearSessionProtectedKeysSnapshot, E as offlineResolutionRecordSchema, H as serializeProtectedRef, L as getPayloadRecordKey, M as createCompactLocalStorageEntry, N as parseCompactLocalStorageEntry, O as getSessionProtectedKeysSnapshot, S as getIsOfflineModeFromStatus, T as offlineItemEntityRefSchema, U as scheduleIdleCleanup, V as parsePersistedAsyncNamespaceKind, _ as keepEntriesWithinByteBudget, a as estimateManagedAsyncStorageEntrySizeBytes, b as compactOfflineStatusSnapshotSchema, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as getSerializedStringSize, h as createTimedKeySet, j as warnIfNavigatorLockUnavailable, k as setSessionProtectedKeysSnapshot, l as registerAsyncStartupStoreCleanup, m as createShouldIgnoreItemPredicate, o as getProtectedKeysFromMetadata, p as getDefaultMaxBytesForScope, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as serializeJsonForStorage, w as isOfflineModeStatusValue, x as defaultOfflineRuntimeConfig, y as OfflineResolutionConflictParseError } from "./asyncStorageAdapter-CSzvgl3s.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-3c1zSDZi.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 { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
@@ -66,7 +66,7 @@ function createLruCacheRuntime() {
66
66
  /** @internal */
67
67
  const CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS = 3600 * 1e3;
68
68
  /** @internal */
69
- function createIdleThrottledScheduler({ throttleMs, run }) {
69
+ function createIdleThrottledScheduler(throttleMs, run) {
70
70
  let pendingTimer = null;
71
71
  let cancelIdleRun = null;
72
72
  let isScheduled = false;
@@ -1312,18 +1312,18 @@ function ensureAsyncNamespaceKind(entryPrefix) {
1312
1312
  * forced manifest keys are coalesced and a global sweep request wins over
1313
1313
  * targeted maintenance because it already covers the full cleanup pass.
1314
1314
  */
1315
- function scheduleLocalStorageMaintenance(options = {}) {
1316
- if (options.forceManifestKeys === void 0) {
1315
+ function scheduleLocalStorageMaintenance(forceManifestKeys) {
1316
+ if (forceManifestKeys === void 0) {
1317
1317
  localStorageGlobalMaintenanceRequested = true;
1318
1318
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1319
- } else if (!localStorageGlobalMaintenanceRequested) for (const manifestKey of options.forceManifestKeys) scheduledLocalStorageMaintenanceManifestKeys.add(manifestKey);
1319
+ } else if (!localStorageGlobalMaintenanceRequested) for (const manifestKey of forceManifestKeys) scheduledLocalStorageMaintenanceManifestKeys.add(manifestKey);
1320
1320
  if (cancelScheduledLocalStorageMaintenance !== null) return;
1321
1321
  cancelScheduledLocalStorageMaintenance = scheduleIdleCleanup(() => {
1322
1322
  cancelScheduledLocalStorageMaintenance = null;
1323
- const forceManifestKeys = localStorageGlobalMaintenanceRequested ? void 0 : [...scheduledLocalStorageMaintenanceManifestKeys];
1323
+ const maintenanceManifestKeys = localStorageGlobalMaintenanceRequested ? void 0 : [...scheduledLocalStorageMaintenanceManifestKeys];
1324
1324
  localStorageGlobalMaintenanceRequested = false;
1325
1325
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1326
- localPersistentStorage.runMaintenance(forceManifestKeys);
1326
+ localPersistentStorage.runMaintenance(maintenanceManifestKeys);
1327
1327
  });
1328
1328
  }
1329
1329
  function preserveOfflineProtectionFlag(sessionKey, storageKey, nextMeta, currentMeta) {
@@ -2175,16 +2175,16 @@ function getStorageKeyForStore(sessionKey, storeName) {
2175
2175
  function getStoragePrefixForStoreNamespace(sessionKey, storeName, entryPrefix) {
2176
2176
  return `${getStorageKey(sessionKey, storeName)}.${entryPrefix}.`;
2177
2177
  }
2178
- function createProtectedStorageKey(args) {
2179
- if ((args.backend ?? "localStorage") === "localStorage") {
2180
- if (args.kind === "document" && args.key === "d") return getStorageKeyForStore(args.sessionKey, args.storeName);
2181
- return `${getStoragePrefixForStoreNamespace(args.sessionKey, args.storeName, args.kind)}${args.key}`;
2178
+ function createProtectedStorageKey(sessionKey, storeName, kind, key, backend = "localStorage") {
2179
+ if (backend === "localStorage") {
2180
+ if (kind === "document" && key === "d") return getStorageKeyForStore(sessionKey, storeName);
2181
+ return `${getStoragePrefixForStoreNamespace(sessionKey, storeName, kind)}${key}`;
2182
2182
  }
2183
2183
  return serializeProtectedRef({
2184
- sessionKey: args.sessionKey,
2185
- storeName: args.storeName,
2186
- kind: ensureAsyncNamespaceKind(args.kind),
2187
- key: args.key
2184
+ sessionKey,
2185
+ storeName,
2186
+ kind: ensureAsyncNamespaceKind(kind),
2187
+ key
2188
2188
  });
2189
2189
  }
2190
2190
  function readManifestPayloadMeta(meta) {
@@ -2205,7 +2205,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2205
2205
  }
2206
2206
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2207
2207
  async function clearAllSessionStorage(sessionKey) {
2208
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-DbyKyARM.js");
2208
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-W8bChTBu.js");
2209
2209
  await Promise.all([
2210
2210
  clearSessionStorage(sessionKey, "local-sync"),
2211
2211
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -2295,10 +2295,7 @@ function toCollectionItemState(persisted, dataSchema, shouldIgnoreItem) {
2295
2295
  function setupCollectionPersistence(config, options = {}) {
2296
2296
  assertValidPersistentStoreName(config.storeName);
2297
2297
  const version = config.version;
2298
- const defaultMaxBytes = getDefaultMaxBytesForScope({
2299
- adapter: config.adapter,
2300
- scopeKind: "collection.item"
2301
- });
2298
+ const defaultMaxBytes = getDefaultMaxBytesForScope(config.adapter, "collection.item");
2302
2299
  const maxBytes = config.maxBytes ?? defaultMaxBytes;
2303
2300
  const resolveItemKey = options.getItemKey ?? ((payload) => getCompositeKey(payload));
2304
2301
  const pinnedItemKeys = new Set((config.pinnedItems ?? []).map((payload) => resolveItemKey(payload)));
@@ -2349,18 +2346,8 @@ function setupCollectionPersistence(config, options = {}) {
2349
2346
  const asyncNamespaceScope = getAsyncNamespaceScope();
2350
2347
  if (asyncNamespaceScope === null) return JSON.stringify(args.value).length;
2351
2348
  const serializedValue = serializeJsonForStorage(args.value.data);
2352
- return estimateManagedAsyncStorageEntrySizeBytes({
2353
- customMetadata: mergeManagedAsyncStorageCustomMetadata({
2354
- currentCustomMetadata: args.currentCustomMetadata,
2355
- key: args.itemKey,
2356
- nextCustomMetadata: { p: args.value.payload },
2357
- protectedKeysSnapshotSet: args.protectedKeysSnapshotSet,
2358
- scope: asyncNamespaceScope
2359
- }),
2360
- lastAccessAt: args.lastAccessAt,
2361
- serializedValue: serializedValue.rawValue,
2362
- version: version ?? 1
2363
- });
2349
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, { p: args.value.payload }, args.protectedKeysSnapshotSet, asyncNamespaceScope, args.itemKey);
2350
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
2364
2351
  }
2365
2352
  let storeRef = null;
2366
2353
  let unsubscribe = null;
@@ -2434,15 +2421,7 @@ function setupCollectionPersistence(config, options = {}) {
2434
2421
  protected: protectedItemKeys.has(itemKey),
2435
2422
  sizeBytes: rememberPersistedMetadataSize(itemKey, metadata.sizeBytes)
2436
2423
  }));
2437
- const keptKeys = keepEntriesWithinByteBudget({
2438
- entries: candidateEntries,
2439
- getKey: (entry) => entry.itemKey,
2440
- getLastAccessAt: (entry) => entry.lastAccessAt,
2441
- getSizeBytes: (entry) => entry.sizeBytes,
2442
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2443
- isProtected: (entry) => entry.protected,
2444
- maxBytes: effectiveStaticPolicy.maxBytes
2445
- });
2424
+ const keptKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
2446
2425
  for (const { itemKey } of candidateEntries) {
2447
2426
  if (keptKeys.has(itemKey)) continue;
2448
2427
  deleteKeys.add(getPayloadRecordKey(itemKey));
@@ -2707,15 +2686,7 @@ function setupCollectionPersistence(config, options = {}) {
2707
2686
  await Promise.all(ignoredEntries.map(({ itemKey }) => namespace.remove(itemKey)));
2708
2687
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2709
2688
  }
2710
- const keptKeys = keepEntriesWithinByteBudget({
2711
- entries: filteredEntries,
2712
- getKey: (entry) => entry.itemKey,
2713
- getLastAccessAt: (entry) => entry.lastAccessAt,
2714
- getSizeBytes: (entry) => entry.sizeBytes,
2715
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2716
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
2717
- maxBytes
2718
- });
2689
+ const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2719
2690
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2720
2691
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2721
2692
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2743,15 +2714,7 @@ function setupCollectionPersistence(config, options = {}) {
2743
2714
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2744
2715
  }
2745
2716
  const filteredEntries = validEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
2746
- const keptKeys = keepEntriesWithinByteBudget({
2747
- entries: filteredEntries,
2748
- getKey: (entry) => entry.itemKey,
2749
- getLastAccessAt: (entry) => entry.lastAccessAt,
2750
- getSizeBytes: (entry) => entry.sizeBytes,
2751
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2752
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
2753
- maxBytes
2754
- });
2717
+ const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2755
2718
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2756
2719
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2757
2720
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2874,15 +2837,7 @@ function setupCollectionPersistence(config, options = {}) {
2874
2837
  if (metadataByKey.has(entry.itemKey)) pendingRemoves.add(entry.itemKey);
2875
2838
  }
2876
2839
  const remainingCandidates = candidateEntries.filter(({ itemKey }) => !pendingRemoves.has(itemKey));
2877
- const keptKeys = keepEntriesWithinByteBudget({
2878
- entries: remainingCandidates,
2879
- getKey: (entry) => entry.itemKey,
2880
- getLastAccessAt: (entry) => entry.lastAccessAt,
2881
- getSizeBytes: (entry) => entry.sizeBytes,
2882
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
2883
- isProtected: (entry) => entry.protected,
2884
- maxBytes
2885
- });
2840
+ const keptKeys = keepEntriesWithinByteBudget(remainingCandidates, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, maxBytes);
2886
2841
  if (keptKeys.size !== remainingCandidates.length) {
2887
2842
  for (const { itemKey } of remainingCandidates) {
2888
2843
  if (keptKeys.has(itemKey)) continue;
@@ -2915,7 +2870,7 @@ function setupCollectionPersistence(config, options = {}) {
2915
2870
  } else knownPersistedKeys = null;
2916
2871
  if (localStorageAdapter !== null && maintenanceManifestKey !== null) {
2917
2872
  const nextKnownPersistedBytes = getKnownPersistedBytes(knownPersistedKeys);
2918
- if (hasIgnoreItemFilter || nextKnownPersistedBytes === null || nextKnownPersistedBytes > maxBytes) scheduleLocalStorageMaintenance({ forceManifestKeys: [maintenanceManifestKey] });
2873
+ if (hasIgnoreItemFilter || nextKnownPersistedBytes === null || nextKnownPersistedBytes > maxBytes) scheduleLocalStorageMaintenance([maintenanceManifestKey]);
2919
2874
  return;
2920
2875
  }
2921
2876
  const sessionKey = config.getSessionKey();
@@ -2998,7 +2953,7 @@ function setupCollectionPersistence(config, options = {}) {
2998
2953
  }
2999
2954
  //#endregion
3000
2955
  //#region src/persistentStorage/offline/mutationRuntime.ts
3001
- async function runHybridOfflineMutation({ controller, offline, upload, directMutation }) {
2956
+ async function runHybridOfflineMutation(controller, offline, upload, directMutation) {
3002
2957
  if (!offline || !controller) throw new Error("runHybridOfflineMutation requires an offline mutation and controller");
3003
2958
  const prepared = await controller.prepareForMutation({
3004
2959
  offline,
@@ -3029,14 +2984,14 @@ function isOfflineResolutionRecordForStore(resolution, operations) {
3029
2984
  }
3030
2985
  //#endregion
3031
2986
  //#region src/persistentStorage/offline/overlayStoreLifecycle.ts
3032
- function rebindOfflineOverlayEntries(args) {
3033
- if (args.itemKeyRewrites.length === 0) return;
3034
- args.overlayStore.produceState((draft) => {
3035
- for (const { previousItemKey, nextItemKey } of args.itemKeyRewrites) {
2987
+ function rebindOfflineOverlayEntries(overlayStore, itemKeyRewrites, createReboundOverlay) {
2988
+ if (itemKeyRewrites.length === 0) return;
2989
+ overlayStore.produceState((draft) => {
2990
+ for (const { previousItemKey, nextItemKey } of itemKeyRewrites) {
3036
2991
  if (previousItemKey === nextItemKey) continue;
3037
2992
  const existingOverlay = draft[previousItemKey];
3038
2993
  if (existingOverlay === void 0) continue;
3039
- if (draft[nextItemKey] === void 0) draft[nextItemKey] = args.createReboundOverlay({
2994
+ if (draft[nextItemKey] === void 0) draft[nextItemKey] = createReboundOverlay({
3040
2995
  existingOverlay,
3041
2996
  nextItemKey
3042
2997
  });
@@ -3045,28 +3000,26 @@ function rebindOfflineOverlayEntries(args) {
3045
3000
  }
3046
3001
  });
3047
3002
  }
3048
- function captureOfflineOverlayEntries(args) {
3049
- const targetItemKeys = [...new Set(args.itemKeys)];
3003
+ function captureOfflineOverlayEntries(overlayStore, itemKeys, createOverlay) {
3004
+ const targetItemKeys = [...new Set(itemKeys)];
3050
3005
  if (targetItemKeys.length === 0) return;
3051
- args.overlayStore.produceState((draft) => {
3006
+ overlayStore.produceState((draft) => {
3052
3007
  for (const itemKey of targetItemKeys) {
3053
3008
  const existingOverlay = draft[itemKey];
3054
3009
  if (existingOverlay?.keepVisibleWhileResolutionRequired) {
3055
3010
  existingOverlay.keepVisibleWhileResolutionRequired = false;
3056
3011
  continue;
3057
3012
  }
3058
- draft[itemKey] = args.createOverlay(itemKey);
3013
+ draft[itemKey] = createOverlay(itemKey);
3059
3014
  }
3060
3015
  });
3061
3016
  }
3062
3017
  //#endregion
3063
3018
  //#region src/utils/browserTabsPriority.ts
3064
- const DEFAULT_HEARTBEAT_MS = 5e3;
3065
- const DEFAULT_PRESENCE_TTL_MS = 15e3;
3066
3019
  const DEFAULT_FETCH_LEASE_MS = 1e4;
3067
3020
  const COALESCING_WINDOW_STEP_MS = 1e3;
3068
3021
  /** @internal */
3069
- function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getWindowIsFocused, onWindowFocusChange, publishStatus, timings, onLeaderChange }) {
3022
+ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWindowIsFocused, onWindowFocusChange, publishStatus, timings, onLeaderChange) {
3070
3023
  const knownTabs = /* @__PURE__ */ new Map();
3071
3024
  const remoteFetchLeases = /* @__PURE__ */ new Map();
3072
3025
  let lastLeaderTabId;
@@ -3076,25 +3029,18 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3076
3029
  lastFocusedAt: getWindowIsFocused() ? Date.now() : 0,
3077
3030
  lastPresenceAt: Date.now()
3078
3031
  };
3079
- const heartbeatMs = timings?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
3080
- const presenceTtlMs = timings?.presenceTtlMs ?? DEFAULT_PRESENCE_TTL_MS;
3081
3032
  function resolveFetchLeaseMs(lastFetchDuration) {
3082
3033
  const configuredLeaseMs = timings?.fetchLeaseMs;
3083
3034
  if (typeof configuredLeaseMs === "function") return Math.max(0, configuredLeaseMs(lastFetchDuration));
3084
3035
  if (typeof configuredLeaseMs === "number") return Math.max(0, configuredLeaseMs);
3085
3036
  return Math.max(lastFetchDuration * 3, DEFAULT_FETCH_LEASE_MS);
3086
3037
  }
3087
- function pruneStaleTabs() {
3088
- const now = Date.now();
3089
- for (const [remoteTabId, presence] of knownTabs) if (now - presence.lastPresenceAt > presenceTtlMs) knownTabs.delete(remoteTabId);
3090
- }
3091
3038
  function pruneExpiredRemoteLeases() {
3092
3039
  const now = Date.now();
3093
3040
  for (const [targetKey, lease] of remoteFetchLeases) if (lease.expiresAt <= now) remoteFetchLeases.delete(targetKey);
3094
3041
  }
3095
3042
  function getRankedLiveTabs() {
3096
3043
  if (!getIsEnabled()) return [localPresence];
3097
- pruneStaleTabs();
3098
3044
  return [localPresence, ...knownTabs.values()].sort((a, b) => {
3099
3045
  if (a.isFocused !== b.isFocused) return a.isFocused ? -1 : 1;
3100
3046
  if (a.lastFocusedAt !== b.lastFocusedAt) return b.lastFocusedAt - a.lastFocusedAt;
@@ -3211,13 +3157,8 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3211
3157
  remoteFetchLeases.clear();
3212
3158
  }
3213
3159
  let cleanupFocusListeners;
3214
- let heartbeatInterval;
3215
- const shouldRunHeartbeat = transportEnabled && heartbeatMs > 0 && true;
3216
3160
  if (transportEnabled) {
3217
3161
  publishLocalStatus();
3218
- if (shouldRunHeartbeat) heartbeatInterval = setInterval(() => {
3219
- publishLocalStatus();
3220
- }, heartbeatMs);
3221
3162
  if (onWindowFocusChange) cleanupFocusListeners = onWindowFocusChange(() => {
3222
3163
  noteLocalFocusState();
3223
3164
  });
@@ -3246,7 +3187,6 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3246
3187
  reset,
3247
3188
  close() {
3248
3189
  cleanupFocusListeners?.();
3249
- if (heartbeatInterval) clearInterval(heartbeatInterval);
3250
3190
  reset();
3251
3191
  knownTabs.clear();
3252
3192
  }
@@ -3290,11 +3230,10 @@ function getDefaultTransportFactory() {
3290
3230
  };
3291
3231
  }
3292
3232
  /** @internal */
3293
- function createBrowserTabsCoordinator(options) {
3294
- const { storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory = getDefaultTransportFactory() } = options;
3295
- const debugLogger = import.meta.env.DEV ? options.debugLogger : void 0;
3233
+ function createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, tabId = createBrowserTabsTabId()) {
3234
+ const resolvedTransportFactory = transportFactory ?? getDefaultTransportFactory();
3235
+ const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3296
3236
  const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3297
- const tabId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
3298
3237
  let seq = 0;
3299
3238
  const lastSeenSeqByTab = /* @__PURE__ */ new Map();
3300
3239
  let currentSessionKey;
@@ -3330,7 +3269,7 @@ function createBrowserTabsCoordinator(options) {
3330
3269
  }
3331
3270
  return nextSessionKey;
3332
3271
  }
3333
- const transport = transportFactory({
3272
+ const transport = resolvedTransportFactory({
3334
3273
  channelName,
3335
3274
  onMessage(rawMessage) {
3336
3275
  const localSessionKey = refreshSessionKey();
@@ -3434,57 +3373,58 @@ function createBrowserTabsCoordinator(options) {
3434
3373
  };
3435
3374
  }
3436
3375
  /** @internal */
3437
- function createBrowserTabsCoordinatorWithPriority(options) {
3438
- const { storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, getWindowIsFocused, onWindowFocusChange, priorityTimings } = options;
3439
- const debugLogger = import.meta.env.DEV ? options.debugLogger : void 0;
3376
+ function createBrowserTabsCoordinatorWithPriority(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, getWindowIsFocused, onWindowFocusChange, priorityTimings, tabId) {
3377
+ const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3440
3378
  const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3441
3379
  const priorityRef = { current: null };
3442
- const coordinator = createBrowserTabsCoordinator({
3443
- storeType,
3444
- storeKey,
3445
- getSessionKey,
3446
- onMessage,
3447
- onSessionChange(sessionKey, previousSessionKey) {
3448
- priorityRef.current?.reset();
3449
- if (sessionKey !== false && coordinator.enabled) priorityRef.current?.publishLocalStatus();
3450
- onSessionChange?.(sessionKey, previousSessionKey);
3451
- },
3452
- transportFactory,
3453
- ...import.meta.env.DEV ? { debugLogger: options.debugLogger } : void 0
3454
- });
3455
- const priority = createBrowserTabsPriority({
3456
- transportEnabled: coordinator.enabled,
3457
- getIsEnabled: () => coordinator.isSessionActive(),
3458
- tabId: coordinator.tabId,
3459
- getWindowIsFocused,
3460
- onWindowFocusChange,
3461
- publishStatus: (status) => {
3462
- coordinator.publish(__LEGIT_CAST__(status));
3463
- },
3464
- timings: priorityTimings,
3465
- ...import.meta.env.DEV ? { onLeaderChange(details) {
3466
- if (!debugLogger) return;
3467
- emitTSDFDebugLog(debugLogger, {
3468
- area: "browser-tabs",
3469
- level: "log",
3470
- message: "browser-tab sync leader changed",
3471
- operation: "leader-change",
3472
- details: {
3473
- channelName,
3474
- storeKey,
3475
- storeType,
3476
- tabId: details.localTabId,
3477
- ...details
3478
- }
3479
- });
3480
- } } : void 0
3481
- });
3380
+ const coordinator = createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, (sessionKey, previousSessionKey) => {
3381
+ priorityRef.current?.reset();
3382
+ if (sessionKey !== false && coordinator.enabled) priorityRef.current?.publishLocalStatus();
3383
+ onSessionChange?.(sessionKey, previousSessionKey);
3384
+ }, transportFactory, debugLoggerInput, tabId);
3385
+ const priority = createBrowserTabsPriority(coordinator.enabled, () => coordinator.isSessionActive(), coordinator.tabId, getWindowIsFocused, onWindowFocusChange, (status) => {
3386
+ coordinator.publish(__LEGIT_CAST__(status));
3387
+ }, priorityTimings, import.meta.env.DEV ? (details) => {
3388
+ if (!debugLogger) return;
3389
+ emitTSDFDebugLog(debugLogger, {
3390
+ area: "browser-tabs",
3391
+ level: "log",
3392
+ message: "browser-tab sync leader changed",
3393
+ operation: "leader-change",
3394
+ details: {
3395
+ channelName,
3396
+ storeKey,
3397
+ storeType,
3398
+ tabId: details.localTabId,
3399
+ ...details
3400
+ }
3401
+ });
3402
+ } : void 0);
3482
3403
  priorityRef.current = priority;
3483
3404
  return {
3484
3405
  coordinator,
3485
3406
  priority
3486
3407
  };
3487
3408
  }
3409
+ /** @internal */
3410
+ function createBrowserTabsPresencePriority(options) {
3411
+ const priorityRef = { current: null };
3412
+ const { coordinator, priority } = createBrowserTabsCoordinatorWithPriority("presence", "manager", options.getSessionKey, (message) => {
3413
+ priorityRef.current?.onTabStatusMessage(message.tabId, message);
3414
+ }, void 0, options.transportFactory, import.meta.env.DEV ? options.debugLogger : void 0, options.getWindowIsFocused, options.onWindowFocusChange, options.priorityTimings);
3415
+ priorityRef.current = priority;
3416
+ return {
3417
+ priority,
3418
+ tabId: coordinator.tabId,
3419
+ close() {
3420
+ coordinator.close();
3421
+ priority.close();
3422
+ }
3423
+ };
3424
+ }
3425
+ function createBrowserTabsTabId() {
3426
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
3427
+ }
3488
3428
  function toBrowserTabsSyncVersion(meta, consistency) {
3489
3429
  return {
3490
3430
  tabId: meta.tabId,
@@ -3520,25 +3460,25 @@ function stripStoredUploadFile(record) {
3520
3460
  const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, ...upload } = record;
3521
3461
  return upload;
3522
3462
  }
3523
- function createStoredUploadRecord(args) {
3524
- const file = normalizeUploadFile(args.file, args.id);
3463
+ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt) {
3464
+ const file = normalizeUploadFile(fileInput, id);
3525
3465
  const now = Date.now();
3526
- const createdAt = args.createdAt ?? now;
3466
+ const createdAt = createdAtInput ?? now;
3527
3467
  const updatedAt = now;
3528
3468
  return {
3529
- id: args.id,
3530
- sessionKey: args.sessionKey,
3531
- source: args.source,
3532
- state: args.state ?? "pending",
3469
+ id,
3470
+ sessionKey,
3471
+ source,
3472
+ state: state ?? "pending",
3533
3473
  fileName: file.name,
3534
3474
  mimeType: file.type,
3535
3475
  sizeBytes: file.size,
3536
3476
  createdAt,
3537
3477
  updatedAt,
3538
- ...args.resolvedRef !== void 0 ? { resolvedRef: args.resolvedRef } : {},
3539
- ...args.progress !== void 0 ? { progress: args.progress } : {},
3540
- ...args.lastError !== void 0 ? { lastError: args.lastError } : {},
3541
- ...args.lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt: args.lastOnlineSessionStartedAt } : {},
3478
+ ...resolvedRef !== void 0 ? { resolvedRef } : {},
3479
+ ...progress !== void 0 ? { progress } : {},
3480
+ ...lastError !== void 0 ? { lastError } : {},
3481
+ ...lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt } : {},
3542
3482
  file,
3543
3483
  lastModified: file.lastModified
3544
3484
  };
@@ -3853,21 +3793,14 @@ var SessionOfflineCoordinator = class {
3853
3793
  })
3854
3794
  });
3855
3795
  this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
3856
- this.#browserTabs = createBrowserTabsCoordinatorWithPriority({
3857
- storeType: "offline",
3858
- storeKey: `session:${sessionKey}`,
3859
- getSessionKey: () => this.sessionKey,
3860
- getWindowIsFocused: () => !isWindowAvailable() || !document.hidden,
3861
- onMessage: (message) => {
3862
- if (message.kind === "tab-status") {
3863
- this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
3864
- this.#refreshLeadership();
3865
- return;
3866
- }
3867
- this.#applyRemoteSnapshot(message);
3868
- },
3869
- ...import.meta.env.DEV ? { debugLogger } : void 0
3870
- });
3796
+ this.#browserTabs = createBrowserTabsCoordinatorWithPriority("offline", `session:${sessionKey}`, () => this.sessionKey, (message) => {
3797
+ if (message.kind === "tab-status") {
3798
+ this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
3799
+ this.#refreshLeadership();
3800
+ return;
3801
+ }
3802
+ this.#applyRemoteSnapshot(message);
3803
+ }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, void 0, void 0);
3871
3804
  this.#refreshLeadership();
3872
3805
  if (shouldBootstrapFromStorage) this.hydrate();
3873
3806
  if (this.#hasCanonicalConfig) this.#refreshNetworkConfig();
@@ -4029,14 +3962,7 @@ var SessionOfflineCoordinator = class {
4029
3962
  async saveUpload(args) {
4030
3963
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
4031
3964
  const existing = this.#uploads.get(args.id);
4032
- const nextRecord = createStoredUploadRecord({
4033
- id: args.id,
4034
- sessionKey: this.sessionKey,
4035
- file: args.file,
4036
- source: args.source ?? "manual",
4037
- createdAt: existing?.createdAt,
4038
- lastOnlineSessionStartedAt: this.#getCurrentUploadOnlineSessionStartedAt()
4039
- });
3965
+ const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt());
4040
3966
  await this.#saveUploadRecord(nextRecord);
4041
3967
  }
4042
3968
  async replaceUpload(args) {
@@ -5173,10 +5099,9 @@ function initializeOfflineStoreController(controller) {
5173
5099
  controller.ensureReplayScheduled();
5174
5100
  });
5175
5101
  }
5176
- function createOfflineStoreController(options) {
5177
- const { storeName, storeType, getSessionKey, onPersistentStorageError, adapter, storeAdapter, offlineSession, operations } = options;
5102
+ function createOfflineStoreController(storeName, storeType, getSessionKey, onPersistentStorageError, debugLogger, adapter, storeAdapter, offlineSession, operations) {
5178
5103
  const sessionConfig = offlineSession.getConfig();
5179
- const activeDebugLogger = import.meta.env.DEV ? options.debugLogger : void 0;
5104
+ const activeDebugLogger = import.meta.env.DEV ? debugLogger : void 0;
5180
5105
  const replayQueue = createAsyncQueue({
5181
5106
  concurrency: 1,
5182
5107
  autoStart: true
@@ -7663,6 +7588,7 @@ function createStoreManager(options) {
7663
7588
  useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
7664
7589
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
7665
7590
  const registry = {
7591
+ browserTabsPresence: void 0,
7666
7592
  nextStoreRegistrationId: 0,
7667
7593
  stores: /* @__PURE__ */ new Map()
7668
7594
  };
@@ -7696,9 +7622,13 @@ function createStoreManager(options) {
7696
7622
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
7697
7623
  return storeManager;
7698
7624
  }
7699
- function registerStoreWithManager(storeManager, store) {
7625
+ function getRegistryOrThrow(storeManager) {
7700
7626
  const registry = storeManagerRegistry.get(storeManager);
7701
7627
  if (!registry) throw new Error("[tsdf] storeManager must be created with createStoreManager(...)");
7628
+ return registry;
7629
+ }
7630
+ function registerStoreWithManager(storeManager, store) {
7631
+ const registry = getRegistryOrThrow(storeManager);
7702
7632
  let hasDuplicateId = false;
7703
7633
  for (const registeredStore of registry.stores.values()) if (registeredStore.id === store.id) {
7704
7634
  hasDuplicateId = true;
@@ -7710,23 +7640,42 @@ function registerStoreWithManager(storeManager, store) {
7710
7640
  registry.stores.set(registrationId, store);
7711
7641
  return () => {
7712
7642
  registry.stores.delete(registrationId);
7643
+ if (registry.stores.size === 0) {
7644
+ registry.browserTabsPresence?.close();
7645
+ registry.browserTabsPresence = void 0;
7646
+ }
7713
7647
  };
7714
7648
  }
7715
- function resolveStoreManagerOfflineSession(args) {
7716
- const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(args.storeManager));
7717
- if (!args.usesOfflineStorage) return null;
7718
- if (!offlineSession) throw new Error(`[tsdf] Store "${args.storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
7649
+ function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
7650
+ const registry = getRegistryOrThrow(storeManager);
7651
+ const presence = registry.browserTabsPresence ??= createBrowserTabsPresencePriority({
7652
+ getSessionKey: storeManager.getSessionKey,
7653
+ getWindowIsFocused: options.getWindowIsFocused,
7654
+ onWindowFocusChange: options.onWindowFocusChange,
7655
+ transportFactory: options.transportFactory,
7656
+ ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
7657
+ priorityTimings: options.priorityTimings
7658
+ });
7659
+ return {
7660
+ priority: presence.priority,
7661
+ tabId: presence.tabId
7662
+ };
7663
+ }
7664
+ function resolveStoreManagerOfflineSession(storeManager, storeName, usesOfflineStorage) {
7665
+ const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(storeManager));
7666
+ if (!usesOfflineStorage) return null;
7667
+ if (!offlineSession) throw new Error(`[tsdf] Store "${storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
7719
7668
  return offlineSession;
7720
7669
  }
7721
- function validateStoreManagerSessionConsistency(args) {
7722
- const sessionKey = args.getSessionKey();
7723
- const offlineSessionKey = args.offlineSession.getSessionKey();
7724
- if (sessionKey !== offlineSessionKey) throw new Error(`[tsdf] Store "${args.storeName}" is attached to offline session "${offlineSessionKey}" but storeManager.getSessionKey() returned "${sessionKey}"`);
7670
+ function validateStoreManagerSessionConsistency(storeName, offlineSession, getSessionKey) {
7671
+ const sessionKey = getSessionKey();
7672
+ const offlineSessionKey = offlineSession.getSessionKey();
7673
+ if (sessionKey !== offlineSessionKey) throw new Error(`[tsdf] Store "${storeName}" is attached to offline session "${offlineSessionKey}" but storeManager.getSessionKey() returned "${sessionKey}"`);
7725
7674
  return sessionKey;
7726
7675
  }
7727
7676
  //#endregion
7728
7677
  //#region src/utils/performMutation.ts
7729
- async function performMutationWithLifecycle({ startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose }) {
7678
+ async function performMutationWithLifecycle(startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose) {
7730
7679
  const endMutation = startMutation();
7731
7680
  if (optimisticUpdate?.() === false) {
7732
7681
  endMutation();
@@ -7758,7 +7707,7 @@ async function performMutationWithLifecycle({ startMutation, mutation, onError,
7758
7707
  //#endregion
7759
7708
  //#region src/utils/storeFocusLifecycle.ts
7760
7709
  /** @internal */
7761
- function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate }) {
7710
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate) {
7762
7711
  let cleanupFocusListener = null;
7763
7712
  let cleanupReconnectFocusListener = null;
7764
7713
  let reconnectCooldownTimeoutId = null;
@@ -7852,7 +7801,7 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7852
7801
  //#endregion
7853
7802
  //#region src/collectionStore/collectionCacheLimits.ts
7854
7803
  /** @internal */
7855
- function createCollectionCacheLimits({ store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup }) {
7804
+ function createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup) {
7856
7805
  let isEnforcingCacheLimits = false;
7857
7806
  function enforceCacheLimits() {
7858
7807
  if (maxItems === void 0 || isEnforcingCacheLimits) return;
@@ -7897,7 +7846,7 @@ const offlineConnectivityError = {
7897
7846
  function normalizeFetchResultError(fetchResult, errorNormalizer) {
7898
7847
  return fetchResult.offline ? offlineConnectivityError : normalizeStoreError(fetchResult.error, errorNormalizer);
7899
7848
  }
7900
- async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7849
+ async function runOfflineAwareFetch(controller, fetcher, operationName) {
7901
7850
  await controller?.prepareForFetch?.();
7902
7851
  const shouldTreatFetchAsOffline = () => controller?.shouldTreatFetchAsOffline?.() ?? controller?.getSessionStatus()?.isOfflineMode ?? false;
7903
7852
  if (shouldTreatFetchAsOffline()) return {
@@ -7926,7 +7875,7 @@ async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7926
7875
  }
7927
7876
  //#endregion
7928
7877
  //#region src/utils/reusePrevIfEqual.ts
7929
- function reusePrevIfEqual({ prev, current }) {
7878
+ function reusePrevIfEqual(prev, current) {
7930
7879
  if (prev === void 0) return current;
7931
7880
  if (deepEqual(prev, current)) return prev;
7932
7881
  return current;
@@ -7963,10 +7912,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
7963
7912
  }
7964
7913
  if (batchFetchFn && requests.length > 1) try {
7965
7914
  const payloads = requests.map((r) => r.payload);
7966
- const fetchResult = await runOfflineAwareFetch({
7967
- controller: offlineController,
7968
- fetcher: () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__")
7969
- });
7915
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__"));
7970
7916
  if (!fetchResult.ok) {
7971
7917
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
7972
7918
  store.produceState((draft) => {
@@ -8000,10 +7946,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8000
7946
  item.status = "error";
8001
7947
  results.set(itemId, false);
8002
7948
  } else if (result !== void 0) try {
8003
- item.data = reusePrevIfEqual({
8004
- current: unwrapMaybeTSDFResult(result),
8005
- prev: item.data
8006
- });
7949
+ item.data = reusePrevIfEqual(item.data, unwrapMaybeTSDFResult(result));
8007
7950
  item.status = "success";
8008
7951
  item.wasLoaded = true;
8009
7952
  results.set(itemId, true);
@@ -8039,10 +7982,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8039
7982
  }
8040
7983
  const fetchPromises = requests.map(async ({ requestId: itemId, payload }) => {
8041
7984
  try {
8042
- const fetchResult = await runOfflineAwareFetch({
8043
- controller: offlineController,
8044
- fetcher: () => fetchFn(klona(payload), fetchCtx.signal)
8045
- });
7985
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchFn(klona(payload), fetchCtx.signal));
8046
7986
  if (!fetchResult.ok) {
8047
7987
  if (fetchCtx.shouldAbort()) {
8048
7988
  results.set(itemId, false);
@@ -8071,10 +8011,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8071
8011
  store.produceState((draft) => {
8072
8012
  const item = draft[itemId];
8073
8013
  if (!item) return;
8074
- item.data = reusePrevIfEqual({
8075
- current: data,
8076
- prev: item.data
8077
- });
8014
+ item.data = reusePrevIfEqual(item.data, data);
8078
8015
  item.status = "success";
8079
8016
  item.wasLoaded = true;
8080
8017
  }, { action: "fetch-success" });
@@ -8307,8 +8244,7 @@ function createFieldsResourceSignature(fields) {
8307
8244
  if (fields === void 0) return "";
8308
8245
  return JSON.stringify(Array.from(new Set(fields)).sort());
8309
8246
  }
8310
- function shouldScheduleAutomaticFetch(options) {
8311
- const { wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false } = options;
8247
+ function shouldScheduleAutomaticFetch(wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false) {
8312
8248
  if (disableRefetches) return !wasLoaded;
8313
8249
  if (disableRefetchOnMount) return shouldFetch;
8314
8250
  if (skipFreshFetch && !shouldFetch) return false;
@@ -8503,14 +8439,7 @@ function useMultipleItems$1(items, { selector, returnIdleStatus: allItemsReturnI
8503
8439
  const shouldFetch = requiredFetch || !!itemState.refetchOnMount;
8504
8440
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemId)) continue;
8505
8441
  ignoreItemsInRefetchOnMount.add(itemId);
8506
- if (shouldScheduleAutomaticFetch({
8507
- wasLoaded: itemState?.wasLoaded,
8508
- shouldFetch,
8509
- requiredFetch,
8510
- disableRefetches,
8511
- disableRefetchOnMount,
8512
- refetchOnMount: itemState?.refetchOnMount ?? false
8513
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, itemId, itemState?.status)) scheduleAutomaticFetch(fetchType, payload);
8442
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount) && tryClaimAutomaticFetchSlot(automaticRetryState, itemId, itemState?.status)) scheduleAutomaticFetch(fetchType, payload);
8514
8443
  }
8515
8444
  }
8516
8445
  for (const itemId of removedQueries) ignoreItemsInRefetchOnMount.delete(itemId);
@@ -8551,18 +8480,9 @@ function createCollectionStore(storeOptions) {
8551
8480
  let offlineOverlaySessionKey = null;
8552
8481
  const itemCacheRuntime = createLruCacheRuntime();
8553
8482
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
8554
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
8555
- storeManager,
8556
- storeName: id,
8557
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
8558
- });
8483
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
8559
8484
  const getSessionKeyBase = storeManager.getSessionKey;
8560
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
8561
- storeManager,
8562
- storeName: id,
8563
- offlineSession: resolvedOfflineSession,
8564
- getSessionKey: getSessionKeyBase
8565
- });
8485
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
8566
8486
  const errorNormalizer = storeManager.errorNormalizer;
8567
8487
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
8568
8488
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -8596,100 +8516,76 @@ function createCollectionStore(storeOptions) {
8596
8516
  offlineOverlayStore.setState({});
8597
8517
  }
8598
8518
  function rebindOfflineOverlays(itemKeyRewrites) {
8599
- rebindOfflineOverlayEntries({
8600
- itemKeyRewrites,
8601
- overlayStore: offlineOverlayStore,
8602
- createReboundOverlay: ({ existingOverlay, nextItemKey }) => ({
8603
- data: existingOverlay.data ?? null,
8604
- payload: store.state[nextItemKey]?.payload ?? existingOverlay.payload,
8605
- keepVisibleWhileResolutionRequired: true
8606
- })
8607
- });
8519
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
8520
+ data: existingOverlay.data ?? null,
8521
+ payload: store.state[nextItemKey]?.payload ?? existingOverlay.payload,
8522
+ keepVisibleWhileResolutionRequired: true
8523
+ }));
8608
8524
  }
8609
8525
  function captureOfflineOverlays(itemKeys) {
8610
- captureOfflineOverlayEntries({
8611
- itemKeys,
8612
- overlayStore: offlineOverlayStore,
8613
- createOverlay: (itemKey) => {
8614
- const item = store.state[itemKey];
8615
- return {
8616
- data: item ? klona(item.data) : null,
8617
- payload: item ? klona(item.payload) : void 0
8618
- };
8619
- }
8526
+ captureOfflineOverlayEntries(offlineOverlayStore, itemKeys, (itemKey) => {
8527
+ const item = store.state[itemKey];
8528
+ return {
8529
+ data: item ? klona(item.data) : null,
8530
+ payload: item ? klona(item.payload) : void 0
8531
+ };
8620
8532
  });
8621
8533
  }
8622
8534
  const resolvedOfflineConfig = resolvedPersistentStorageConfig?.offline;
8623
8535
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_COLLECTION_OFFLINE_OPERATIONS);
8624
8536
  const offlineOperationsForRuntime = resolvedOfflineOperations;
8625
- const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController({
8626
- storeName: id,
8627
- storeType: "collection",
8628
- getSessionKey: getSessionKeyForRuntime,
8629
- onPersistentStorageError: resolvedPersistentStorageConfig.onPersistentStorageError,
8630
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8631
- adapter: resolvedPersistentStorageConfig.adapter,
8632
- offlineSession: resolvedOfflineConfig.session,
8633
- operations: __LEGIT_CAST__(offlineOperationsForRuntime),
8634
- storeAdapter: {
8635
- normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
8636
- const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
8637
- if (normalizedRef !== null) return normalizedRef;
8638
- return {
8639
- entityKey: getItemKey(__LEGIT_CAST__(ref)),
8640
- entityKind: "item"
8641
- };
8642
- }),
8643
- getProtectedCacheKeys: (entityRefs) => {
8644
- const sessionKey = getSessionKeyForRuntime();
8645
- if (sessionKey === false) return [];
8646
- return entityRefs.map((ref) => createProtectedStorageKey({
8647
- backend: resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage",
8648
- sessionKey,
8649
- storeName: id,
8650
- kind: "collection.item",
8651
- key: ref.entityKey
8652
- }));
8653
- },
8654
- applyPendingEntity: ({ tempId, pendingEntity }) => {
8655
- if (!pendingEntity || typeof pendingEntity !== "object") return;
8656
- addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
8657
- },
8658
- rollbackPendingEntity: ({ tempId }) => {
8659
- deleteItemState(__LEGIT_CAST__(tempId));
8660
- },
8661
- reconcileTempEntity: ({ tempId, reconciliation }) => {
8662
- const tempPayload = __LEGIT_CAST__(tempId);
8663
- const currentItem = getItemState(tempPayload);
8664
- const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem?.data ?? void 0;
8665
- if (finalData === void 0) return;
8666
- deleteItemState(tempPayload);
8667
- const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
8668
- addItemToState(finalPayload, finalData);
8669
- storeEvents.emit("tempEntityReconciled", {
8670
- tempId: tempPayload,
8671
- finalPayload
8672
- });
8673
- },
8674
- captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
8675
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8676
- captureOfflineOverlays(entityRefs.flatMap((ref) => {
8677
- return ref.entityKind === "item" ? [ref.entityKey] : [];
8678
- }));
8679
- },
8680
- rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
8681
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8682
- rebindOfflineOverlays(itemKeyRewrites);
8683
- },
8684
- syncEntityOverlays: ({ entities, sessionKey }) => {
8685
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8686
- const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
8687
- offlineOverlayStore.produceState((draft) => {
8688
- for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
8689
- });
8690
- }
8537
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "collection", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
8538
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
8539
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
8540
+ if (normalizedRef !== null) return normalizedRef;
8541
+ return {
8542
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
8543
+ entityKind: "item"
8544
+ };
8545
+ }),
8546
+ getProtectedCacheKeys: (entityRefs) => {
8547
+ const sessionKey = getSessionKeyForRuntime();
8548
+ if (sessionKey === false) return [];
8549
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "collection.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
8550
+ },
8551
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
8552
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
8553
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
8554
+ },
8555
+ rollbackPendingEntity: ({ tempId }) => {
8556
+ deleteItemState(__LEGIT_CAST__(tempId));
8557
+ },
8558
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
8559
+ const tempPayload = __LEGIT_CAST__(tempId);
8560
+ const currentItem = getItemState(tempPayload);
8561
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem?.data ?? void 0;
8562
+ if (finalData === void 0) return;
8563
+ deleteItemState(tempPayload);
8564
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
8565
+ addItemToState(finalPayload, finalData);
8566
+ storeEvents.emit("tempEntityReconciled", {
8567
+ tempId: tempPayload,
8568
+ finalPayload
8569
+ });
8570
+ },
8571
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
8572
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8573
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
8574
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
8575
+ }));
8576
+ },
8577
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
8578
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8579
+ rebindOfflineOverlays(itemKeyRewrites);
8580
+ },
8581
+ syncEntityOverlays: ({ entities, sessionKey }) => {
8582
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8583
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
8584
+ offlineOverlayStore.produceState((draft) => {
8585
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
8586
+ });
8691
8587
  }
8692
- }) : null;
8588
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
8693
8589
  function touchItems(itemKeys) {
8694
8590
  itemCacheRuntime.touch(itemKeys, (itemKey) => {
8695
8591
  return store.state[itemKey] !== void 0;
@@ -8931,10 +8827,6 @@ function createCollectionStore(storeOptions) {
8931
8827
  return getKnownScheduler(message.itemKey)?.isMutationInProgress(message.itemKey) ?? false;
8932
8828
  }
8933
8829
  function handleRemoteMessage(message) {
8934
- if (message.kind === "tab-status") {
8935
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
8936
- return;
8937
- }
8938
8830
  if (message.kind === "fetch-start") {
8939
8831
  const scheduler = getSchedulerForTargetKey(message.targetKey);
8940
8832
  scheduler?.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -8953,21 +8845,16 @@ function createCollectionStore(storeOptions) {
8953
8845
  }
8954
8846
  applyRemoteItemSnapshot(message, candidateVersion);
8955
8847
  }
8956
- const { coordinator: browserTabsSync, priority: browserTabsPriority } = createBrowserTabsCoordinatorWithPriority({
8957
- storeType: "collection",
8958
- storeKey: id,
8959
- getSessionKey: getSessionKeyForRuntime,
8960
- onMessage: handleRemoteMessage,
8961
- onSessionChange() {
8962
- lastCollectionSyncVersions.clear();
8963
- clearOfflineOverlays();
8964
- },
8965
- transportFactory: testOptions?.browserTabsTransportFactory,
8966
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8848
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
8967
8849
  getWindowIsFocused,
8968
8850
  onWindowFocusChange: testOptions?.onWindowFocusChange,
8851
+ transportFactory: testOptions?.browserTabsTransportFactory,
8969
8852
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
8970
8853
  });
8854
+ const browserTabsSync = createBrowserTabsCoordinator("collection", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
8855
+ lastCollectionSyncVersions.clear();
8856
+ clearOfflineOverlays();
8857
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
8971
8858
  async function executeBatchFetch$1(requests, fetchCtx, batchKey) {
8972
8859
  const results = await executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchFn, errorNormalizer, batchKey, offlineController);
8973
8860
  const successfulRequests = requests.filter(({ requestId }) => results.get(requestId) === true);
@@ -9246,50 +9133,37 @@ function createCollectionStore(storeOptions) {
9246
9133
  item: klona(store.state[itemKey])
9247
9134
  })) : [];
9248
9135
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
9249
- const result = await performMutationWithLifecycle({
9250
- startMutation: () => startMutation(payloadToUse),
9251
- optimisticUpdate: optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse)) : void 0,
9252
- debounce: _debounce,
9253
- blockWindowClose: blockWindowClose ?? void 0,
9254
- mutation: offline ? () => runHybridOfflineMutation({
9255
- controller: __LEGIT_CAST__(offlineController),
9256
- offline,
9257
- upload,
9258
- directMutation
9259
- }) : async () => ({
9260
- kind: "online",
9261
- data: await directMutation()
9262
- }),
9263
- onSuccess: (result) => {
9264
- if (revalidateOnSuccess && affectedItems.length > 0) invalidateItem(payloadToUse);
9265
- if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
9266
- },
9267
- onError: (exception) => {
9268
- const error = toStoreMutationError(exception, errorNormalizer);
9269
- if (optimisticRollbackSnapshots.length > 0) {
9270
- const restoredItemKeys = [];
9271
- runWithBroadcastConsistency("confirmed", () => {
9272
- store.produceState((draft) => {
9273
- for (const snapshot of optimisticRollbackSnapshots) {
9274
- if (snapshot.item === void 0) {
9275
- delete draft[snapshot.itemKey];
9276
- continue;
9277
- }
9278
- draft[snapshot.itemKey] = snapshot.item;
9279
- }
9280
- }, { action: "rollback-mutation-error" });
9136
+ const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9137
+ kind: "online",
9138
+ data: await directMutation()
9139
+ }), (exception) => {
9140
+ const error = toStoreMutationError(exception, errorNormalizer);
9141
+ if (optimisticRollbackSnapshots.length > 0) {
9142
+ const restoredItemKeys = [];
9143
+ runWithBroadcastConsistency("confirmed", () => {
9144
+ store.produceState((draft) => {
9281
9145
  for (const snapshot of optimisticRollbackSnapshots) {
9282
- if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9283
- else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9284
- publishItemSnapshot(snapshot.itemKey);
9146
+ if (snapshot.item === void 0) {
9147
+ delete draft[snapshot.itemKey];
9148
+ continue;
9149
+ }
9150
+ draft[snapshot.itemKey] = snapshot.item;
9285
9151
  }
9286
- });
9287
- if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9288
- }
9289
- if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9290
- return error;
9291
- }
9292
- });
9152
+ }, { action: "rollback-mutation-error" });
9153
+ for (const snapshot of optimisticRollbackSnapshots) {
9154
+ if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9155
+ else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9156
+ publishItemSnapshot(snapshot.itemKey);
9157
+ }
9158
+ });
9159
+ if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9160
+ }
9161
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9162
+ return error;
9163
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse)) : void 0, (result) => {
9164
+ if (revalidateOnSuccess && affectedItems.length > 0) invalidateItem(payloadToUse);
9165
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
9166
+ }, _debounce, blockWindowClose ?? void 0);
9293
9167
  storeEvents.emit("mutationEnd", {
9294
9168
  mutationId,
9295
9169
  items: affectedItems,
@@ -9298,31 +9172,13 @@ function createCollectionStore(storeOptions) {
9298
9172
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
9299
9173
  return result;
9300
9174
  }
9301
- const focusLifecycle = createStoreFocusLifecycle({
9302
- revalidateOnWindowFocus: resolvedRevalidateOnWindowFocus,
9303
- usesRealTimeUpdates,
9304
- transportReconnectCooldownMs,
9305
- getWindowIsFocused,
9306
- onWindowFocus: testOptions?.onWindowFocus ?? onWindowFocus,
9307
- onWindowFocusRevalidate: () => {
9308
- invalidateItem(() => true, "lowPriority");
9309
- },
9310
- onTransportReconnectRevalidate: () => {
9311
- invalidateItem(() => true, "realtimeUpdate");
9312
- }
9313
- });
9314
- const { enforceCacheLimits } = createCollectionCacheLimits({
9315
- store,
9316
- maxItems,
9317
- itemCacheRuntime,
9318
- isProtectedFromEviction,
9319
- cleanupItemResources,
9320
- onStateCleanup
9321
- });
9322
- const cacheLimitEnforcementScheduler = createIdleThrottledScheduler({
9323
- throttleMs: CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS,
9324
- run: enforceCacheLimits
9175
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9176
+ invalidateItem(() => true, "lowPriority");
9177
+ }, () => {
9178
+ invalidateItem(() => true, "realtimeUpdate");
9325
9179
  });
9180
+ const { enforceCacheLimits } = createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup);
9181
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
9326
9182
  function scheduleCacheLimitEnforcement() {
9327
9183
  cacheLimitEnforcementScheduler.schedule();
9328
9184
  }
@@ -9358,7 +9214,6 @@ function createCollectionStore(storeOptions) {
9358
9214
  clearOfflineOverlays();
9359
9215
  itemCacheRuntime.clearAll();
9360
9216
  cacheLimitEnforcementScheduler.cancel();
9361
- browserTabsPriority.reset();
9362
9217
  persistence?.dispose();
9363
9218
  persistence?.clear();
9364
9219
  store.setState(persistence?.createInitialState({}) ?? {});
@@ -9381,7 +9236,6 @@ function createCollectionStore(storeOptions) {
9381
9236
  itemCacheRuntime.clearAll();
9382
9237
  cacheLimitEnforcementScheduler.cancel();
9383
9238
  browserTabsSync.close();
9384
- browserTabsPriority.close();
9385
9239
  focusLifecycle.dispose();
9386
9240
  persistence?.dispose();
9387
9241
  offlineController?.dispose();
@@ -9709,18 +9563,9 @@ function createDocumentStore(storeOptions) {
9709
9563
  let initialStatus = "idle";
9710
9564
  let initialError = null;
9711
9565
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
9712
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
9713
- storeManager,
9714
- storeName: id,
9715
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
9716
- });
9566
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
9717
9567
  const getSessionKeyBase = storeManager.getSessionKey;
9718
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
9719
- storeManager,
9720
- storeName: id,
9721
- offlineSession: resolvedOfflineSession,
9722
- getSessionKey: getSessionKeyBase
9723
- });
9568
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
9724
9569
  const errorNormalizer = storeManager.errorNormalizer;
9725
9570
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
9726
9571
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -9743,55 +9588,39 @@ function createDocumentStore(storeOptions) {
9743
9588
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_DOCUMENT_OFFLINE_OPERATIONS);
9744
9589
  if (import.meta.env.DEV) assertDocumentOfflineOperations(__LEGIT_CAST__(resolvedOfflineOperations));
9745
9590
  const offlineOperationsForRuntime = resolvedOfflineOperations;
9746
- const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController({
9747
- storeName: id,
9748
- storeType: "document",
9749
- getSessionKey: getSessionKeyForRuntime,
9750
- onPersistentStorageError: resolvedPersistentStorageConfig.onPersistentStorageError,
9751
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9752
- adapter: resolvedPersistentStorageConfig.adapter,
9753
- offlineSession: resolvedOfflineConfig.session,
9754
- operations: __LEGIT_CAST__(offlineOperationsForRuntime),
9755
- storeAdapter: {
9756
- getEntityRefs: () => [{
9757
- entityKey: DOC_TARGET_KEY,
9758
- entityKind: "document"
9759
- }],
9760
- normalizeEntityRefs: () => [{
9761
- entityKey: DOC_TARGET_KEY,
9762
- entityKind: "document"
9763
- }],
9764
- getProtectedCacheKeys: () => {
9765
- const sessionKey = getSessionKeyForRuntime();
9766
- if (sessionKey === false) return [];
9767
- return [createProtectedStorageKey({
9768
- backend: resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage",
9769
- sessionKey,
9770
- storeName: id,
9771
- kind: "document",
9772
- key: "d"
9773
- })];
9774
- },
9775
- applyPendingEntity: ({ pendingEntity }) => {
9776
- if (!pendingEntity || typeof pendingEntity !== "object") return;
9777
- updateState((draft) => Object.assign(draft, pendingEntity));
9778
- },
9779
- reconcileTempEntity: ({ reconciliation }) => {
9780
- if (!reconciliation.finalData || typeof reconciliation.finalData !== "object") return;
9781
- updateState((draft) => Object.assign(draft, reconciliation.finalData));
9782
- },
9783
- captureQueuedMutationOverlays: ({ sessionKey }) => {
9784
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9785
- offlineOverlayStore.setState({ data: klona(store.state.data) });
9786
- },
9787
- syncEntityOverlays: ({ entities, sessionKey }) => {
9788
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9789
- if (!entities.some((entity) => {
9790
- return entity.entityKey === DOC_TARGET_KEY;
9791
- })) offlineOverlayStore.setState(null);
9792
- }
9591
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "document", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
9592
+ getEntityRefs: () => [{
9593
+ entityKey: DOC_TARGET_KEY,
9594
+ entityKind: "document"
9595
+ }],
9596
+ normalizeEntityRefs: () => [{
9597
+ entityKey: DOC_TARGET_KEY,
9598
+ entityKind: "document"
9599
+ }],
9600
+ getProtectedCacheKeys: () => {
9601
+ const sessionKey = getSessionKeyForRuntime();
9602
+ if (sessionKey === false) return [];
9603
+ return [createProtectedStorageKey(sessionKey, id, "document", "d", resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage")];
9604
+ },
9605
+ applyPendingEntity: ({ pendingEntity }) => {
9606
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
9607
+ updateState((draft) => Object.assign(draft, pendingEntity));
9608
+ },
9609
+ reconcileTempEntity: ({ reconciliation }) => {
9610
+ if (!reconciliation.finalData || typeof reconciliation.finalData !== "object") return;
9611
+ updateState((draft) => Object.assign(draft, reconciliation.finalData));
9612
+ },
9613
+ captureQueuedMutationOverlays: ({ sessionKey }) => {
9614
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9615
+ offlineOverlayStore.setState({ data: klona(store.state.data) });
9616
+ },
9617
+ syncEntityOverlays: ({ entities, sessionKey }) => {
9618
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9619
+ if (!entities.some((entity) => {
9620
+ return entity.entityKey === DOC_TARGET_KEY;
9621
+ })) offlineOverlayStore.setState(null);
9793
9622
  }
9794
- }) : null;
9623
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
9795
9624
  const store = new Store({
9796
9625
  debugName: id,
9797
9626
  state: () => persistence?.createInitialState({
@@ -9849,10 +9678,7 @@ function createDocumentStore(storeOptions) {
9849
9678
  }
9850
9679
  runWithoutBroadcast(() => {
9851
9680
  store.setPartialState({
9852
- data: reusePrevIfEqual({
9853
- prev: store.state.data,
9854
- current: message.data
9855
- }),
9681
+ data: reusePrevIfEqual(store.state.data, message.data),
9856
9682
  error: null,
9857
9683
  status: "success",
9858
9684
  refetchOnMount: false
@@ -9865,10 +9691,6 @@ function createDocumentStore(storeOptions) {
9865
9691
  return message.consistency === "confirmed" && scheduler.isMutationInProgress(DOC_REQUEST_ID);
9866
9692
  }
9867
9693
  function handleRemoteMessage(message) {
9868
- if (message.kind === "tab-status") {
9869
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
9870
- return;
9871
- }
9872
9694
  if (message.kind === "fetch-start") {
9873
9695
  if (!hasLocalDocumentState()) return;
9874
9696
  scheduler.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -9888,21 +9710,16 @@ function createDocumentStore(storeOptions) {
9888
9710
  }
9889
9711
  applyRemoteDocumentSnapshot(message, candidateVersion);
9890
9712
  }
9891
- const { coordinator: browserTabsSync, priority: browserTabsPriority } = createBrowserTabsCoordinatorWithPriority({
9892
- storeType: "document",
9893
- storeKey: id,
9894
- getSessionKey: getSessionKeyForRuntime,
9895
- onMessage: handleRemoteMessage,
9896
- onSessionChange() {
9897
- lastDocumentSyncVersion = void 0;
9898
- clearOfflineOverlay();
9899
- },
9900
- transportFactory: testOptions?.browserTabsTransportFactory,
9901
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9713
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
9902
9714
  getWindowIsFocused,
9903
9715
  onWindowFocusChange: testOptions?.onWindowFocusChange,
9716
+ transportFactory: testOptions?.browserTabsTransportFactory,
9904
9717
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
9905
9718
  });
9719
+ const browserTabsSync = createBrowserTabsCoordinator("document", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
9720
+ lastDocumentSyncVersion = void 0;
9721
+ clearOfflineOverlay();
9722
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
9906
9723
  async function executeFetch(fetchCtx) {
9907
9724
  const currentStatus = store.state.status;
9908
9725
  const wasLoadedBeforeFetch = currentStatus === "success";
@@ -9912,10 +9729,7 @@ function createDocumentStore(storeOptions) {
9912
9729
  refetchOnMount: false
9913
9730
  }, { action: currentStatus === "success" ? "fetch-start-refetching" : "fetch-start-loading" });
9914
9731
  try {
9915
- const result = await runOfflineAwareFetch({
9916
- controller: offlineController,
9917
- fetcher: () => fetchFn(fetchCtx.signal)
9918
- });
9732
+ const result = await runOfflineAwareFetch(offlineController, () => fetchFn(fetchCtx.signal));
9919
9733
  if (!result.ok) {
9920
9734
  if (result.offline) {
9921
9735
  store.setPartialState(wasLoadedBeforeFetch ? {
@@ -9932,10 +9746,7 @@ function createDocumentStore(storeOptions) {
9932
9746
  const data = result.data;
9933
9747
  if (fetchCtx.shouldAbort()) return false;
9934
9748
  store.setPartialState({
9935
- data: reusePrevIfEqual({
9936
- prev: store.state.data,
9937
- current: data
9938
- }),
9749
+ data: reusePrevIfEqual(store.state.data, data),
9939
9750
  status: "success"
9940
9751
  }, { action: "fetch-success" });
9941
9752
  return true;
@@ -9987,18 +9798,10 @@ function createDocumentStore(storeOptions) {
9987
9798
  usesRealTimeUpdates
9988
9799
  });
9989
9800
  if (initialStatus !== "idle" || initialData !== null || initialError !== null) scheduler.setLastFetchStartTimeForRequest(DOC_REQUEST_ID, testOptions?.initialLastFetchStartTime ?? 0);
9990
- const focusLifecycle = createStoreFocusLifecycle({
9991
- revalidateOnWindowFocus: resolvedRevalidateOnWindowFocus,
9992
- usesRealTimeUpdates,
9993
- transportReconnectCooldownMs,
9994
- getWindowIsFocused,
9995
- onWindowFocus: testOptions?.onWindowFocus ?? onWindowFocus,
9996
- onWindowFocusRevalidate: () => {
9997
- invalidateData("lowPriority");
9998
- },
9999
- onTransportReconnectRevalidate: () => {
10000
- invalidateData("realtimeUpdate");
10001
- }
9801
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9802
+ invalidateData("lowPriority");
9803
+ }, () => {
9804
+ invalidateData("realtimeUpdate");
10002
9805
  });
10003
9806
  persistence?.attach(store);
10004
9807
  initializeOfflineStoreController(offlineController);
@@ -10085,7 +9888,6 @@ function createDocumentStore(storeOptions) {
10085
9888
  scheduler.reset();
10086
9889
  lastDocumentSyncVersion = void 0;
10087
9890
  clearOfflineOverlay();
10088
- browserTabsPriority.reset();
10089
9891
  persistence?.dispose();
10090
9892
  persistence?.clear();
10091
9893
  store.setState({
@@ -10106,7 +9908,6 @@ function createDocumentStore(storeOptions) {
10106
9908
  lastDocumentSyncVersion = void 0;
10107
9909
  clearOfflineOverlay();
10108
9910
  browserTabsSync.close();
10109
- browserTabsPriority.close();
10110
9911
  focusLifecycle.dispose();
10111
9912
  persistence?.dispose();
10112
9913
  offlineController?.dispose();
@@ -10123,32 +9924,19 @@ function createDocumentStore(storeOptions) {
10123
9924
  updateState,
10124
9925
  currentState: store.state.data
10125
9926
  }));
10126
- const result = await performMutationWithLifecycle({
10127
- startMutation,
10128
- optimisticUpdate: optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data)) : void 0,
10129
- debounce,
10130
- blockWindowClose: blockWindowClose ?? void 0,
10131
- mutation: offline ? () => runHybridOfflineMutation({
10132
- controller: __LEGIT_CAST__(offlineController),
10133
- offline,
10134
- upload,
10135
- directMutation
10136
- }) : async () => ({
10137
- kind: "online",
10138
- data: await directMutation()
10139
- }),
10140
- onSuccess: (result) => {
10141
- if (revalidateOnSuccess && result.kind === "online") invalidateData();
10142
- },
10143
- onError: (exception) => {
10144
- if (optimisticUpdate) runWithBroadcastConsistency("confirmed", () => {
10145
- store.setKey("data", optimisticRollbackSnapshot ?? null, { action: "rollback-mutation-error" });
10146
- publishDocumentSnapshot();
10147
- });
10148
- if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
10149
- return toStoreMutationError(exception, errorNormalizer);
10150
- }
10151
- });
9927
+ const result = await performMutationWithLifecycle(startMutation, offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9928
+ kind: "online",
9929
+ data: await directMutation()
9930
+ }), (exception) => {
9931
+ if (optimisticUpdate) runWithBroadcastConsistency("confirmed", () => {
9932
+ store.setKey("data", optimisticRollbackSnapshot ?? null, { action: "rollback-mutation-error" });
9933
+ publishDocumentSnapshot();
9934
+ });
9935
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9936
+ return toStoreMutationError(exception, errorNormalizer);
9937
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data)) : void 0, (result) => {
9938
+ if (revalidateOnSuccess && result.kind === "online") invalidateData();
9939
+ }, debounce, blockWindowClose ?? void 0);
10152
9940
  storeEvents.emit("mutationEnd", {
10153
9941
  mutationId,
10154
9942
  status: result.ok ? "success" : result.error === mutationSkipped ? "skipped" : "error"
@@ -10221,16 +10009,7 @@ function createDocumentStore(storeOptions) {
10221
10009
  }
10222
10010
  if (disabled) return;
10223
10011
  const fetchType = store.state.refetchOnMount || "lowPriority";
10224
- const wasLoaded = store.state.status === "success" || store.state.status === "refetching";
10225
- const requiredFetch = store.state.status === "idle" || store.state.status === "error";
10226
- if (shouldScheduleAutomaticFetch({
10227
- wasLoaded,
10228
- shouldFetch: requiredFetch || !!store.state.refetchOnMount,
10229
- requiredFetch,
10230
- disableRefetches: !!disableRefetches,
10231
- disableRefetchOnMount: !!disableRefetchOnMount,
10232
- refetchOnMount: store.state.refetchOnMount
10233
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, DOC_TARGET_KEY, store.state.status)) scheduleFetch(fetchType);
10012
+ if (shouldScheduleAutomaticFetch(store.state.status === "success" || store.state.status === "refetching", store.state.status === "idle" || store.state.status === "error" || !!store.state.refetchOnMount, !!disableRefetches, !!disableRefetchOnMount) && tryClaimAutomaticFetchSlot(automaticRetryState, DOC_TARGET_KEY, store.state.status)) scheduleFetch(fetchType);
10234
10013
  })();
10235
10014
  return () => {
10236
10015
  effectState.cancelled = true;
@@ -10397,14 +10176,8 @@ function readManifestGroupMeta(meta) {
10397
10176
  function setupListQueryPersistence(config, options = {}) {
10398
10177
  assertValidPersistentStoreName(config.storeName);
10399
10178
  const version = config.version;
10400
- const defaultMaxItemBytes = getDefaultMaxBytesForScope({
10401
- adapter: config.adapter,
10402
- scopeKind: "listQuery.item"
10403
- });
10404
- const defaultMaxQueryBytes = getDefaultMaxBytesForScope({
10405
- adapter: config.adapter,
10406
- scopeKind: "listQuery.query"
10407
- });
10179
+ const defaultMaxItemBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.item");
10180
+ const defaultMaxQueryBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.query");
10408
10181
  const maxItemBytes = config.maxItemBytes ?? defaultMaxItemBytes;
10409
10182
  const maxQueryBytes = config.maxQueryBytes ?? defaultMaxQueryBytes;
10410
10183
  const maxQuerySize = config.maxQuerySize ?? DEFAULT_MAX_QUERY_SIZE;
@@ -10507,38 +10280,18 @@ function setupListQueryPersistence(config, options = {}) {
10507
10280
  const asyncItemNamespaceScope = getAsyncItemNamespaceScope();
10508
10281
  if (asyncItemNamespaceScope === null) return JSON.stringify(args.value).length;
10509
10282
  const serializedValue = serializeJsonForStorage(args.value.data);
10510
- return estimateManagedAsyncStorageEntrySizeBytes({
10511
- customMetadata: mergeManagedAsyncStorageCustomMetadata({
10512
- currentCustomMetadata: args.currentCustomMetadata,
10513
- key: args.itemKey,
10514
- nextCustomMetadata: args.nextCustomMetadata,
10515
- protectedKeysSnapshotSet: args.protectedKeysSnapshotSet,
10516
- scope: asyncItemNamespaceScope
10517
- }),
10518
- lastAccessAt: args.lastAccessAt,
10519
- serializedValue: serializedValue.rawValue,
10520
- version: version ?? 1
10521
- });
10283
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, args.nextCustomMetadata, args.protectedKeysSnapshotSet, asyncItemNamespaceScope, args.itemKey);
10284
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10522
10285
  }
10523
10286
  function estimateAsyncQueryEntrySizeBytes(args) {
10524
10287
  const asyncQueryNamespaceScope = getAsyncQueryNamespaceScope();
10525
10288
  if (asyncQueryNamespaceScope === null) return JSON.stringify(args.value).length;
10526
10289
  const serializedValue = serializeJsonForStorage(args.value.items);
10527
- return estimateManagedAsyncStorageEntrySizeBytes({
10528
- customMetadata: mergeManagedAsyncStorageCustomMetadata({
10529
- currentCustomMetadata: args.currentCustomMetadata,
10530
- key: args.queryKey,
10531
- nextCustomMetadata: {
10532
- ...args.value.hasMore ? { h: true } : {},
10533
- p: args.value.payload
10534
- },
10535
- protectedKeysSnapshotSet: args.protectedKeysSnapshotSet,
10536
- scope: asyncQueryNamespaceScope
10537
- }),
10538
- lastAccessAt: args.lastAccessAt,
10539
- serializedValue: serializedValue.rawValue,
10540
- version: version ?? 1
10541
- });
10290
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, {
10291
+ ...args.value.hasMore ? { h: true } : {},
10292
+ p: args.value.payload
10293
+ }, args.protectedKeysSnapshotSet, asyncQueryNamespaceScope, args.queryKey);
10294
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10542
10295
  }
10543
10296
  let storeRef = null;
10544
10297
  let unsubscribe = null;
@@ -11288,15 +11041,7 @@ function setupListQueryPersistence(config, options = {}) {
11288
11041
  };
11289
11042
  });
11290
11043
  if (invalidPayloadQueryKeys.length > 0) await Promise.all(invalidPayloadQueryKeys.map((queryKey) => removeLocalStorageQueryEntry(queryKey)));
11291
- const keptQueryKeys = keepEntriesWithinByteBudget({
11292
- entries: filteredEntries,
11293
- getKey: (entry) => entry.queryKey,
11294
- getLastAccessAt: (entry) => entry.lastAccessAt,
11295
- getSizeBytes: (entry) => entry.sizeBytes,
11296
- isPinned: (entry) => pinnedQueryKeys.has(entry.queryKey),
11297
- isProtected: (entry) => entry.offlineProtected,
11298
- maxBytes: maxQueryBytes
11299
- });
11044
+ const keptQueryKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11300
11045
  await Promise.all(filteredEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11301
11046
  for (const { queryKey } of filteredEntries) if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11302
11047
  knownPersistedQueryKeys = keptQueryKeys;
@@ -11320,15 +11065,7 @@ function setupListQueryPersistence(config, options = {}) {
11320
11065
  });
11321
11066
  }
11322
11067
  if (invalidQueryKeys.length > 0) await Promise.all(invalidQueryKeys.map((queryKey) => queryNamespace.remove(queryKey)));
11323
- const keptQueryKeys = keepEntriesWithinByteBudget({
11324
- entries: validEntries,
11325
- getKey: (entry) => entry.queryKey,
11326
- getLastAccessAt: (entry) => entry.lastAccessAt,
11327
- getSizeBytes: (entry) => entry.sizeBytes,
11328
- isPinned: (entry) => pinnedQueryKeys.has(entry.queryKey),
11329
- isProtected: (entry) => protectedQueryKeys.has(entry.queryKey),
11330
- maxBytes: maxQueryBytes
11331
- });
11068
+ const keptQueryKeys = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
11332
11069
  await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
11333
11070
  for (const entry of validEntries) {
11334
11071
  const { queryKey } = entry;
@@ -11367,15 +11104,7 @@ function setupListQueryPersistence(config, options = {}) {
11367
11104
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11368
11105
  }
11369
11106
  const persistedItemEntries = hydratedItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11370
- const keptItemKeys = keepEntriesWithinByteBudget({
11371
- entries: persistedItemEntries,
11372
- getKey: (entry) => entry.itemKey,
11373
- getLastAccessAt: (entry) => entry.lastAccessAt,
11374
- getSizeBytes: (entry) => entry.sizeBytes,
11375
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
11376
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
11377
- maxBytes: maxItemBytes
11378
- });
11107
+ const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11379
11108
  const evictedItemKeys = /* @__PURE__ */ new Set();
11380
11109
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11381
11110
  evictedItemKeys.add(itemKey);
@@ -11425,15 +11154,7 @@ function setupListQueryPersistence(config, options = {}) {
11425
11154
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11426
11155
  }
11427
11156
  const persistedItemEntries = validItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11428
- const keptItemKeys = keepEntriesWithinByteBudget({
11429
- entries: persistedItemEntries,
11430
- getKey: (entry) => entry.itemKey,
11431
- getLastAccessAt: (entry) => entry.lastAccessAt,
11432
- getSizeBytes: (entry) => entry.sizeBytes,
11433
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
11434
- isProtected: (entry) => protectedItemKeys.has(entry.itemKey),
11435
- maxBytes: maxItemBytes
11436
- });
11157
+ const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11437
11158
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => itemNamespace.remove(itemKey)));
11438
11159
  for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11439
11160
  knownPersistedItemKeys = keptItemKeys;
@@ -11603,7 +11324,7 @@ function setupListQueryPersistence(config, options = {}) {
11603
11324
  if (localStorageAdapter !== null) {
11604
11325
  const nextKnownPersistedItemBytes = getKnownPersistedItemBytes(knownPersistedItemKeys);
11605
11326
  const nextKnownPersistedQueryBytes = getKnownPersistedQueryBytes(knownPersistedQueryKeys);
11606
- if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance({ forceManifestKeys: [maintenanceCallbackKey] });
11327
+ if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance([maintenanceCallbackKey]);
11607
11328
  return;
11608
11329
  }
11609
11330
  const sessionKey = config.getSessionKey();
@@ -11697,15 +11418,7 @@ function setupListQueryPersistence(config, options = {}) {
11697
11418
  sizeBytes
11698
11419
  });
11699
11420
  }
11700
- const keptQueryKeys = keepEntriesWithinByteBudget({
11701
- entries: candidateEntries,
11702
- getKey: (entry) => entry.queryKey,
11703
- getLastAccessAt: (entry) => entry.lastAccessAt,
11704
- getSizeBytes: (entry) => entry.sizeBytes,
11705
- isPinned: (entry) => pinnedQueryKeys.has(entry.queryKey),
11706
- isProtected: (entry) => entry.offlineProtected,
11707
- maxBytes: maxQueryBytes
11708
- });
11421
+ const keptQueryKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11709
11422
  finalPersistedQueryKeys.clear();
11710
11423
  for (const queryKey of keptQueryKeys) finalPersistedQueryKeys.add(queryKey);
11711
11424
  const evictedQueryKeys = [];
@@ -11797,15 +11510,7 @@ function setupListQueryPersistence(config, options = {}) {
11797
11510
  sizeBytes
11798
11511
  });
11799
11512
  }
11800
- const keptItemKeys = keepEntriesWithinByteBudget({
11801
- entries: itemCandidateEntries,
11802
- getKey: (entry) => entry.itemKey,
11803
- getLastAccessAt: (entry) => entry.lastAccessAt,
11804
- getSizeBytes: (entry) => entry.sizeBytes,
11805
- isPinned: (entry) => pinnedItemKeys.has(entry.itemKey),
11806
- isProtected: (entry) => entry.offlineProtected,
11807
- maxBytes: maxItemBytes
11808
- });
11513
+ const keptItemKeys = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11809
11514
  finalPersistedItemKeys.clear();
11810
11515
  for (const itemKey of keptItemKeys) finalPersistedItemKeys.add(itemKey);
11811
11516
  const evictedItemKeys = [];
@@ -11994,10 +11699,7 @@ function excludeLoadedFields(loadedFields, requestedFields) {
11994
11699
  function applyPartialItemMerge(draft, itemKey, data, fields, partialResources) {
11995
11700
  const prev = draft.items[itemKey] ?? void 0;
11996
11701
  const merged = partialResources.mergeItems(prev, data);
11997
- draft.items[itemKey] = reusePrevIfEqual({
11998
- current: merged,
11999
- prev
12000
- });
11702
+ draft.items[itemKey] = reusePrevIfEqual(prev, merged);
12001
11703
  if (fields && fields.length > 0) {
12002
11704
  const existingFields = draft.itemLoadedFields[itemKey] ?? [];
12003
11705
  const fieldSet = new Set([...existingFields, ...fields]);
@@ -12011,10 +11713,7 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12011
11713
  const results = /* @__PURE__ */ new Map();
12012
11714
  function applyItemResult(draft, itemKey, data, fields) {
12013
11715
  if (partialResources) applyPartialItemMerge(draft, itemKey, data, fields, partialResources);
12014
- else draft.items[itemKey] = reusePrevIfEqual({
12015
- current: data,
12016
- prev: draft.items[itemKey] ?? void 0
12017
- });
11716
+ else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12018
11717
  }
12019
11718
  function clearSatisfiedItemInvalidationFields(draft, itemKey, requestFields) {
12020
11719
  const invalidationFields = draft.itemFieldInvalidationFields[itemKey];
@@ -12057,13 +11756,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12057
11756
  payload: r.payload.payload,
12058
11757
  fields: r.payload.fields
12059
11758
  }));
12060
- const fetchResult = await runOfflineAwareFetch({
12061
- controller: offlineController,
12062
- fetcher: () => batchFetchItemFn(batchRequests, {
12063
- signal: fetchCtx.signal,
12064
- batchKey: batchKey ?? "__default__"
12065
- })
12066
- });
11759
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchItemFn(batchRequests, {
11760
+ signal: fetchCtx.signal,
11761
+ batchKey: batchKey ?? "__default__"
11762
+ }));
12067
11763
  if (!fetchResult.ok) {
12068
11764
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
12069
11765
  store.produceState((draft) => {
@@ -12139,13 +11835,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12139
11835
  }
12140
11836
  const fetchPromises = requests.map(async ({ requestId: itemKey, payload: requestData }) => {
12141
11837
  try {
12142
- const fetchResult = await runOfflineAwareFetch({
12143
- controller: offlineController,
12144
- fetcher: () => fetchItemFn(klona(requestData.payload), {
12145
- signal: fetchCtx.signal,
12146
- fields: requestData.fields
12147
- })
12148
- });
11838
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchItemFn(klona(requestData.payload), {
11839
+ signal: fetchCtx.signal,
11840
+ fields: requestData.fields
11841
+ }));
12149
11842
  if (!fetchResult.ok) {
12150
11843
  if (fetchCtx.shouldAbort()) {
12151
11844
  results.set(itemKey, false);
@@ -12221,10 +11914,7 @@ function applyFetchedItems(draft, queryKey, items, hasMore, fields, getItemKey,
12221
11914
  if (remainingFields.length > 0) draft.itemFieldInvalidationFields[itemKey] = remainingFields;
12222
11915
  else delete draft.itemFieldInvalidationFields[itemKey];
12223
11916
  }
12224
- } else draft.items[itemKey] = reusePrevIfEqual({
12225
- current: data,
12226
- prev: draft.items[itemKey] ?? void 0
12227
- });
11917
+ } else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12228
11918
  if (!existingItemKeys.has(itemKey)) {
12229
11919
  query.items.push(itemKey);
12230
11920
  existingItemKeys.add(itemKey);
@@ -12286,13 +11976,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12286
11976
  stopOnError: true,
12287
11977
  rejectPendingOnError: true
12288
11978
  });
12289
- const chunkResultPromises = chunks.map((chunk) => queue.resultifyAdd(() => runOfflineAwareFetch({
12290
- controller: offlineController,
12291
- fetcher: () => normalizedFetchListFn(payload, chunk.offset, chunk.limit, {
12292
- signal: fetchCtx.signal,
12293
- fields
12294
- })
12295
- }).then((result) => {
11979
+ const chunkResultPromises = chunks.map((chunk) => queue.resultifyAdd(() => runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, chunk.offset, chunk.limit, {
11980
+ signal: fetchCtx.signal,
11981
+ fields
11982
+ })).then((result) => {
12296
11983
  if (!result.ok) throw result.offline ? offlineConnectivityError : result.error;
12297
11984
  return result.data;
12298
11985
  })));
@@ -12301,13 +11988,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12301
11988
  const lastChunk = successResults[successResults.length - 1];
12302
11989
  hasMore = lastChunk ? lastChunk.hasMore : false;
12303
11990
  } else {
12304
- const fetchResult = await runOfflineAwareFetch({
12305
- controller: offlineController,
12306
- fetcher: () => normalizedFetchListFn(payload, offset, limit, {
12307
- signal: fetchCtx.signal,
12308
- fields
12309
- })
12310
- });
11991
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, offset, limit, {
11992
+ signal: fetchCtx.signal,
11993
+ fields
11994
+ }));
12311
11995
  if (!fetchResult.ok) throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
12312
11996
  const result = fetchResult.data;
12313
11997
  allItems = result.items;
@@ -12349,7 +12033,7 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12349
12033
  //#endregion
12350
12034
  //#region src/listQueryStore/createFetchApi.ts
12351
12035
  /** @internal */
12352
- function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, dynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, syncHydrationEnabled = false, preloadQueries: preloadQueries_, preloadItems: preloadItems_, persistence, testInitialLastFetchStartTime, onQueryFetchStart, onQueryFetchSettled, onItemFetchStart, onItemFetchSettled, offlineController }) {
12036
+ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, dynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, syncHydrationEnabled, preloadQueries_, preloadItems_, persistence, testInitialLastFetchStartTime, onQueryFetchStart, onQueryFetchSettled, onItemFetchStart, onItemFetchSettled, offlineController) {
12353
12037
  const noFetchItemFnError = "No fetchItemFn was provided";
12354
12038
  const querySchedulers = /* @__PURE__ */ new Map();
12355
12039
  const queryInitialFetchStartTime = /* @__PURE__ */ new Map();
@@ -13066,7 +12750,7 @@ const GET_ALL = () => true;
13066
12750
  //#endregion
13067
12751
  //#region src/listQueryStore/createMutationApi.ts
13068
12752
  /** @internal */
13069
- 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 }) {
12753
+ 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) {
13070
12754
  const storeEvents = evtmitter();
13071
12755
  const deferredOptimisticQueryInvalidationsStack = [];
13072
12756
  const optimisticMutationQueryContextStack = [];
@@ -13466,55 +13150,42 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13466
13150
  items: affectedItems
13467
13151
  });
13468
13152
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
13469
- const result = await performMutationWithLifecycle({
13470
- startMutation: () => {
13471
- const endBaseMutations = startItemMutation(payloadToUse);
13472
- return () => {
13473
- endBaseMutations();
13474
- for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
13475
- };
13476
- },
13477
- optimisticUpdate: optimisticUpdate ? () => {
13478
- deferredOptimisticQueryInvalidationsStack.push(deferredOptimisticQueryInvalidations);
13479
- optimisticMutationQueryContextStack.push(optimisticMutationQueryContext);
13480
- try {
13481
- return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse));
13482
- } finally {
13483
- optimisticMutationQueryContextStack.pop();
13484
- deferredOptimisticQueryInvalidationsStack.pop();
13485
- }
13486
- } : void 0,
13487
- debounce,
13488
- blockWindowClose: blockWindowClose ?? void 0,
13489
- mutation: offline ? () => runHybridOfflineMutation({
13490
- controller: offlineController,
13491
- offline,
13492
- upload,
13493
- directMutation
13494
- }) : async () => ({
13495
- kind: "online",
13496
- data: await directMutation()
13497
- }),
13498
- onSuccess: (result) => {
13499
- const successInvalidationQueryPayloads = result.kind === "online" ? getSuccessInvalidationQueryPayloads(deferredOptimisticQueryInvalidations, normalizedRevalidateOnSuccess.queryFilter, normalizedRevalidateOnSuccess.shouldRevalidate) : [];
13500
- if (result.kind === "online" && (normalizedRevalidateOnSuccess.shouldRevalidate || successInvalidationQueryPayloads.length > 0)) invalidateQueryAndItems({
13501
- itemPayload: !normalizedRevalidateOnSuccess.includeItems || affectedItems.length === 0 ? false : payloadToUse,
13502
- queryPayload: successInvalidationQueryPayloads.length > 0 ? successInvalidationQueryPayloads : false
13503
- });
13504
- if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
13505
- },
13506
- onError: (exception) => {
13507
- const error = toStoreMutationError(exception, errorNormalizer);
13508
- const queryRollbackSnapshots = [...optimisticMutationQueryContext.queryRollbackSnapshots.values()];
13509
- if (itemRollbackSnapshots.length > 0 || queryRollbackSnapshots.length) restoreMutationRollbackState({
13510
- itemSnapshots: itemRollbackSnapshots,
13511
- querySnapshots: queryRollbackSnapshots
13512
- });
13513
- if (onMutationError) onMutationError(exception, { silentErrors });
13514
- if (onError) onError(error);
13515
- return error;
13516
- }
13517
- });
13153
+ const result = await performMutationWithLifecycle(() => {
13154
+ const endBaseMutations = startItemMutation(payloadToUse);
13155
+ return () => {
13156
+ endBaseMutations();
13157
+ for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
13158
+ };
13159
+ }, offline ? () => runHybridOfflineMutation(offlineController, offline, upload, directMutation) : async () => ({
13160
+ kind: "online",
13161
+ data: await directMutation()
13162
+ }), (exception) => {
13163
+ const error = toStoreMutationError(exception, errorNormalizer);
13164
+ const queryRollbackSnapshots = [...optimisticMutationQueryContext.queryRollbackSnapshots.values()];
13165
+ if (itemRollbackSnapshots.length > 0 || queryRollbackSnapshots.length) restoreMutationRollbackState({
13166
+ itemSnapshots: itemRollbackSnapshots,
13167
+ querySnapshots: queryRollbackSnapshots
13168
+ });
13169
+ if (onMutationError) onMutationError(exception, { silentErrors });
13170
+ if (onError) onError(error);
13171
+ return error;
13172
+ }, optimisticUpdate ? () => {
13173
+ deferredOptimisticQueryInvalidationsStack.push(deferredOptimisticQueryInvalidations);
13174
+ optimisticMutationQueryContextStack.push(optimisticMutationQueryContext);
13175
+ try {
13176
+ return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse));
13177
+ } finally {
13178
+ optimisticMutationQueryContextStack.pop();
13179
+ deferredOptimisticQueryInvalidationsStack.pop();
13180
+ }
13181
+ } : void 0, (result) => {
13182
+ const successInvalidationQueryPayloads = result.kind === "online" ? getSuccessInvalidationQueryPayloads(deferredOptimisticQueryInvalidations, normalizedRevalidateOnSuccess.queryFilter, normalizedRevalidateOnSuccess.shouldRevalidate) : [];
13183
+ if (result.kind === "online" && (normalizedRevalidateOnSuccess.shouldRevalidate || successInvalidationQueryPayloads.length > 0)) invalidateQueryAndItems({
13184
+ itemPayload: !normalizedRevalidateOnSuccess.includeItems || affectedItems.length === 0 ? false : payloadToUse,
13185
+ queryPayload: successInvalidationQueryPayloads.length > 0 ? successInvalidationQueryPayloads : false
13186
+ });
13187
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
13188
+ }, debounce, blockWindowClose ?? void 0);
13518
13189
  storeEvents.emit("mutationEnd", {
13519
13190
  mutationId,
13520
13191
  items: affectedItems,
@@ -13542,7 +13213,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13542
13213
  //#endregion
13543
13214
  //#region src/listQueryStore/listQueryCacheLimits.ts
13544
13215
  /** @internal */
13545
- function createListQueryCacheLimits({ store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup }) {
13216
+ function createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup) {
13546
13217
  let isEnforcingCacheLimits = false;
13547
13218
  function getReferencedItemKeysFromQueries(queryKeys = Object.keys(store.state.queries)) {
13548
13219
  const referencedItemKeys = /* @__PURE__ */ new Set();
@@ -14198,15 +13869,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14198
13869
  }
14199
13870
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemKey)) continue;
14200
13871
  ignoreItemsInRefetchOnMount.add(itemKey);
14201
- if (shouldScheduleAutomaticFetch({
14202
- wasLoaded: itemState?.wasLoaded,
14203
- shouldFetch,
14204
- requiredFetch,
14205
- disableRefetches,
14206
- disableRefetchOnMount,
14207
- refetchOnMount: itemState?.refetchOnMount ?? false,
14208
- skipFreshFetch: !!partialResources
14209
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, itemState?.status)) scheduleAutomaticItemFetch(fetchType, payload, { fields: fieldsToFetch });
13872
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, itemState?.status)) scheduleAutomaticItemFetch(fetchType, payload, { fields: fieldsToFetch });
14210
13873
  }
14211
13874
  for (const itemKey of removedItems) ignoreItemsInRefetchOnMount.delete(itemKey);
14212
13875
  })();
@@ -14754,15 +14417,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14754
14417
  }
14755
14418
  if (!shouldFetch && ignoreQueriesInRefetchOnMount.has(queryId)) continue;
14756
14419
  ignoreQueriesInRefetchOnMount.add(queryId);
14757
- if (shouldScheduleAutomaticFetch({
14758
- wasLoaded: effectiveQueryState?.wasLoaded,
14759
- shouldFetch,
14760
- requiredFetch,
14761
- disableRefetches,
14762
- disableRefetchOnMount,
14763
- refetchOnMount: queryState?.refetchOnMount ?? false,
14764
- skipFreshFetch: !!partialResources
14765
- }) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
14420
+ if (shouldScheduleAutomaticFetch(effectiveQueryState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
14766
14421
  stickyDerivedQueryKeys.delete(queryId);
14767
14422
  scheduleAutomaticListQueryFetch(fetchType, payload, loadSize, { fields: fieldsToFetch });
14768
14423
  }
@@ -14950,18 +14605,9 @@ function createListQueryStore(storeOptions) {
14950
14605
  if (fields === "*") return void 0;
14951
14606
  return fields;
14952
14607
  }
14953
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
14954
- storeManager,
14955
- storeName: id,
14956
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
14957
- });
14608
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
14958
14609
  const getSessionKeyBase = storeManager.getSessionKey;
14959
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
14960
- storeManager,
14961
- storeName: id,
14962
- offlineSession: resolvedOfflineSession,
14963
- getSessionKey: getSessionKeyBase
14964
- });
14610
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
14965
14611
  const errorNormalizer = storeManager.errorNormalizer;
14966
14612
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
14967
14613
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -15081,11 +14727,20 @@ function createListQueryStore(storeOptions) {
15081
14727
  lastFetchDuration,
15082
14728
  windowIsNotFocused: !getWindowIsFocused()
15083
14729
  });
14730
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
14731
+ getWindowIsFocused,
14732
+ onWindowFocusChange: testOptions?.onWindowFocusChange,
14733
+ transportFactory: testOptions?.browserTabsTransportFactory,
14734
+ priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
14735
+ });
15084
14736
  function getCoalescingWindowMs() {
15085
- return browserTabsPriority?.getCoalescingWindowMs(baseCoalescingWindowMs) ?? baseCoalescingWindowMs;
14737
+ return browserTabsPriority.getCoalescingWindowMs(baseCoalescingWindowMs);
15086
14738
  }
15087
- let browserTabsSync = null;
15088
- let browserTabsPriority = null;
14739
+ const browserTabsSync = createBrowserTabsCoordinator("listQuery", id, getSessionKeyForRuntime, handleRemoteBrowserTabsMessage, () => {
14740
+ lastQuerySyncVersions.clear();
14741
+ lastItemSyncVersions.clear();
14742
+ clearOfflineOverlays();
14743
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
15089
14744
  function getQueryTargetKey(queryKey) {
15090
14745
  return `query:${queryKey}`;
15091
14746
  }
@@ -15119,7 +14774,7 @@ function createListQueryStore(storeOptions) {
15119
14774
  const query = store.state.queries[queryKey];
15120
14775
  if (!query) return;
15121
14776
  const items = getQuerySnapshotItems(query);
15122
- const message = browserTabsSync?.publish({
14777
+ const message = browserTabsSync.publish({
15123
14778
  kind: "list-query-snapshot",
15124
14779
  queryKey,
15125
14780
  consistency,
@@ -15132,7 +14787,7 @@ function createListQueryStore(storeOptions) {
15132
14787
  }
15133
14788
  function publishItemSnapshot(itemKey, consistency = currentBroadcastConsistency) {
15134
14789
  if (remoteApplyDepth > 0) return;
15135
- const message = browserTabsSync?.publish({
14790
+ const message = browserTabsSync.publish({
15136
14791
  kind: "list-item-snapshot",
15137
14792
  itemKey,
15138
14793
  consistency,
@@ -15194,212 +14849,142 @@ function createListQueryStore(storeOptions) {
15194
14849
  preloaded: results[index] ?? false
15195
14850
  }));
15196
14851
  }
15197
- const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers } = createFetchApi({
15198
- store,
15199
- normalizedFetchListFn,
15200
- offsetPagination,
15201
- fetchItemFn,
15202
- batchFetchItemFn,
15203
- getItemsBatchKey,
15204
- errorNormalizer,
15205
- partialResources,
15206
- lowPriorityThrottleMs,
15207
- getCoalescingWindowMs,
15208
- mediumPriorityDelayMs,
15209
- dynamicRealtimeThrottleMs: wrappedDynamicRealtimeThrottleMs,
15210
- onSchedulerEvent,
15211
- usesRealTimeUpdates,
15212
- defaultQuerySize,
15213
- maxItemBatchSize,
15214
- getQueryKey,
15215
- getItemKey,
15216
- normalizeFieldsOption,
15217
- syncHydrationEnabled: !!persistence && !persistence.hasAsyncPreload,
15218
- preloadQueries: persistence ? (queryKeys) => persistence.preloadQueries(queryKeys) : void 0,
15219
- preloadItems: persistence ? (itemKeys) => persistence.preloadItems(itemKeys) : void 0,
15220
- persistence,
15221
- testInitialLastFetchStartTime: testOptions?.initialLastFetchStartTime,
15222
- offlineController: offlineFetchController,
15223
- onQueryFetchStart: (requests, startedAt) => {
15224
- const queryKey = requests[0]?.requestId;
15225
- if (!queryKey) return;
15226
- browserTabsSync?.publish({
15227
- kind: "fetch-start",
15228
- targetKey: getQueryTargetKey(queryKey),
15229
- requestIds: requests.map(({ requestId }) => requestId),
15230
- startedAt
14852
+ const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers } = createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, wrappedDynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, !!persistence && !persistence.hasAsyncPreload, persistence ? (queryKeys) => persistence.preloadQueries(queryKeys) : void 0, persistence ? (itemKeys) => persistence.preloadItems(itemKeys) : void 0, persistence, testOptions?.initialLastFetchStartTime, (requests, startedAt) => {
14853
+ const queryKey = requests[0]?.requestId;
14854
+ if (!queryKey) return;
14855
+ browserTabsSync.publish({
14856
+ kind: "fetch-start",
14857
+ targetKey: getQueryTargetKey(queryKey),
14858
+ requestIds: requests.map(({ requestId }) => requestId),
14859
+ startedAt
14860
+ });
14861
+ }, ({ requests, results, startedAt, duration }) => {
14862
+ pruneItemInvalidationTracking();
14863
+ const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
14864
+ if (successfulQueryKeys.length > 0) {
14865
+ touchQueries(successfulQueryKeys);
14866
+ touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
14867
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
14868
+ }
14869
+ const firstQueryKey = successfulQueryKeys[0];
14870
+ if (firstQueryKey) {
14871
+ browserTabsSync.publish({
14872
+ kind: "fetch-success",
14873
+ targetKey: getQueryTargetKey(firstQueryKey),
14874
+ requestIds: successfulQueryKeys,
14875
+ startedAt,
14876
+ duration
15231
14877
  });
15232
- },
15233
- onItemFetchStart: (requests, startedAt) => {
15234
- const firstRequest = requests[0];
15235
- if (!firstRequest) return;
15236
- const payload = firstRequest.payload.payload;
15237
- const batchKey = getItemBatchKey(payload);
15238
- const targetKey = batchKey === false ? getItemTargetKey(firstRequest.requestId) : getItemBatchTargetKey(batchKey);
15239
- browserTabsSync?.publish({
15240
- kind: "fetch-start",
14878
+ for (const queryKey of successfulQueryKeys) publishQuerySnapshot(queryKey, "confirmed");
14879
+ }
14880
+ }, (requests, startedAt) => {
14881
+ const firstRequest = requests[0];
14882
+ if (!firstRequest) return;
14883
+ const payload = firstRequest.payload.payload;
14884
+ const batchKey = getItemBatchKey(payload);
14885
+ const targetKey = batchKey === false ? getItemTargetKey(firstRequest.requestId) : getItemBatchTargetKey(batchKey);
14886
+ browserTabsSync.publish({
14887
+ kind: "fetch-start",
14888
+ targetKey,
14889
+ requestIds: requests.map(({ requestId }) => requestId),
14890
+ startedAt
14891
+ });
14892
+ }, ({ requests, results, startedAt, duration }) => {
14893
+ pruneItemInvalidationTracking();
14894
+ const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
14895
+ if (successfulItems.length > 0) {
14896
+ touchItems(successfulItems.map(({ itemKey }) => itemKey));
14897
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
14898
+ }
14899
+ const firstSuccessfulItem = successfulItems[0];
14900
+ if (firstSuccessfulItem) {
14901
+ const payload = requests[0]?.payload.payload;
14902
+ const batchKey = payload ? getItemBatchKey(payload) : false;
14903
+ const targetKey = batchKey === false ? getItemTargetKey(firstSuccessfulItem.itemKey) : getItemBatchTargetKey(batchKey);
14904
+ browserTabsSync.publish({
14905
+ kind: "fetch-success",
15241
14906
  targetKey,
15242
- requestIds: requests.map(({ requestId }) => requestId),
15243
- startedAt
14907
+ requestIds: successfulItems.map(({ itemKey }) => itemKey),
14908
+ startedAt,
14909
+ duration
15244
14910
  });
14911
+ for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
14912
+ }
14913
+ }, offlineFetchController);
14914
+ const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, invalidateQueryAndItems, invalidateItem, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, resolvedOnMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, (event) => {
14915
+ events.emit("invalidateQuery", event);
14916
+ }, (event) => {
14917
+ events.emit("invalidateItem", event);
14918
+ }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0);
14919
+ if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
14920
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
14921
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
14922
+ if (normalizedRef !== null) return normalizedRef;
14923
+ return {
14924
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
14925
+ entityKind: "item"
14926
+ };
14927
+ }),
14928
+ getProtectedCacheKeys: (entityRefs) => {
14929
+ const sessionKey = getSessionKeyForRuntime();
14930
+ if (sessionKey === false) return [];
14931
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "listQuery.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
15245
14932
  },
15246
- onQueryFetchSettled: ({ requests, results, startedAt, duration }) => {
15247
- pruneItemInvalidationTracking();
15248
- const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
15249
- if (successfulQueryKeys.length > 0) {
15250
- touchQueries(successfulQueryKeys);
15251
- touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
15252
- if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15253
- }
15254
- const firstQueryKey = successfulQueryKeys[0];
15255
- if (firstQueryKey) {
15256
- browserTabsSync?.publish({
15257
- kind: "fetch-success",
15258
- targetKey: getQueryTargetKey(firstQueryKey),
15259
- requestIds: successfulQueryKeys,
15260
- startedAt,
15261
- duration
15262
- });
15263
- for (const queryKey of successfulQueryKeys) publishQuerySnapshot(queryKey, "confirmed");
15264
- }
14933
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
14934
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
14935
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
15265
14936
  },
15266
- onItemFetchSettled: ({ requests, results, startedAt, duration }) => {
15267
- pruneItemInvalidationTracking();
15268
- const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
15269
- if (successfulItems.length > 0) {
15270
- touchItems(successfulItems.map(({ itemKey }) => itemKey));
15271
- if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15272
- }
15273
- const firstSuccessfulItem = successfulItems[0];
15274
- if (firstSuccessfulItem) {
15275
- const payload = requests[0]?.payload.payload;
15276
- const batchKey = payload ? getItemBatchKey(payload) : false;
15277
- const targetKey = batchKey === false ? getItemTargetKey(firstSuccessfulItem.itemKey) : getItemBatchTargetKey(batchKey);
15278
- browserTabsSync?.publish({
15279
- kind: "fetch-success",
15280
- targetKey,
15281
- requestIds: successfulItems.map(({ itemKey }) => itemKey),
15282
- startedAt,
15283
- duration
15284
- });
15285
- for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
15286
- }
15287
- }
15288
- });
15289
- const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, invalidateQueryAndItems, invalidateItem, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi({
15290
- store,
15291
- fetchItemFn,
15292
- partialResources,
15293
- optimisticListUpdates,
15294
- onInvalidateQuery,
15295
- onInvalidateItem,
15296
- onMutationError: resolvedOnMutationError,
15297
- errorNormalizer,
15298
- getItemKey,
15299
- getQueriesKeyArray,
15300
- getQueriesRelatedToItem,
15301
- getItemsKeyArray,
15302
- getOrCreateItemScheduler,
15303
- getOrCreateQueryScheduler,
15304
- deleteItemFetchResources,
15305
- emitInvalidateQuery: (event) => {
15306
- events.emit("invalidateQuery", event);
14937
+ rollbackPendingEntity: ({ tempId }) => {
14938
+ deleteItemState(__LEGIT_CAST__(tempId));
15307
14939
  },
15308
- emitInvalidateItem: (event) => {
15309
- events.emit("invalidateItem", event);
14940
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
14941
+ const tempPayload = __LEGIT_CAST__(tempId);
14942
+ const tempItemKey = getItemKey(tempPayload);
14943
+ const currentItem = getItemState(tempPayload);
14944
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
14945
+ if (finalData === void 0) return;
14946
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
14947
+ const finalItemKey = getItemKey(finalPayload);
14948
+ const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
14949
+ queryKey,
14950
+ index: query.items.indexOf(tempItemKey)
14951
+ })).filter(({ index }) => index !== -1);
14952
+ deleteItemState(tempPayload);
14953
+ addItemToState(finalPayload, finalData);
14954
+ storeEvents.emit("tempEntityReconciled", {
14955
+ tempId: tempPayload,
14956
+ finalPayload
14957
+ });
14958
+ if (queryMemberships.length === 0) return;
14959
+ store.produceState((draft) => {
14960
+ for (const { queryKey, index } of queryMemberships) {
14961
+ const query = notNullish(draft.queries[queryKey]);
14962
+ const existingIndex = query.items.indexOf(finalItemKey);
14963
+ if (existingIndex !== -1) query.items.splice(existingIndex, 1);
14964
+ query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
14965
+ }
14966
+ }, { action: "offline-reconcile-temp-item" });
14967
+ touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
14968
+ for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
15310
14969
  },
15311
- blockWindowClose,
15312
- offlineController: resolvedOfflineConfig ? offlineMutationController : null,
15313
- runWithBroadcastConsistency,
15314
- publishQuerySnapshot,
15315
- publishItemSnapshot,
15316
- onOfflineTimelineEvent: void 0
15317
- });
15318
- if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController({
15319
- storeName: id,
15320
- storeType: "listQuery",
15321
- getSessionKey: getSessionKeyForRuntime,
15322
- onPersistentStorageError: resolvedPersistentStorageConfig.onPersistentStorageError,
15323
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
15324
- adapter: resolvedPersistentStorageConfig.adapter,
15325
- offlineSession: resolvedOfflineConfig.session,
15326
- operations: __LEGIT_CAST__(offlineOperationsForRuntime),
15327
- storeAdapter: {
15328
- normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
15329
- const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
15330
- if (normalizedRef !== null) return normalizedRef;
15331
- return {
15332
- entityKey: getItemKey(__LEGIT_CAST__(ref)),
15333
- entityKind: "item"
15334
- };
15335
- }),
15336
- getProtectedCacheKeys: (entityRefs) => {
15337
- const sessionKey = getSessionKeyForRuntime();
15338
- if (sessionKey === false) return [];
15339
- return entityRefs.map((ref) => createProtectedStorageKey({
15340
- backend: resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage",
15341
- sessionKey,
15342
- storeName: id,
15343
- kind: "listQuery.item",
15344
- key: ref.entityKey
15345
- }));
15346
- },
15347
- applyPendingEntity: ({ tempId, pendingEntity }) => {
15348
- if (!pendingEntity || typeof pendingEntity !== "object") return;
15349
- addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
15350
- },
15351
- rollbackPendingEntity: ({ tempId }) => {
15352
- deleteItemState(__LEGIT_CAST__(tempId));
15353
- },
15354
- reconcileTempEntity: ({ tempId, reconciliation }) => {
15355
- const tempPayload = __LEGIT_CAST__(tempId);
15356
- const tempItemKey = getItemKey(tempPayload);
15357
- const currentItem = getItemState(tempPayload);
15358
- const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
15359
- if (finalData === void 0) return;
15360
- const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
15361
- const finalItemKey = getItemKey(finalPayload);
15362
- const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
15363
- queryKey,
15364
- index: query.items.indexOf(tempItemKey)
15365
- })).filter(({ index }) => index !== -1);
15366
- deleteItemState(tempPayload);
15367
- addItemToState(finalPayload, finalData);
15368
- storeEvents.emit("tempEntityReconciled", {
15369
- tempId: tempPayload,
15370
- finalPayload
15371
- });
15372
- if (queryMemberships.length === 0) return;
15373
- store.produceState((draft) => {
15374
- for (const { queryKey, index } of queryMemberships) {
15375
- const query = notNullish(draft.queries[queryKey]);
15376
- const existingIndex = query.items.indexOf(finalItemKey);
15377
- if (existingIndex !== -1) query.items.splice(existingIndex, 1);
15378
- query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
15379
- }
15380
- }, { action: "offline-reconcile-temp-item" });
15381
- touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
15382
- for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
15383
- },
15384
- captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
15385
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15386
- captureOfflineOverlays(entityRefs.flatMap((ref) => {
15387
- return ref.entityKind === "item" ? [ref.entityKey] : [];
15388
- }));
15389
- },
15390
- rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
15391
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15392
- rebindOfflineOverlays(itemKeyRewrites);
15393
- },
15394
- syncEntityOverlays: ({ entities, sessionKey }) => {
15395
- if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15396
- const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
15397
- offlineOverlayStore.produceState((draft) => {
15398
- for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
15399
- });
15400
- }
14970
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
14971
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
14972
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
14973
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
14974
+ }));
14975
+ },
14976
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
14977
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
14978
+ rebindOfflineOverlays(itemKeyRewrites);
14979
+ },
14980
+ syncEntityOverlays: ({ entities, sessionKey }) => {
14981
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
14982
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
14983
+ offlineOverlayStore.produceState((draft) => {
14984
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
14985
+ });
15401
14986
  }
15402
- });
14987
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime));
15403
14988
  function applyLoadedFieldsFromSnapshot(draft, itemKey, loadedFields) {
15404
14989
  if (loadedFields.length > 0) {
15405
14990
  const existingLoadedFields = draft.itemLoadedFields[itemKey] ?? [];
@@ -15438,16 +15023,12 @@ function createListQueryStore(storeOptions) {
15438
15023
  offlineOverlayStore.setState({});
15439
15024
  }
15440
15025
  function rebindOfflineOverlays(itemKeyRewrites) {
15441
- rebindOfflineOverlayEntries({
15442
- itemKeyRewrites,
15443
- overlayStore: offlineOverlayStore,
15444
- createReboundOverlay: ({ existingOverlay, nextItemKey }) => ({
15445
- item: existingOverlay.item ?? null,
15446
- itemPayload: store.state.itemQueries[nextItemKey]?.payload ?? existingOverlay.itemPayload,
15447
- queryMemberships: existingOverlay.queryMemberships,
15448
- keepVisibleWhileResolutionRequired: true
15449
- })
15450
- });
15026
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
15027
+ item: existingOverlay.item ?? null,
15028
+ itemPayload: store.state.itemQueries[nextItemKey]?.payload ?? existingOverlay.itemPayload,
15029
+ queryMemberships: existingOverlay.queryMemberships,
15030
+ keepVisibleWhileResolutionRequired: true
15031
+ }));
15451
15032
  }
15452
15033
  function captureOfflineOverlays(itemKeys) {
15453
15034
  const targetItemKeySet = new Set(itemKeys);
@@ -15460,18 +15041,14 @@ function createListQueryStore(storeOptions) {
15460
15041
  if (!queryMemberships) continue;
15461
15042
  queryMemberships[queryKey] = index;
15462
15043
  }
15463
- captureOfflineOverlayEntries({
15464
- itemKeys: [...targetItemKeySet],
15465
- overlayStore: offlineOverlayStore,
15466
- createOverlay: (itemKey) => {
15467
- const item = store.state.items[itemKey];
15468
- const itemPayload = store.state.itemQueries[itemKey]?.payload;
15469
- return {
15470
- item: item == null ? null : klona(item),
15471
- itemPayload: itemPayload === void 0 ? void 0 : klona(itemPayload),
15472
- queryMemberships: queryMembershipsByItemKey.get(itemKey) ?? {}
15473
- };
15474
- }
15044
+ captureOfflineOverlayEntries(offlineOverlayStore, [...targetItemKeySet], (itemKey) => {
15045
+ const item = store.state.items[itemKey];
15046
+ const itemPayload = store.state.itemQueries[itemKey]?.payload;
15047
+ return {
15048
+ item: item == null ? null : klona(item),
15049
+ itemPayload: itemPayload === void 0 ? void 0 : klona(itemPayload),
15050
+ queryMemberships: queryMembershipsByItemKey.get(itemKey) ?? {}
15051
+ };
15475
15052
  });
15476
15053
  }
15477
15054
  function isQueryProtectedFromEviction(queryKey, query) {
@@ -15586,10 +15163,6 @@ function createListQueryStore(storeOptions) {
15586
15163
  return false;
15587
15164
  }
15588
15165
  function handleRemoteBrowserTabsMessage(message) {
15589
- if (message.kind === "tab-status") {
15590
- browserTabsPriority?.onTabStatusMessage(message.tabId, message);
15591
- return;
15592
- }
15593
15166
  if (message.kind === "fetch-start") {
15594
15167
  syncRemoteFetchStart(message.targetKey, message.requestIds, message.startedAt);
15595
15168
  return;
@@ -15631,22 +15204,6 @@ function createListQueryStore(storeOptions) {
15631
15204
  }
15632
15205
  applyRemoteQuerySnapshot(message);
15633
15206
  }
15634
- ({coordinator: browserTabsSync, priority: browserTabsPriority} = createBrowserTabsCoordinatorWithPriority({
15635
- storeType: "listQuery",
15636
- storeKey: id,
15637
- getSessionKey: getSessionKeyForRuntime,
15638
- onMessage: handleRemoteBrowserTabsMessage,
15639
- onSessionChange() {
15640
- lastQuerySyncVersions.clear();
15641
- lastItemSyncVersions.clear();
15642
- clearOfflineOverlays();
15643
- },
15644
- transportFactory: testOptions?.browserTabsTransportFactory,
15645
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
15646
- getWindowIsFocused,
15647
- onWindowFocusChange: testOptions?.onWindowFocusChange,
15648
- priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
15649
- }));
15650
15207
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
15651
15208
  const offlineEntities = useOfflineStoreEntities({
15652
15209
  sessionKey: getSessionKeyForRuntime(),
@@ -15702,43 +15259,19 @@ function createListQueryStore(storeOptions) {
15702
15259
  function useFindItem$1(findItemFn, options = {}) {
15703
15260
  return useFindItem(findItemFn, options, store, registerActiveStandaloneItems, touchItems);
15704
15261
  }
15705
- const focusLifecycle = createStoreFocusLifecycle({
15706
- revalidateOnWindowFocus: resolvedRevalidateOnWindowFocus,
15707
- usesRealTimeUpdates,
15708
- transportReconnectCooldownMs,
15709
- getWindowIsFocused,
15710
- onWindowFocus: testOptions?.onWindowFocus ?? onWindowFocus,
15711
- onWindowFocusRevalidate: () => {
15712
- invalidateQueryAndItems({
15713
- all: true,
15714
- type: "lowPriority"
15715
- });
15716
- },
15717
- onTransportReconnectRevalidate: () => {
15718
- invalidateQueryAndItems({
15719
- all: true,
15720
- type: "realtimeUpdate"
15721
- });
15722
- }
15723
- });
15724
- const { enforceCacheLimits } = createListQueryCacheLimits({
15725
- store,
15726
- maxItems,
15727
- maxQueries,
15728
- itemCacheRuntime,
15729
- queryCacheRuntime,
15730
- isQueryProtectedFromEviction,
15731
- isStandaloneItemProtectedFromEviction,
15732
- cleanupItemStateMetadata,
15733
- cleanupQueryStateMetadata,
15734
- deleteQueryFetchResources,
15735
- deleteItemFetchResources,
15736
- onStateCleanup
15737
- });
15738
- const cacheLimitEnforcementScheduler = createIdleThrottledScheduler({
15739
- throttleMs: CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS,
15740
- run: enforceCacheLimits
15262
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
15263
+ invalidateQueryAndItems({
15264
+ all: true,
15265
+ type: "lowPriority"
15266
+ });
15267
+ }, () => {
15268
+ invalidateQueryAndItems({
15269
+ all: true,
15270
+ type: "realtimeUpdate"
15271
+ });
15741
15272
  });
15273
+ const { enforceCacheLimits } = createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup);
15274
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
15742
15275
  function scheduleCacheLimitEnforcement() {
15743
15276
  cacheLimitEnforcementScheduler.schedule();
15744
15277
  }
@@ -15778,7 +15311,6 @@ function createListQueryStore(storeOptions) {
15778
15311
  queryCacheRuntime.clearAll();
15779
15312
  itemCacheRuntime.clearAll();
15780
15313
  cacheLimitEnforcementScheduler.cancel();
15781
- browserTabsPriority?.reset();
15782
15314
  persistence?.dispose();
15783
15315
  persistence?.clear();
15784
15316
  store.setState(persistence?.createInitialState({
@@ -15810,8 +15342,7 @@ function createListQueryStore(storeOptions) {
15810
15342
  queryCacheRuntime.clearAll();
15811
15343
  itemCacheRuntime.clearAll();
15812
15344
  cacheLimitEnforcementScheduler.cancel();
15813
- browserTabsSync?.close();
15814
- browserTabsPriority?.close();
15345
+ browserTabsSync.close();
15815
15346
  focusLifecycle.dispose();
15816
15347
  persistence?.dispose();
15817
15348
  offlineController?.dispose();