tsdf 17.0.0-alpha.9 → 17.0.0-beta.2

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 offlineResolutionRecordSchema, C as OfflineResolutionConflictParseError, D as isModeEffectivelyActive, E as getIsOfflineModeFromStatus, F as warnIfNavigatorLockUnavailable, G as parsePersistedAsyncNamespaceKind, I as createCompactLocalStorageEntry, J as scheduleIdleCleanup, K as serializeProtectedRef, L as parseCompactLocalStorageEntry, M as getSessionProtectedKeysSnapshot, N as setSessionProtectedKeysSnapshot, O as isOfflineModeStatusValue, P as getNavigatorLockManager, S as serializeJsonForStorage, T as defaultOfflineRuntimeConfig, V as getPayloadRecordKey, _ as getDefaultMaxBytesForScope, a as estimateManagedAsyncStorageEntrySizeBytes, b as getSerializedStringSize, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as resolveTSDFLogger, h as getTSDFDebugTimingMs, j as clearSessionProtectedKeysSnapshot, k as offlineItemEntityRefSchema, l as registerAsyncStartupStoreCleanup, m as emitTSDFDebugLog, o as getProtectedKeysFromMetadata, p as logPersistentStorageQuotaCleanup, q as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as createShouldIgnoreItemPredicate, w as compactOfflineStatusSnapshotSchema, x as keepEntriesWithinByteBudget, y as createTimedKeySet } from "./asyncStorageAdapter-CGfnsd9m.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-DqJXzF7M.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;
@@ -866,7 +866,7 @@ const persistedCollectionItemDataSchema = rc_object({
866
866
  const persistedListQueryItemDataSchema = rc_object({
867
867
  data: rc_unknown,
868
868
  payload: rc_unknown,
869
- loadedFields: rc_array(rc_string).optional()
869
+ loadedFields: rc_union(rc_array(rc_string), rc_literals("*")).optional()
870
870
  });
871
871
  const persistedListQueryDataSchema = rc_object({
872
872
  payload: rc_unknown,
@@ -964,39 +964,6 @@ function parsePersistedListQueryData(value, payloadSchema) {
964
964
  };
965
965
  }
966
966
  //#endregion
967
- //#region src/debug.ts
968
- function defaultConsoleDebugLogger(entry) {
969
- if (import.meta.env.DEV) {
970
- const consoleForLevel = globalThis.console[entry.level];
971
- if (typeof consoleForLevel !== "function") return;
972
- const details = entry.details ? {
973
- operation: entry.operation,
974
- ...entry.details
975
- } : { operation: entry.operation };
976
- consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
977
- }
978
- }
979
- function resolveTSDFDebugLogger(debug) {
980
- if (!import.meta.env.DEV) return void 0;
981
- if (debug === void 0 || debug === false) return void 0;
982
- if (debug === true) return defaultConsoleDebugLogger;
983
- return debug;
984
- }
985
- function emitTSDFDebugLog(logger, entry) {
986
- if (import.meta.env.DEV) {
987
- if (!logger) return;
988
- try {
989
- logger(entry);
990
- } catch (error) {
991
- globalThis.console.error("[tsdf:debug] Debug logger failed", error);
992
- }
993
- }
994
- }
995
- function getTSDFDebugTimingMs() {
996
- if (!import.meta.env.DEV) return 0;
997
- return Date.now();
998
- }
999
- //#endregion
1000
967
  //#region src/persistentStorage/offlineUploadRegistry.ts
1001
968
  const uploadAdaptersBySession = /* @__PURE__ */ new Map();
1002
969
  function registerOfflineUploadAdapterForSession(sessionKey, adapter) {
@@ -1242,14 +1209,12 @@ function createPersistentStorageDebugContext(adapter, storeName, debugLogger, en
1242
1209
  };
1243
1210
  }
1244
1211
  function startPersistentStorageDebugTiming(context) {
1245
- if (!import.meta.env.DEV) return null;
1246
- if (!context?.debugLogger) return null;
1247
- return context.adapterKind === "async" ? getTSDFDebugTimingMs() : null;
1212
+ return null;
1248
1213
  }
1249
1214
  function logPersistentStorageOperation(context, operation, status, startTime, details, error) {
1250
1215
  if (!import.meta.env.DEV) return;
1251
1216
  if (!context?.debugLogger) return;
1252
- const durationMs = startTime === null ? void 0 : getTSDFDebugTimingMs() - startTime;
1217
+ const durationMs = startTime === null ? void 0 : Date.now() - startTime;
1253
1218
  const logDetails = {
1254
1219
  adapter: context.adapterKind,
1255
1220
  storeName: context.storeName,
@@ -1292,7 +1257,9 @@ function scheduleAdapterExpirationScan(adapter) {
1292
1257
  if (adapter === "local-sync") {
1293
1258
  if (localStorageExpirationScanScheduled) return;
1294
1259
  localStorageExpirationScanScheduled = true;
1295
- scheduleLocalStorageMaintenance();
1260
+ setTimeout(() => {
1261
+ scheduleLocalStorageMaintenance();
1262
+ }, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS);
1296
1263
  return;
1297
1264
  }
1298
1265
  if (scannedAsyncAdapters.has(adapter)) return;
@@ -1312,18 +1279,18 @@ function ensureAsyncNamespaceKind(entryPrefix) {
1312
1279
  * forced manifest keys are coalesced and a global sweep request wins over
1313
1280
  * targeted maintenance because it already covers the full cleanup pass.
1314
1281
  */
1315
- function scheduleLocalStorageMaintenance(options = {}) {
1316
- if (options.forceManifestKeys === void 0) {
1282
+ function scheduleLocalStorageMaintenance(forceManifestKeys) {
1283
+ if (forceManifestKeys === void 0) {
1317
1284
  localStorageGlobalMaintenanceRequested = true;
1318
1285
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1319
- } else if (!localStorageGlobalMaintenanceRequested) for (const manifestKey of options.forceManifestKeys) scheduledLocalStorageMaintenanceManifestKeys.add(manifestKey);
1286
+ } else if (!localStorageGlobalMaintenanceRequested) for (const manifestKey of forceManifestKeys) scheduledLocalStorageMaintenanceManifestKeys.add(manifestKey);
1320
1287
  if (cancelScheduledLocalStorageMaintenance !== null) return;
1321
1288
  cancelScheduledLocalStorageMaintenance = scheduleIdleCleanup(() => {
1322
1289
  cancelScheduledLocalStorageMaintenance = null;
1323
- const forceManifestKeys = localStorageGlobalMaintenanceRequested ? void 0 : [...scheduledLocalStorageMaintenanceManifestKeys];
1290
+ const maintenanceManifestKeys = localStorageGlobalMaintenanceRequested ? void 0 : [...scheduledLocalStorageMaintenanceManifestKeys];
1324
1291
  localStorageGlobalMaintenanceRequested = false;
1325
1292
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1326
- localPersistentStorage.runMaintenance(forceManifestKeys);
1293
+ localPersistentStorage.runMaintenance(maintenanceManifestKeys);
1327
1294
  });
1328
1295
  }
1329
1296
  function preserveOfflineProtectionFlag(sessionKey, storageKey, nextMeta, currentMeta) {
@@ -1421,6 +1388,8 @@ function createPersistentStorageHandle(config, { asyncValueCodec, getManifestMet
1421
1388
  if (asyncAdapter === null) return null;
1422
1389
  const sessionKey = config.getSessionKey();
1423
1390
  if (sessionKey === false) return null;
1391
+ asyncAdapter.debugLogger = config.debugLogger;
1392
+ asyncAdapter.logger = config.logger;
1424
1393
  return asyncAdapter.openNamespace({
1425
1394
  sessionKey,
1426
1395
  storeName: asyncNamespace?.storeName ?? config.storeName,
@@ -1625,6 +1594,8 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
1625
1594
  if (asyncAdapter === null) return null;
1626
1595
  const sessionKey = config.getSessionKey();
1627
1596
  if (sessionKey === false) return null;
1597
+ asyncAdapter.debugLogger = config.debugLogger;
1598
+ asyncAdapter.logger = config.logger;
1628
1599
  return asyncAdapter.openNamespace({
1629
1600
  sessionKey,
1630
1601
  storeName: config.storeName,
@@ -2175,16 +2146,16 @@ function getStorageKeyForStore(sessionKey, storeName) {
2175
2146
  function getStoragePrefixForStoreNamespace(sessionKey, storeName, entryPrefix) {
2176
2147
  return `${getStorageKey(sessionKey, storeName)}.${entryPrefix}.`;
2177
2148
  }
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}`;
2149
+ function createProtectedStorageKey(sessionKey, storeName, kind, key, backend = "localStorage") {
2150
+ if (backend === "localStorage") {
2151
+ if (kind === "document" && key === "d") return getStorageKeyForStore(sessionKey, storeName);
2152
+ return `${getStoragePrefixForStoreNamespace(sessionKey, storeName, kind)}${key}`;
2182
2153
  }
2183
2154
  return serializeProtectedRef({
2184
- sessionKey: args.sessionKey,
2185
- storeName: args.storeName,
2186
- kind: ensureAsyncNamespaceKind(args.kind),
2187
- key: args.key
2155
+ sessionKey,
2156
+ storeName,
2157
+ kind: ensureAsyncNamespaceKind(kind),
2158
+ key
2188
2159
  });
2189
2160
  }
2190
2161
  function readManifestPayloadMeta(meta) {
@@ -2205,7 +2176,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2205
2176
  }
2206
2177
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2207
2178
  async function clearAllSessionStorage(sessionKey) {
2208
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-DbyKyARM.js");
2179
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-BpfM2_Y6.js");
2209
2180
  await Promise.all([
2210
2181
  clearSessionStorage(sessionKey, "local-sync"),
2211
2182
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -2295,10 +2266,7 @@ function toCollectionItemState(persisted, dataSchema, shouldIgnoreItem) {
2295
2266
  function setupCollectionPersistence(config, options = {}) {
2296
2267
  assertValidPersistentStoreName(config.storeName);
2297
2268
  const version = config.version;
2298
- const defaultMaxBytes = getDefaultMaxBytesForScope({
2299
- adapter: config.adapter,
2300
- scopeKind: "collection.item"
2301
- });
2269
+ const defaultMaxBytes = getDefaultMaxBytesForScope(config.adapter, "collection.item");
2302
2270
  const maxBytes = config.maxBytes ?? defaultMaxBytes;
2303
2271
  const resolveItemKey = options.getItemKey ?? ((payload) => getCompositeKey(payload));
2304
2272
  const pinnedItemKeys = new Set((config.pinnedItems ?? []).map((payload) => resolveItemKey(payload)));
@@ -2335,6 +2303,26 @@ function setupCollectionPersistence(config, options = {}) {
2335
2303
  getManifestMeta: (data) => ({ p: data.payload }),
2336
2304
  valueCodec: itemStorageValueCodec
2337
2305
  });
2306
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
2307
+ function logByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
2308
+ const logger = config.logger;
2309
+ if (!logger) return;
2310
+ const evictedEntries = totalEntries - keptKeys.size;
2311
+ if (evictedEntries === 0) return;
2312
+ logPersistentStorageQuotaCleanup({
2313
+ adapter: quotaCleanupAdapter,
2314
+ logger,
2315
+ evictedEntries,
2316
+ keptEntries: keptKeys.size,
2317
+ maxBytes,
2318
+ namespaceKind: "collection.item",
2319
+ phase,
2320
+ quota: "maxBytes",
2321
+ storeName: config.storeName,
2322
+ totalEntries,
2323
+ unprotectedBytes
2324
+ });
2325
+ }
2338
2326
  function getAsyncNamespaceScope() {
2339
2327
  if (asyncStorageAdapter === null) return null;
2340
2328
  const sessionKey = config.getSessionKey();
@@ -2349,18 +2337,8 @@ function setupCollectionPersistence(config, options = {}) {
2349
2337
  const asyncNamespaceScope = getAsyncNamespaceScope();
2350
2338
  if (asyncNamespaceScope === null) return JSON.stringify(args.value).length;
2351
2339
  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
- });
2340
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, { p: args.value.payload }, args.protectedKeysSnapshotSet, asyncNamespaceScope, args.itemKey);
2341
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
2364
2342
  }
2365
2343
  let storeRef = null;
2366
2344
  let unsubscribe = null;
@@ -2434,15 +2412,8 @@ function setupCollectionPersistence(config, options = {}) {
2434
2412
  protected: protectedItemKeys.has(itemKey),
2435
2413
  sizeBytes: rememberPersistedMetadataSize(itemKey, metadata.sizeBytes)
2436
2414
  }));
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
- });
2415
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
2416
+ logByteBudgetCleanup("startup-cleanup", candidateEntries.length, keptKeys, unprotectedBytes);
2446
2417
  for (const { itemKey } of candidateEntries) {
2447
2418
  if (keptKeys.has(itemKey)) continue;
2448
2419
  deleteKeys.add(getPayloadRecordKey(itemKey));
@@ -2707,15 +2678,8 @@ function setupCollectionPersistence(config, options = {}) {
2707
2678
  await Promise.all(ignoredEntries.map(({ itemKey }) => namespace.remove(itemKey)));
2708
2679
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2709
2680
  }
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
- });
2681
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2682
+ logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
2719
2683
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2720
2684
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2721
2685
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2743,15 +2707,8 @@ function setupCollectionPersistence(config, options = {}) {
2743
2707
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2744
2708
  }
2745
2709
  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
- });
2710
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2711
+ logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
2755
2712
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2756
2713
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2757
2714
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2874,15 +2831,8 @@ function setupCollectionPersistence(config, options = {}) {
2874
2831
  if (metadataByKey.has(entry.itemKey)) pendingRemoves.add(entry.itemKey);
2875
2832
  }
2876
2833
  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
- });
2834
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(remainingCandidates, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, maxBytes);
2835
+ logByteBudgetCleanup("flush", remainingCandidates.length, keptKeys, unprotectedBytes);
2886
2836
  if (keptKeys.size !== remainingCandidates.length) {
2887
2837
  for (const { itemKey } of remainingCandidates) {
2888
2838
  if (keptKeys.has(itemKey)) continue;
@@ -2915,7 +2865,7 @@ function setupCollectionPersistence(config, options = {}) {
2915
2865
  } else knownPersistedKeys = null;
2916
2866
  if (localStorageAdapter !== null && maintenanceManifestKey !== null) {
2917
2867
  const nextKnownPersistedBytes = getKnownPersistedBytes(knownPersistedKeys);
2918
- if (hasIgnoreItemFilter || nextKnownPersistedBytes === null || nextKnownPersistedBytes > maxBytes) scheduleLocalStorageMaintenance({ forceManifestKeys: [maintenanceManifestKey] });
2868
+ if (hasIgnoreItemFilter || nextKnownPersistedBytes === null || nextKnownPersistedBytes > maxBytes) scheduleLocalStorageMaintenance([maintenanceManifestKey]);
2919
2869
  return;
2920
2870
  }
2921
2871
  const sessionKey = config.getSessionKey();
@@ -2998,7 +2948,7 @@ function setupCollectionPersistence(config, options = {}) {
2998
2948
  }
2999
2949
  //#endregion
3000
2950
  //#region src/persistentStorage/offline/mutationRuntime.ts
3001
- async function runHybridOfflineMutation({ controller, offline, upload, directMutation }) {
2951
+ async function runHybridOfflineMutation(controller, offline, upload, directMutation) {
3002
2952
  if (!offline || !controller) throw new Error("runHybridOfflineMutation requires an offline mutation and controller");
3003
2953
  const prepared = await controller.prepareForMutation({
3004
2954
  offline,
@@ -3029,14 +2979,14 @@ function isOfflineResolutionRecordForStore(resolution, operations) {
3029
2979
  }
3030
2980
  //#endregion
3031
2981
  //#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) {
2982
+ function rebindOfflineOverlayEntries(overlayStore, itemKeyRewrites, createReboundOverlay) {
2983
+ if (itemKeyRewrites.length === 0) return;
2984
+ overlayStore.produceState((draft) => {
2985
+ for (const { previousItemKey, nextItemKey } of itemKeyRewrites) {
3036
2986
  if (previousItemKey === nextItemKey) continue;
3037
2987
  const existingOverlay = draft[previousItemKey];
3038
2988
  if (existingOverlay === void 0) continue;
3039
- if (draft[nextItemKey] === void 0) draft[nextItemKey] = args.createReboundOverlay({
2989
+ if (draft[nextItemKey] === void 0) draft[nextItemKey] = createReboundOverlay({
3040
2990
  existingOverlay,
3041
2991
  nextItemKey
3042
2992
  });
@@ -3045,28 +2995,27 @@ function rebindOfflineOverlayEntries(args) {
3045
2995
  }
3046
2996
  });
3047
2997
  }
3048
- function captureOfflineOverlayEntries(args) {
3049
- const targetItemKeys = [...new Set(args.itemKeys)];
2998
+ function captureOfflineOverlayEntries(overlayStore, itemKeys, createOverlay) {
2999
+ const targetItemKeys = [...new Set(itemKeys)];
3050
3000
  if (targetItemKeys.length === 0) return;
3051
- args.overlayStore.produceState((draft) => {
3001
+ overlayStore.produceState((draft) => {
3052
3002
  for (const itemKey of targetItemKeys) {
3053
3003
  const existingOverlay = draft[itemKey];
3054
3004
  if (existingOverlay?.keepVisibleWhileResolutionRequired) {
3055
3005
  existingOverlay.keepVisibleWhileResolutionRequired = false;
3056
3006
  continue;
3057
3007
  }
3058
- draft[itemKey] = args.createOverlay(itemKey);
3008
+ draft[itemKey] = createOverlay(itemKey);
3059
3009
  }
3060
3010
  });
3061
3011
  }
3062
3012
  //#endregion
3063
3013
  //#region src/utils/browserTabsPriority.ts
3064
- const DEFAULT_HEARTBEAT_MS = 5e3;
3065
- const DEFAULT_PRESENCE_TTL_MS = 15e3;
3066
3014
  const DEFAULT_FETCH_LEASE_MS = 1e4;
3015
+ const DEFAULT_BACKGROUND_COALESCING_DELAY_MS$1 = 3e3;
3067
3016
  const COALESCING_WINDOW_STEP_MS = 1e3;
3068
3017
  /** @internal */
3069
- function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getWindowIsFocused, onWindowFocusChange, publishStatus, timings, onLeaderChange }) {
3018
+ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWindowIsFocused, onWindowFocusChange, publishStatus, timings, onLeaderChange) {
3070
3019
  const knownTabs = /* @__PURE__ */ new Map();
3071
3020
  const remoteFetchLeases = /* @__PURE__ */ new Map();
3072
3021
  let lastLeaderTabId;
@@ -3076,25 +3025,18 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3076
3025
  lastFocusedAt: getWindowIsFocused() ? Date.now() : 0,
3077
3026
  lastPresenceAt: Date.now()
3078
3027
  };
3079
- const heartbeatMs = timings?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
3080
- const presenceTtlMs = timings?.presenceTtlMs ?? DEFAULT_PRESENCE_TTL_MS;
3081
3028
  function resolveFetchLeaseMs(lastFetchDuration) {
3082
3029
  const configuredLeaseMs = timings?.fetchLeaseMs;
3083
3030
  if (typeof configuredLeaseMs === "function") return Math.max(0, configuredLeaseMs(lastFetchDuration));
3084
3031
  if (typeof configuredLeaseMs === "number") return Math.max(0, configuredLeaseMs);
3085
3032
  return Math.max(lastFetchDuration * 3, DEFAULT_FETCH_LEASE_MS);
3086
3033
  }
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
3034
  function pruneExpiredRemoteLeases() {
3092
3035
  const now = Date.now();
3093
3036
  for (const [targetKey, lease] of remoteFetchLeases) if (lease.expiresAt <= now) remoteFetchLeases.delete(targetKey);
3094
3037
  }
3095
3038
  function getRankedLiveTabs() {
3096
3039
  if (!getIsEnabled()) return [localPresence];
3097
- pruneStaleTabs();
3098
3040
  return [localPresence, ...knownTabs.values()].sort((a, b) => {
3099
3041
  if (a.isFocused !== b.isFocused) return a.isFocused ? -1 : 1;
3100
3042
  if (a.lastFocusedAt !== b.lastFocusedAt) return b.lastFocusedAt - a.lastFocusedAt;
@@ -3166,7 +3108,7 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3166
3108
  if (baseCoalescingWindowMs <= 0) return baseCoalescingWindowMs;
3167
3109
  const coalescingRank = getCoalescingRank();
3168
3110
  if (coalescingRank <= 0) return baseCoalescingWindowMs;
3169
- return baseCoalescingWindowMs + coalescingRank * COALESCING_WINDOW_STEP_MS;
3111
+ return baseCoalescingWindowMs + Math.max(0, timings?.backgroundCoalescingDelayMs ?? DEFAULT_BACKGROUND_COALESCING_DELAY_MS$1) + (coalescingRank - 1) * COALESCING_WINDOW_STEP_MS;
3170
3112
  }
3171
3113
  function onTabStatusMessage(remoteTabId, message) {
3172
3114
  if (!getIsEnabled()) return;
@@ -3211,13 +3153,8 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3211
3153
  remoteFetchLeases.clear();
3212
3154
  }
3213
3155
  let cleanupFocusListeners;
3214
- let heartbeatInterval;
3215
- const shouldRunHeartbeat = transportEnabled && heartbeatMs > 0 && true;
3216
3156
  if (transportEnabled) {
3217
3157
  publishLocalStatus();
3218
- if (shouldRunHeartbeat) heartbeatInterval = setInterval(() => {
3219
- publishLocalStatus();
3220
- }, heartbeatMs);
3221
3158
  if (onWindowFocusChange) cleanupFocusListeners = onWindowFocusChange(() => {
3222
3159
  noteLocalFocusState();
3223
3160
  });
@@ -3246,7 +3183,6 @@ function createBrowserTabsPriority({ transportEnabled, getIsEnabled, tabId, getW
3246
3183
  reset,
3247
3184
  close() {
3248
3185
  cleanupFocusListeners?.();
3249
- if (heartbeatInterval) clearInterval(heartbeatInterval);
3250
3186
  reset();
3251
3187
  knownTabs.clear();
3252
3188
  }
@@ -3290,11 +3226,10 @@ function getDefaultTransportFactory() {
3290
3226
  };
3291
3227
  }
3292
3228
  /** @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;
3229
+ function createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, tabId = createBrowserTabsTabId()) {
3230
+ const resolvedTransportFactory = transportFactory ?? getDefaultTransportFactory();
3231
+ const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3296
3232
  const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3297
- const tabId = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
3298
3233
  let seq = 0;
3299
3234
  const lastSeenSeqByTab = /* @__PURE__ */ new Map();
3300
3235
  let currentSessionKey;
@@ -3330,7 +3265,7 @@ function createBrowserTabsCoordinator(options) {
3330
3265
  }
3331
3266
  return nextSessionKey;
3332
3267
  }
3333
- const transport = transportFactory({
3268
+ const transport = resolvedTransportFactory({
3334
3269
  channelName,
3335
3270
  onMessage(rawMessage) {
3336
3271
  const localSessionKey = refreshSessionKey();
@@ -3434,57 +3369,58 @@ function createBrowserTabsCoordinator(options) {
3434
3369
  };
3435
3370
  }
3436
3371
  /** @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;
3372
+ function createBrowserTabsCoordinatorWithPriority(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, getWindowIsFocused, onWindowFocusChange, priorityTimings, tabId) {
3373
+ const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3440
3374
  const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3441
3375
  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
- });
3376
+ const coordinator = createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, (sessionKey, previousSessionKey) => {
3377
+ priorityRef.current?.reset();
3378
+ if (sessionKey !== false && coordinator.enabled) priorityRef.current?.publishLocalStatus();
3379
+ onSessionChange?.(sessionKey, previousSessionKey);
3380
+ }, transportFactory, debugLoggerInput, tabId);
3381
+ const priority = createBrowserTabsPriority(coordinator.enabled, () => coordinator.isSessionActive(), coordinator.tabId, getWindowIsFocused, onWindowFocusChange, (status) => {
3382
+ coordinator.publish(__LEGIT_CAST__(status));
3383
+ }, priorityTimings, import.meta.env.DEV ? (details) => {
3384
+ if (!debugLogger) return;
3385
+ emitTSDFDebugLog(debugLogger, {
3386
+ area: "browser-tabs",
3387
+ level: "log",
3388
+ message: "browser-tab sync leader changed",
3389
+ operation: "leader-change",
3390
+ details: {
3391
+ channelName,
3392
+ storeKey,
3393
+ storeType,
3394
+ tabId: details.localTabId,
3395
+ ...details
3396
+ }
3397
+ });
3398
+ } : void 0);
3482
3399
  priorityRef.current = priority;
3483
3400
  return {
3484
3401
  coordinator,
3485
3402
  priority
3486
3403
  };
3487
3404
  }
3405
+ /** @internal */
3406
+ function createBrowserTabsPresencePriority(options) {
3407
+ const priorityRef = { current: null };
3408
+ const { coordinator, priority } = createBrowserTabsCoordinatorWithPriority("presence", "manager", options.getSessionKey, (message) => {
3409
+ priorityRef.current?.onTabStatusMessage(message.tabId, message);
3410
+ }, void 0, options.transportFactory, import.meta.env.DEV ? options.debugLogger : void 0, options.getWindowIsFocused, options.onWindowFocusChange, options.priorityTimings);
3411
+ priorityRef.current = priority;
3412
+ return {
3413
+ priority,
3414
+ tabId: coordinator.tabId,
3415
+ close() {
3416
+ coordinator.close();
3417
+ priority.close();
3418
+ }
3419
+ };
3420
+ }
3421
+ function createBrowserTabsTabId() {
3422
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
3423
+ }
3488
3424
  function toBrowserTabsSyncVersion(meta, consistency) {
3489
3425
  return {
3490
3426
  tabId: meta.tabId,
@@ -3520,25 +3456,25 @@ function stripStoredUploadFile(record) {
3520
3456
  const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, ...upload } = record;
3521
3457
  return upload;
3522
3458
  }
3523
- function createStoredUploadRecord(args) {
3524
- const file = normalizeUploadFile(args.file, args.id);
3459
+ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt) {
3460
+ const file = normalizeUploadFile(fileInput, id);
3525
3461
  const now = Date.now();
3526
- const createdAt = args.createdAt ?? now;
3462
+ const createdAt = createdAtInput ?? now;
3527
3463
  const updatedAt = now;
3528
3464
  return {
3529
- id: args.id,
3530
- sessionKey: args.sessionKey,
3531
- source: args.source,
3532
- state: args.state ?? "pending",
3465
+ id,
3466
+ sessionKey,
3467
+ source,
3468
+ state: state ?? "pending",
3533
3469
  fileName: file.name,
3534
3470
  mimeType: file.type,
3535
3471
  sizeBytes: file.size,
3536
3472
  createdAt,
3537
3473
  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 } : {},
3474
+ ...resolvedRef !== void 0 ? { resolvedRef } : {},
3475
+ ...progress !== void 0 ? { progress } : {},
3476
+ ...lastError !== void 0 ? { lastError } : {},
3477
+ ...lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt } : {},
3542
3478
  file,
3543
3479
  lastModified: file.lastModified
3544
3480
  };
@@ -3853,21 +3789,14 @@ var SessionOfflineCoordinator = class {
3853
3789
  })
3854
3790
  });
3855
3791
  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
- });
3792
+ this.#browserTabs = createBrowserTabsCoordinatorWithPriority("offline", `session:${sessionKey}`, () => this.sessionKey, (message) => {
3793
+ if (message.kind === "tab-status") {
3794
+ this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
3795
+ this.#refreshLeadership();
3796
+ return;
3797
+ }
3798
+ this.#applyRemoteSnapshot(message);
3799
+ }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, void 0, void 0);
3871
3800
  this.#refreshLeadership();
3872
3801
  if (shouldBootstrapFromStorage) this.hydrate();
3873
3802
  if (this.#hasCanonicalConfig) this.#refreshNetworkConfig();
@@ -4029,14 +3958,7 @@ var SessionOfflineCoordinator = class {
4029
3958
  async saveUpload(args) {
4030
3959
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
4031
3960
  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
- });
3961
+ 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
3962
  await this.#saveUploadRecord(nextRecord);
4041
3963
  }
4042
3964
  async replaceUpload(args) {
@@ -5173,10 +5095,9 @@ function initializeOfflineStoreController(controller) {
5173
5095
  controller.ensureReplayScheduled();
5174
5096
  });
5175
5097
  }
5176
- function createOfflineStoreController(options) {
5177
- const { storeName, storeType, getSessionKey, onPersistentStorageError, adapter, storeAdapter, offlineSession, operations } = options;
5098
+ function createOfflineStoreController(storeName, storeType, getSessionKey, onPersistentStorageError, debugLogger, adapter, storeAdapter, offlineSession, operations) {
5178
5099
  const sessionConfig = offlineSession.getConfig();
5179
- const activeDebugLogger = import.meta.env.DEV ? options.debugLogger : void 0;
5100
+ const activeDebugLogger = import.meta.env.DEV ? debugLogger : void 0;
5180
5101
  const replayQueue = createAsyncQueue({
5181
5102
  concurrency: 1,
5182
5103
  autoStart: true
@@ -7018,8 +6939,8 @@ var RequestScheduler = class {
7018
6939
  phase: { type: "idle" },
7019
6940
  pending: {
7020
6941
  scheduledRequests: /* @__PURE__ */ new Map(),
7021
- rtuDelayed: null,
7022
- mediumPriorityDelayed: null,
6942
+ rtuDelayed: /* @__PURE__ */ new Map(),
6943
+ mediumPriorityDelayed: /* @__PURE__ */ new Map(),
7023
6944
  mutationsInProgress: /* @__PURE__ */ new Map()
7024
6945
  },
7025
6946
  timing: {
@@ -7038,7 +6959,7 @@ var RequestScheduler = class {
7038
6959
  }
7039
6960
  get hasPendingFetch() {
7040
6961
  const { phase, pending } = this.#state;
7041
- return phase.type !== "idle" || pending.scheduledRequests.size > 0 || pending.rtuDelayed !== null || pending.mediumPriorityDelayed !== null;
6962
+ return phase.type !== "idle" || pending.scheduledRequests.size > 0 || pending.rtuDelayed.size > 0 || pending.mediumPriorityDelayed.size > 0;
7042
6963
  }
7043
6964
  get fetchIsInProgress() {
7044
6965
  return this.#state.phase.type === "fetching";
@@ -7146,11 +7067,31 @@ var RequestScheduler = class {
7146
7067
  reset() {
7147
7068
  const { phase, pending, abort } = this.#state;
7148
7069
  if (phase.type === "coalescing") clearTimeout(phase.timeoutId);
7149
- if (pending.rtuDelayed) clearTimeout(pending.rtuDelayed.timeoutId);
7150
- if (pending.mediumPriorityDelayed) clearTimeout(pending.mediumPriorityDelayed.timeoutId);
7070
+ for (const rtu of pending.rtuDelayed.values()) clearTimeout(rtu.timeoutId);
7071
+ for (const delayed of pending.mediumPriorityDelayed.values()) clearTimeout(delayed.timeoutId);
7151
7072
  if (abort.controller) abort.controller.abort();
7152
7073
  this.#state = this.#createInitialState();
7153
7074
  }
7075
+ /** Re-evaluates the pending delayed realtime update fetch against the
7076
+ * current dynamic throttle, rescheduling it sooner (or firing it right away
7077
+ * when the recomputed interval has already elapsed). Used when the window
7078
+ * regains focus so a refetch priced with the background throttle doesn't
7079
+ * keep the tab stale. Never extends the pending delay. */
7080
+ reevaluateDelayedRTU() {
7081
+ if (!this.#dynamicRealtimeThrottleMs) return;
7082
+ if (this.#state.pending.rtuDelayed.size === 0) return;
7083
+ const { timing } = this.#state;
7084
+ const newFireAt = timing.lastFetchStartTime + timing.lastFetchDuration + this.#dynamicRealtimeThrottleMs(timing.lastFetchDuration);
7085
+ for (const rtu of Array.from(this.#state.pending.rtuDelayed.values())) {
7086
+ if (newFireAt >= rtu.fireAt) continue;
7087
+ clearTimeout(rtu.timeoutId);
7088
+ this.#state.pending.rtuDelayed.delete(rtu.requestId);
7089
+ if (!this.#scheduleDelayedRTU(Date.now(), rtu.requestId, rtu.payload, rtu.remoteStartCancelable)) {
7090
+ this.#onEvent?.("scheduled-rt-fetch-started");
7091
+ this.#scheduleRequest(rtu.requestId, "highPriority", rtu.payload, void 0, rtu.remoteStartCancelable);
7092
+ }
7093
+ }
7094
+ }
7154
7095
  cancelCoalescingRequests(requestIds) {
7155
7096
  return this.#cancelCoalescingRequests(requestIds, false, void 0);
7156
7097
  }
@@ -7164,20 +7105,24 @@ var RequestScheduler = class {
7164
7105
  this.#finalizePendingRequestCallbacks(scheduledRequest, false);
7165
7106
  wasCancelled = true;
7166
7107
  }
7167
- const rtuDelayed = this.#state.pending.rtuDelayed;
7168
- if (rtuDelayed && requestIds.includes(rtuDelayed.requestId) && matchesShouldCancel(shouldCancel, rtuDelayed.requestId, rtuDelayed)) {
7169
- this.#clearRtuDelayed();
7170
- wasCancelled = true;
7108
+ for (const requestId of requestIds) {
7109
+ const rtuDelayed = this.#state.pending.rtuDelayed.get(requestId);
7110
+ if (rtuDelayed && matchesShouldCancel(shouldCancel, requestId, rtuDelayed)) {
7111
+ this.#clearRtuDelayed(requestId);
7112
+ wasCancelled = true;
7113
+ }
7171
7114
  }
7172
- const mediumPriorityDelayed = this.#state.pending.mediumPriorityDelayed;
7173
- if (mediumPriorityDelayed && requestIds.includes(mediumPriorityDelayed.requestId) && matchesShouldCancel(shouldCancel, mediumPriorityDelayed.requestId, mediumPriorityDelayed)) {
7174
- this.#cancelMediumPriority();
7175
- wasCancelled = true;
7115
+ for (const requestId of requestIds) {
7116
+ const mediumDelayed = this.#state.pending.mediumPriorityDelayed.get(requestId);
7117
+ if (mediumDelayed && matchesShouldCancel(shouldCancel, requestId, mediumDelayed)) {
7118
+ this.#cancelMediumPriority(requestId);
7119
+ wasCancelled = true;
7120
+ }
7176
7121
  }
7177
- if (this.#state.phase.type === "fetching") {
7178
- const rtuAfterFetch = this.#state.phase.rtuAfterFetch;
7179
- if (rtuAfterFetch && requestIds.includes(rtuAfterFetch.requestId) && matchesShouldCancel(shouldCancel, rtuAfterFetch.requestId, rtuAfterFetch)) {
7180
- this.#state.phase.rtuAfterFetch = null;
7122
+ if (this.#state.phase.type === "fetching") for (const requestId of requestIds) {
7123
+ const rtuAfterFetch = this.#state.phase.rtuAfterFetch.get(requestId);
7124
+ if (rtuAfterFetch && matchesShouldCancel(shouldCancel, requestId, rtuAfterFetch)) {
7125
+ this.#state.phase.rtuAfterFetch.delete(requestId);
7181
7126
  wasCancelled = true;
7182
7127
  }
7183
7128
  }
@@ -7313,10 +7258,12 @@ var RequestScheduler = class {
7313
7258
  fetchId,
7314
7259
  startTime,
7315
7260
  fetchingRequests,
7316
- rtuAfterFetch: null
7261
+ rtuAfterFetch: /* @__PURE__ */ new Map()
7317
7262
  };
7318
- this.#clearRtuDelayed();
7319
- this.#cancelMediumPriority();
7263
+ for (const requestId of requests.keys()) {
7264
+ this.#clearRtuDelayed(requestId);
7265
+ this.#cancelMediumPriority(requestId);
7266
+ }
7320
7267
  const shouldAbort = this.#createShouldAbort(fetchId, requests, abortController);
7321
7268
  const batchRequests = Array.from(requests.entries()).map(([requestId, request]) => ({
7322
7269
  requestId,
@@ -7340,13 +7287,15 @@ var RequestScheduler = class {
7340
7287
  }
7341
7288
  if (Array.from(results.values()).some((value) => value)) this.#state.timing.lastFetchDuration = Date.now() - startTime;
7342
7289
  const { fetchingRequests: callbacks, rtuAfterFetch } = this.#state.phase;
7343
- this.#clearRtuDelayed();
7344
7290
  this.#state.phase = { type: "idle" };
7345
7291
  for (const [requestId, { awaitCallbacks }] of callbacks) {
7346
7292
  const wasAborted = this.#state.lastAbortedRequests.has(requestId);
7347
7293
  for (const callback of awaitCallbacks) callback(wasAborted);
7348
7294
  }
7349
- if (rtuAfterFetch) this.#scheduleDelayedRTU(Date.now(), rtuAfterFetch.requestId, rtuAfterFetch.payload, rtuAfterFetch.remoteStartCancelable);
7295
+ for (const rtu of rtuAfterFetch.values()) if (!this.#scheduleDelayedRTU(Date.now(), rtu.requestId, rtu.payload, rtu.remoteStartCancelable)) {
7296
+ this.#onEvent?.("scheduled-rt-fetch-started");
7297
+ this.#scheduleRequest(rtu.requestId, "highPriority", rtu.payload, void 0, rtu.remoteStartCancelable);
7298
+ }
7350
7299
  this.#flushScheduledRequests();
7351
7300
  return true;
7352
7301
  }
@@ -7430,30 +7379,35 @@ var RequestScheduler = class {
7430
7379
  }
7431
7380
  return false;
7432
7381
  }
7433
- #clearRtuDelayed() {
7434
- const rtu = this.#state.pending.rtuDelayed;
7382
+ #clearRtuDelayed(requestId) {
7383
+ const rtu = this.#state.pending.rtuDelayed.get(requestId);
7435
7384
  if (rtu) {
7436
7385
  clearTimeout(rtu.timeoutId);
7437
- this.#state.pending.rtuDelayed = null;
7386
+ this.#state.pending.rtuDelayed.delete(requestId);
7438
7387
  this.#onEvent?.("rt-fetch-cancelled");
7439
7388
  }
7440
7389
  }
7441
7390
  #handleRealtimeUpdate(startTime, requestId, payload, remoteStartCancelable) {
7442
7391
  const { timing, phase, pending } = this.#state;
7443
7392
  if (!timing.lastFetchDuration || !timing.lastFetchStartTime || !this.#dynamicRealtimeThrottleMs) return false;
7444
- if (pending.rtuDelayed && pending.rtuDelayed.requestId === requestId) {
7445
- pending.rtuDelayed.payload = this.#coalescePayload ? this.#coalescePayload(pending.rtuDelayed.payload, payload) : payload;
7446
- pending.rtuDelayed.remoteStartCancelable = pending.rtuDelayed.remoteStartCancelable && remoteStartCancelable;
7393
+ const existingDelayed = pending.rtuDelayed.get(requestId);
7394
+ if (existingDelayed) {
7395
+ existingDelayed.payload = this.#coalescePayload ? this.#coalescePayload(existingDelayed.payload, payload) : payload;
7396
+ existingDelayed.remoteStartCancelable = existingDelayed.remoteStartCancelable && remoteStartCancelable;
7447
7397
  return true;
7448
7398
  }
7449
7399
  if (phase.type === "fetching") {
7450
- phase.rtuAfterFetch = {
7400
+ const existing = phase.rtuAfterFetch.get(requestId);
7401
+ if (existing) {
7402
+ existing.payload = this.#coalescePayload ? this.#coalescePayload(existing.payload, payload) : payload;
7403
+ existing.remoteStartCancelable = existing.remoteStartCancelable && remoteStartCancelable;
7404
+ } else phase.rtuAfterFetch.set(requestId, {
7451
7405
  requestId,
7452
7406
  payload,
7453
7407
  priority: "realtimeUpdate",
7454
7408
  addedAt: startTime,
7455
7409
  remoteStartCancelable
7456
- };
7410
+ });
7457
7411
  return true;
7458
7412
  }
7459
7413
  if (pending.mutationsInProgress.has(requestId)) {
@@ -7469,9 +7423,11 @@ var RequestScheduler = class {
7469
7423
  const minimumRealtimeInterval = this.#dynamicRealtimeThrottleMs(timing.lastFetchDuration);
7470
7424
  if (timeSinceLastFetch >= minimumRealtimeInterval) return false;
7471
7425
  const delay = minimumRealtimeInterval - timeSinceLastFetch;
7472
- this.#state.pending.rtuDelayed = {
7426
+ const existing = this.#state.pending.rtuDelayed.get(requestId);
7427
+ if (existing) clearTimeout(existing.timeoutId);
7428
+ this.#state.pending.rtuDelayed.set(requestId, {
7473
7429
  timeoutId: setTimeout(() => {
7474
- this.#state.pending.rtuDelayed = null;
7430
+ this.#state.pending.rtuDelayed.delete(requestId);
7475
7431
  this.#onEvent?.("scheduled-rt-fetch-started");
7476
7432
  this.#scheduleRequest(requestId, "highPriority", payload, void 0, remoteStartCancelable);
7477
7433
  }, delay),
@@ -7479,8 +7435,9 @@ var RequestScheduler = class {
7479
7435
  payload,
7480
7436
  priority: "realtimeUpdate",
7481
7437
  addedAt: startTime,
7482
- remoteStartCancelable
7483
- };
7438
+ remoteStartCancelable,
7439
+ fireAt: startTime + delay
7440
+ });
7484
7441
  this.#onEvent?.("rt-fetch-scheduled", { delayMs: delay });
7485
7442
  return true;
7486
7443
  }
@@ -7488,36 +7445,43 @@ var RequestScheduler = class {
7488
7445
  const delayMs = customDelayMs ?? this.#mediumPriorityDelayMs;
7489
7446
  if (delayMs === void 0) throw new Error("[tsdf] mediumPriorityDelayMs must be configured to use mediumPriority fetch type");
7490
7447
  if (!this.#state.timing.lastFetchStartTime) return this.#scheduleRequest(requestId, "highPriority", payload, void 0, remoteStartCancelable);
7491
- if (this.#state.pending.mediumPriorityDelayed) clearTimeout(this.#state.pending.mediumPriorityDelayed.timeoutId);
7492
- this.#state.pending.mediumPriorityDelayed = {
7448
+ const existing = this.#state.pending.mediumPriorityDelayed.get(requestId);
7449
+ let mergedPayload = payload;
7450
+ let mergedRemoteStartCancelable = remoteStartCancelable;
7451
+ if (existing) {
7452
+ clearTimeout(existing.timeoutId);
7453
+ mergedPayload = this.#coalescePayload ? this.#coalescePayload(existing.payload, payload) : payload;
7454
+ mergedRemoteStartCancelable = existing.remoteStartCancelable && remoteStartCancelable;
7455
+ }
7456
+ this.#state.pending.mediumPriorityDelayed.set(requestId, {
7493
7457
  timeoutId: setTimeout(() => {
7494
7458
  this.#executeMediumPriorityFetch(requestId);
7495
7459
  }, delayMs),
7496
7460
  requestId,
7497
- payload,
7461
+ payload: mergedPayload,
7498
7462
  priority: "mediumPriority",
7499
7463
  addedAt: startTime,
7500
- remoteStartCancelable
7501
- };
7464
+ remoteStartCancelable: mergedRemoteStartCancelable
7465
+ });
7502
7466
  this.#onEvent?.("medium-priority-scheduled", { delayMs });
7503
7467
  return "medium-scheduled";
7504
7468
  }
7505
7469
  #executeMediumPriorityFetch(requestId) {
7506
- const delayedRequest = this.#state.pending.mediumPriorityDelayed;
7507
- if (!delayedRequest || delayedRequest.requestId !== requestId) return;
7508
- this.#state.pending.mediumPriorityDelayed = null;
7470
+ const delayedRequest = this.#state.pending.mediumPriorityDelayed.get(requestId);
7471
+ if (!delayedRequest) return;
7472
+ this.#state.pending.mediumPriorityDelayed.delete(requestId);
7509
7473
  this.#onEvent?.("medium-priority-fetch-started");
7510
- const { phase, pending } = this.#state;
7511
- if (phase.type !== "idle" || pending.mutationsInProgress.has(requestId)) {
7474
+ if (this.#state.phase.type === "fetching") {
7512
7475
  this.#addToScheduledRequests(requestId, delayedRequest.payload, "mediumPriority", Date.now(), delayedRequest.remoteStartCancelable);
7513
7476
  return;
7514
7477
  }
7515
7478
  this.#scheduleRequest(requestId, "highPriority", delayedRequest.payload, void 0, delayedRequest.remoteStartCancelable);
7516
7479
  }
7517
- #cancelMediumPriority() {
7518
- if (this.#state.pending.mediumPriorityDelayed) {
7519
- clearTimeout(this.#state.pending.mediumPriorityDelayed.timeoutId);
7520
- this.#state.pending.mediumPriorityDelayed = null;
7480
+ #cancelMediumPriority(requestId) {
7481
+ const delayed = this.#state.pending.mediumPriorityDelayed.get(requestId);
7482
+ if (delayed) {
7483
+ clearTimeout(delayed.timeoutId);
7484
+ this.#state.pending.mediumPriorityDelayed.delete(requestId);
7521
7485
  this.#onEvent?.("medium-priority-cancelled");
7522
7486
  }
7523
7487
  }
@@ -7579,8 +7543,9 @@ var RequestScheduler = class {
7579
7543
  };
7580
7544
  //#endregion
7581
7545
  //#region src/storeManager.ts
7582
- const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 5;
7583
- const DEFAULT_BASE_COALESCING_WINDOW_MS = 10;
7546
+ const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 2400 * 1e3;
7547
+ const DEFAULT_BASE_COALESCING_WINDOW_MS = 16;
7548
+ const DEFAULT_BACKGROUND_COALESCING_DELAY_MS = 3e3;
7584
7549
  function defaultDynamicRealtimeThrottleMs({ windowIsNotFocused }) {
7585
7550
  return windowIsNotFocused ? 1e3 : 100;
7586
7551
  }
@@ -7628,7 +7593,8 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
7628
7593
  };
7629
7594
  }
7630
7595
  function createStoreManager(options) {
7631
- const debugLogger = import.meta.env.DEV ? resolveTSDFDebugLogger(options.debug) : void 0;
7596
+ const debugLogger = import.meta.env.DEV ? resolveTSDFLogger(options.debugLogger) : void 0;
7597
+ const logger = resolveTSDFLogger(options.logger ?? true);
7632
7598
  let resolvedOfflineSession;
7633
7599
  if (options.offlineSession) {
7634
7600
  const createOfflineSessionOptions = {
@@ -7663,6 +7629,7 @@ function createStoreManager(options) {
7663
7629
  useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
7664
7630
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
7665
7631
  const registry = {
7632
+ browserTabsPresence: void 0,
7666
7633
  nextStoreRegistrationId: 0,
7667
7634
  stores: /* @__PURE__ */ new Map()
7668
7635
  };
@@ -7674,6 +7641,7 @@ function createStoreManager(options) {
7674
7641
  storeDefaults: Object.freeze({
7675
7642
  lowPriorityThrottleMs: options.lowPriorityThrottleMs ?? DEFAULT_LOW_PRIORITY_THROTTLE_MS,
7676
7643
  baseCoalescingWindowMs: options.baseCoalescingWindowMs ?? DEFAULT_BASE_COALESCING_WINDOW_MS,
7644
+ backgroundCoalescingDelayMs: options.backgroundCoalescingDelayMs ?? DEFAULT_BACKGROUND_COALESCING_DELAY_MS,
7677
7645
  dynamicRealtimeThrottleMs: options.dynamicRealtimeThrottleMs ?? defaultDynamicRealtimeThrottleMs,
7678
7646
  blockWindowClose: options.blockWindowClose ?? null,
7679
7647
  revalidateOnWindowFocus: options.revalidateOnWindowFocus
@@ -7691,14 +7659,19 @@ function createStoreManager(options) {
7691
7659
  },
7692
7660
  ...offlineApi
7693
7661
  };
7694
- if (debugLogger !== void 0) storeManager.debugLogger = debugLogger;
7662
+ storeManager.debugLogger = debugLogger;
7663
+ storeManager.logger = logger;
7695
7664
  storeManagerRegistry.set(storeManager, registry);
7696
7665
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
7697
7666
  return storeManager;
7698
7667
  }
7699
- function registerStoreWithManager(storeManager, store) {
7668
+ function getRegistryOrThrow(storeManager) {
7700
7669
  const registry = storeManagerRegistry.get(storeManager);
7701
7670
  if (!registry) throw new Error("[tsdf] storeManager must be created with createStoreManager(...)");
7671
+ return registry;
7672
+ }
7673
+ function registerStoreWithManager(storeManager, store) {
7674
+ const registry = getRegistryOrThrow(storeManager);
7702
7675
  let hasDuplicateId = false;
7703
7676
  for (const registeredStore of registry.stores.values()) if (registeredStore.id === store.id) {
7704
7677
  hasDuplicateId = true;
@@ -7710,23 +7683,45 @@ function registerStoreWithManager(storeManager, store) {
7710
7683
  registry.stores.set(registrationId, store);
7711
7684
  return () => {
7712
7685
  registry.stores.delete(registrationId);
7686
+ if (registry.stores.size === 0) {
7687
+ registry.browserTabsPresence?.close();
7688
+ registry.browserTabsPresence = void 0;
7689
+ }
7690
+ };
7691
+ }
7692
+ function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
7693
+ const registry = getRegistryOrThrow(storeManager);
7694
+ const presence = registry.browserTabsPresence ??= createBrowserTabsPresencePriority({
7695
+ getSessionKey: storeManager.getSessionKey,
7696
+ getWindowIsFocused: options.getWindowIsFocused,
7697
+ onWindowFocusChange: options.onWindowFocusChange,
7698
+ transportFactory: options.transportFactory,
7699
+ ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
7700
+ priorityTimings: {
7701
+ backgroundCoalescingDelayMs: storeManager.storeDefaults.backgroundCoalescingDelayMs,
7702
+ ...options.priorityTimings
7703
+ }
7704
+ });
7705
+ return {
7706
+ priority: presence.priority,
7707
+ tabId: presence.tabId
7713
7708
  };
7714
7709
  }
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`);
7710
+ function resolveStoreManagerOfflineSession(storeManager, storeName, usesOfflineStorage) {
7711
+ const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(storeManager));
7712
+ if (!usesOfflineStorage) return null;
7713
+ if (!offlineSession) throw new Error(`[tsdf] Store "${storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
7719
7714
  return offlineSession;
7720
7715
  }
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}"`);
7716
+ function validateStoreManagerSessionConsistency(storeName, offlineSession, getSessionKey) {
7717
+ const sessionKey = getSessionKey();
7718
+ const offlineSessionKey = offlineSession.getSessionKey();
7719
+ if (sessionKey !== offlineSessionKey) throw new Error(`[tsdf] Store "${storeName}" is attached to offline session "${offlineSessionKey}" but storeManager.getSessionKey() returned "${sessionKey}"`);
7725
7720
  return sessionKey;
7726
7721
  }
7727
7722
  //#endregion
7728
7723
  //#region src/utils/performMutation.ts
7729
- async function performMutationWithLifecycle({ startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose }) {
7724
+ async function performMutationWithLifecycle(startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose) {
7730
7725
  const endMutation = startMutation();
7731
7726
  if (optimisticUpdate?.() === false) {
7732
7727
  endMutation();
@@ -7758,7 +7753,7 @@ async function performMutationWithLifecycle({ startMutation, mutation, onError,
7758
7753
  //#endregion
7759
7754
  //#region src/utils/storeFocusLifecycle.ts
7760
7755
  /** @internal */
7761
- function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate }) {
7756
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate, onWindowFocusReevaluateDelayedRTU, debug) {
7762
7757
  let cleanupFocusListener = null;
7763
7758
  let cleanupReconnectFocusListener = null;
7764
7759
  let reconnectCooldownTimeoutId = null;
@@ -7778,6 +7773,19 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7778
7773
  if (typeof revalidateOnWindowFocus === "function") return revalidateOnWindowFocus();
7779
7774
  return !!revalidateOnWindowFocus;
7780
7775
  }
7776
+ const logWindowFocusRevalidate = import.meta.env.DEV && debug?.debugLogger ? (message, details) => {
7777
+ emitTSDFDebugLog(debug.debugLogger, {
7778
+ area: "focus",
7779
+ level: "log",
7780
+ message,
7781
+ operation: "window-focus-revalidate",
7782
+ details: {
7783
+ storeId: debug.storeId,
7784
+ storeType: debug.storeType,
7785
+ ...details
7786
+ }
7787
+ });
7788
+ } : void 0;
7781
7789
  function runTransportReconnectRevalidate() {
7782
7790
  lastTransportReconnectRevalidateAt = Date.now();
7783
7791
  onTransportReconnectRevalidate();
@@ -7816,9 +7824,29 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7816
7824
  clearReconnectCooldownTimeout();
7817
7825
  hasPendingReconnectRevalidateOnFocus = false;
7818
7826
  lastTransportReconnectRevalidateAt = Number.NEGATIVE_INFINITY;
7819
- if (!revalidateOnWindowFocus || usesRealTimeUpdates) return;
7827
+ if (usesRealTimeUpdates) {
7828
+ if (revalidateOnWindowFocus) logWindowFocusRevalidate?.("window focus revalidation skipped", {
7829
+ reason: "real-time-updates",
7830
+ status: "skipped"
7831
+ });
7832
+ cleanupFocusListener = onWindowFocus(onWindowFocusReevaluateDelayedRTU);
7833
+ return;
7834
+ }
7835
+ if (!revalidateOnWindowFocus) return;
7820
7836
  cleanupFocusListener = onWindowFocus(() => {
7821
- if (isFocusRevalidationEnabled()) onWindowFocusRevalidate();
7837
+ if (!isFocusRevalidationEnabled()) {
7838
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
7839
+ policy: "dynamic",
7840
+ reason: "dynamic-disabled",
7841
+ status: "skipped"
7842
+ });
7843
+ return;
7844
+ }
7845
+ logWindowFocusRevalidate?.("window focus revalidation triggered", {
7846
+ policy: typeof revalidateOnWindowFocus === "function" ? "dynamic" : "enabled",
7847
+ status: "triggered"
7848
+ });
7849
+ onWindowFocusRevalidate();
7822
7850
  });
7823
7851
  }
7824
7852
  function dispose() {
@@ -7852,7 +7880,7 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7852
7880
  //#endregion
7853
7881
  //#region src/collectionStore/collectionCacheLimits.ts
7854
7882
  /** @internal */
7855
- function createCollectionCacheLimits({ store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup }) {
7883
+ function createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup) {
7856
7884
  let isEnforcingCacheLimits = false;
7857
7885
  function enforceCacheLimits() {
7858
7886
  if (maxItems === void 0 || isEnforcingCacheLimits) return;
@@ -7897,7 +7925,7 @@ const offlineConnectivityError = {
7897
7925
  function normalizeFetchResultError(fetchResult, errorNormalizer) {
7898
7926
  return fetchResult.offline ? offlineConnectivityError : normalizeStoreError(fetchResult.error, errorNormalizer);
7899
7927
  }
7900
- async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7928
+ async function runOfflineAwareFetch(controller, fetcher, operationName) {
7901
7929
  await controller?.prepareForFetch?.();
7902
7930
  const shouldTreatFetchAsOffline = () => controller?.shouldTreatFetchAsOffline?.() ?? controller?.getSessionStatus()?.isOfflineMode ?? false;
7903
7931
  if (shouldTreatFetchAsOffline()) return {
@@ -7926,7 +7954,7 @@ async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7926
7954
  }
7927
7955
  //#endregion
7928
7956
  //#region src/utils/reusePrevIfEqual.ts
7929
- function reusePrevIfEqual({ prev, current }) {
7957
+ function reusePrevIfEqual(prev, current) {
7930
7958
  if (prev === void 0) return current;
7931
7959
  if (deepEqual(prev, current)) return prev;
7932
7960
  return current;
@@ -7963,10 +7991,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
7963
7991
  }
7964
7992
  if (batchFetchFn && requests.length > 1) try {
7965
7993
  const payloads = requests.map((r) => r.payload);
7966
- const fetchResult = await runOfflineAwareFetch({
7967
- controller: offlineController,
7968
- fetcher: () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__")
7969
- });
7994
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__"));
7970
7995
  if (!fetchResult.ok) {
7971
7996
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
7972
7997
  store.produceState((draft) => {
@@ -8000,10 +8025,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8000
8025
  item.status = "error";
8001
8026
  results.set(itemId, false);
8002
8027
  } else if (result !== void 0) try {
8003
- item.data = reusePrevIfEqual({
8004
- current: unwrapMaybeTSDFResult(result),
8005
- prev: item.data
8006
- });
8028
+ item.data = reusePrevIfEqual(item.data, unwrapMaybeTSDFResult(result));
8007
8029
  item.status = "success";
8008
8030
  item.wasLoaded = true;
8009
8031
  results.set(itemId, true);
@@ -8039,10 +8061,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8039
8061
  }
8040
8062
  const fetchPromises = requests.map(async ({ requestId: itemId, payload }) => {
8041
8063
  try {
8042
- const fetchResult = await runOfflineAwareFetch({
8043
- controller: offlineController,
8044
- fetcher: () => fetchFn(klona(payload), fetchCtx.signal)
8045
- });
8064
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchFn(klona(payload), fetchCtx.signal));
8046
8065
  if (!fetchResult.ok) {
8047
8066
  if (fetchCtx.shouldAbort()) {
8048
8067
  results.set(itemId, false);
@@ -8071,10 +8090,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8071
8090
  store.produceState((draft) => {
8072
8091
  const item = draft[itemId];
8073
8092
  if (!item) return;
8074
- item.data = reusePrevIfEqual({
8075
- current: data,
8076
- prev: item.data
8077
- });
8093
+ item.data = reusePrevIfEqual(item.data, data);
8078
8094
  item.status = "success";
8079
8095
  item.wasLoaded = true;
8080
8096
  }, { action: "fetch-success" });
@@ -8307,8 +8323,7 @@ function createFieldsResourceSignature(fields) {
8307
8323
  if (fields === void 0) return "";
8308
8324
  return JSON.stringify(Array.from(new Set(fields)).sort());
8309
8325
  }
8310
- function shouldScheduleAutomaticFetch(options) {
8311
- const { wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false } = options;
8326
+ function shouldScheduleAutomaticFetch(wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false) {
8312
8327
  if (disableRefetches) return !wasLoaded;
8313
8328
  if (disableRefetchOnMount) return shouldFetch;
8314
8329
  if (skipFreshFetch && !shouldFetch) return false;
@@ -8503,14 +8518,7 @@ function useMultipleItems$1(items, { selector, returnIdleStatus: allItemsReturnI
8503
8518
  const shouldFetch = requiredFetch || !!itemState.refetchOnMount;
8504
8519
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemId)) continue;
8505
8520
  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);
8521
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount) && tryClaimAutomaticFetchSlot(automaticRetryState, itemId, itemState?.status)) scheduleAutomaticFetch(fetchType, payload);
8514
8522
  }
8515
8523
  }
8516
8524
  for (const itemId of removedQueries) ignoreItemsInRefetchOnMount.delete(itemId);
@@ -8551,18 +8559,9 @@ function createCollectionStore(storeOptions) {
8551
8559
  let offlineOverlaySessionKey = null;
8552
8560
  const itemCacheRuntime = createLruCacheRuntime();
8553
8561
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
8554
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
8555
- storeManager,
8556
- storeName: id,
8557
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
8558
- });
8562
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
8559
8563
  const getSessionKeyBase = storeManager.getSessionKey;
8560
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
8561
- storeManager,
8562
- storeName: id,
8563
- offlineSession: resolvedOfflineSession,
8564
- getSessionKey: getSessionKeyBase
8565
- });
8564
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
8566
8565
  const errorNormalizer = storeManager.errorNormalizer;
8567
8566
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
8568
8567
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -8575,7 +8574,8 @@ function createCollectionStore(storeOptions) {
8575
8574
  ...persistentStorageConfig.offline,
8576
8575
  session: resolvedOfflineSessionForPersistentStorage
8577
8576
  } : void 0,
8578
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8577
+ debugLogger: storeManager.debugLogger,
8578
+ logger: storeManager.logger,
8579
8579
  getSessionKey: getSessionKeyForRuntime,
8580
8580
  storeName: id
8581
8581
  }) : null;
@@ -8596,100 +8596,76 @@ function createCollectionStore(storeOptions) {
8596
8596
  offlineOverlayStore.setState({});
8597
8597
  }
8598
8598
  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
- });
8599
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
8600
+ data: existingOverlay.data ?? null,
8601
+ payload: store.state[nextItemKey]?.payload ?? existingOverlay.payload,
8602
+ keepVisibleWhileResolutionRequired: true
8603
+ }));
8608
8604
  }
8609
8605
  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
- }
8606
+ captureOfflineOverlayEntries(offlineOverlayStore, itemKeys, (itemKey) => {
8607
+ const item = store.state[itemKey];
8608
+ return {
8609
+ data: item ? klona(item.data) : null,
8610
+ payload: item ? klona(item.payload) : void 0
8611
+ };
8620
8612
  });
8621
8613
  }
8622
8614
  const resolvedOfflineConfig = resolvedPersistentStorageConfig?.offline;
8623
8615
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_COLLECTION_OFFLINE_OPERATIONS);
8624
8616
  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
- }
8617
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "collection", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
8618
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
8619
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
8620
+ if (normalizedRef !== null) return normalizedRef;
8621
+ return {
8622
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
8623
+ entityKind: "item"
8624
+ };
8625
+ }),
8626
+ getProtectedCacheKeys: (entityRefs) => {
8627
+ const sessionKey = getSessionKeyForRuntime();
8628
+ if (sessionKey === false) return [];
8629
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "collection.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
8630
+ },
8631
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
8632
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
8633
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
8634
+ },
8635
+ rollbackPendingEntity: ({ tempId }) => {
8636
+ deleteItemState(__LEGIT_CAST__(tempId));
8637
+ },
8638
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
8639
+ const tempPayload = __LEGIT_CAST__(tempId);
8640
+ const currentItem = getItemState(tempPayload);
8641
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem?.data ?? void 0;
8642
+ if (finalData === void 0) return;
8643
+ deleteItemState(tempPayload);
8644
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
8645
+ addItemToState(finalPayload, finalData);
8646
+ storeEvents.emit("tempEntityReconciled", {
8647
+ tempId: tempPayload,
8648
+ finalPayload
8649
+ });
8650
+ },
8651
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
8652
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8653
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
8654
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
8655
+ }));
8656
+ },
8657
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
8658
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8659
+ rebindOfflineOverlays(itemKeyRewrites);
8660
+ },
8661
+ syncEntityOverlays: ({ entities, sessionKey }) => {
8662
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8663
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
8664
+ offlineOverlayStore.produceState((draft) => {
8665
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
8666
+ });
8691
8667
  }
8692
- }) : null;
8668
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
8693
8669
  function touchItems(itemKeys) {
8694
8670
  itemCacheRuntime.touch(itemKeys, (itemKey) => {
8695
8671
  return store.state[itemKey] !== void 0;
@@ -8931,10 +8907,6 @@ function createCollectionStore(storeOptions) {
8931
8907
  return getKnownScheduler(message.itemKey)?.isMutationInProgress(message.itemKey) ?? false;
8932
8908
  }
8933
8909
  function handleRemoteMessage(message) {
8934
- if (message.kind === "tab-status") {
8935
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
8936
- return;
8937
- }
8938
8910
  if (message.kind === "fetch-start") {
8939
8911
  const scheduler = getSchedulerForTargetKey(message.targetKey);
8940
8912
  scheduler?.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -8953,21 +8925,16 @@ function createCollectionStore(storeOptions) {
8953
8925
  }
8954
8926
  applyRemoteItemSnapshot(message, candidateVersion);
8955
8927
  }
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,
8928
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
8967
8929
  getWindowIsFocused,
8968
8930
  onWindowFocusChange: testOptions?.onWindowFocusChange,
8931
+ transportFactory: testOptions?.browserTabsTransportFactory,
8969
8932
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
8970
8933
  });
8934
+ const browserTabsSync = createBrowserTabsCoordinator("collection", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
8935
+ lastCollectionSyncVersions.clear();
8936
+ clearOfflineOverlays();
8937
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
8971
8938
  async function executeBatchFetch$1(requests, fetchCtx, batchKey) {
8972
8939
  const results = await executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchFn, errorNormalizer, batchKey, offlineController);
8973
8940
  const successfulRequests = requests.filter(({ requestId }) => results.get(requestId) === true);
@@ -9246,50 +9213,37 @@ function createCollectionStore(storeOptions) {
9246
9213
  item: klona(store.state[itemKey])
9247
9214
  })) : [];
9248
9215
  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" });
9216
+ const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9217
+ kind: "online",
9218
+ data: await directMutation()
9219
+ }), (exception) => {
9220
+ const error = toStoreMutationError(exception, errorNormalizer);
9221
+ if (optimisticRollbackSnapshots.length > 0) {
9222
+ const restoredItemKeys = [];
9223
+ runWithBroadcastConsistency("confirmed", () => {
9224
+ store.produceState((draft) => {
9281
9225
  for (const snapshot of optimisticRollbackSnapshots) {
9282
- if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9283
- else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9284
- publishItemSnapshot(snapshot.itemKey);
9226
+ if (snapshot.item === void 0) {
9227
+ delete draft[snapshot.itemKey];
9228
+ continue;
9229
+ }
9230
+ draft[snapshot.itemKey] = snapshot.item;
9285
9231
  }
9286
- });
9287
- if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9288
- }
9289
- if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9290
- return error;
9291
- }
9292
- });
9232
+ }, { action: "rollback-mutation-error" });
9233
+ for (const snapshot of optimisticRollbackSnapshots) {
9234
+ if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9235
+ else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9236
+ publishItemSnapshot(snapshot.itemKey);
9237
+ }
9238
+ });
9239
+ if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9240
+ }
9241
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9242
+ return error;
9243
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse)) : void 0, (result) => {
9244
+ if (revalidateOnSuccess && affectedItems.length > 0) invalidateItem(payloadToUse);
9245
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
9246
+ }, _debounce, blockWindowClose ?? void 0);
9293
9247
  storeEvents.emit("mutationEnd", {
9294
9248
  mutationId,
9295
9249
  items: affectedItems,
@@ -9298,31 +9252,20 @@ function createCollectionStore(storeOptions) {
9298
9252
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
9299
9253
  return result;
9300
9254
  }
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
9325
- });
9255
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9256
+ invalidateItem(() => true, "lowPriority");
9257
+ }, () => {
9258
+ invalidateItem(() => true, "realtimeUpdate");
9259
+ }, () => {
9260
+ for (const scheduler of batchKeySchedulers.values()) scheduler.reevaluateDelayedRTU();
9261
+ for (const scheduler of perItemSchedulers.values()) scheduler.reevaluateDelayedRTU();
9262
+ }, import.meta.env.DEV ? {
9263
+ debugLogger: storeManager.debugLogger,
9264
+ storeId: id,
9265
+ storeType: "collection"
9266
+ } : void 0);
9267
+ const { enforceCacheLimits } = createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup);
9268
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
9326
9269
  function scheduleCacheLimitEnforcement() {
9327
9270
  cacheLimitEnforcementScheduler.schedule();
9328
9271
  }
@@ -9358,7 +9301,6 @@ function createCollectionStore(storeOptions) {
9358
9301
  clearOfflineOverlays();
9359
9302
  itemCacheRuntime.clearAll();
9360
9303
  cacheLimitEnforcementScheduler.cancel();
9361
- browserTabsPriority.reset();
9362
9304
  persistence?.dispose();
9363
9305
  persistence?.clear();
9364
9306
  store.setState(persistence?.createInitialState({}) ?? {});
@@ -9381,7 +9323,6 @@ function createCollectionStore(storeOptions) {
9381
9323
  itemCacheRuntime.clearAll();
9382
9324
  cacheLimitEnforcementScheduler.cancel();
9383
9325
  browserTabsSync.close();
9384
- browserTabsPriority.close();
9385
9326
  focusLifecycle.dispose();
9386
9327
  persistence?.dispose();
9387
9328
  offlineController?.dispose();
@@ -9709,18 +9650,9 @@ function createDocumentStore(storeOptions) {
9709
9650
  let initialStatus = "idle";
9710
9651
  let initialError = null;
9711
9652
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
9712
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
9713
- storeManager,
9714
- storeName: id,
9715
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
9716
- });
9653
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
9717
9654
  const getSessionKeyBase = storeManager.getSessionKey;
9718
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
9719
- storeManager,
9720
- storeName: id,
9721
- offlineSession: resolvedOfflineSession,
9722
- getSessionKey: getSessionKeyBase
9723
- });
9655
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
9724
9656
  const errorNormalizer = storeManager.errorNormalizer;
9725
9657
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
9726
9658
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -9733,7 +9665,8 @@ function createDocumentStore(storeOptions) {
9733
9665
  ...persistentStorageConfig.offline,
9734
9666
  session: resolvedOfflineSessionForPersistentStorage
9735
9667
  } : void 0,
9736
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9668
+ debugLogger: storeManager.debugLogger,
9669
+ logger: storeManager.logger,
9737
9670
  getSessionKey: getSessionKeyForRuntime,
9738
9671
  storeName: id
9739
9672
  }) : null;
@@ -9743,55 +9676,39 @@ function createDocumentStore(storeOptions) {
9743
9676
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_DOCUMENT_OFFLINE_OPERATIONS);
9744
9677
  if (import.meta.env.DEV) assertDocumentOfflineOperations(__LEGIT_CAST__(resolvedOfflineOperations));
9745
9678
  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
- }
9679
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "document", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
9680
+ getEntityRefs: () => [{
9681
+ entityKey: DOC_TARGET_KEY,
9682
+ entityKind: "document"
9683
+ }],
9684
+ normalizeEntityRefs: () => [{
9685
+ entityKey: DOC_TARGET_KEY,
9686
+ entityKind: "document"
9687
+ }],
9688
+ getProtectedCacheKeys: () => {
9689
+ const sessionKey = getSessionKeyForRuntime();
9690
+ if (sessionKey === false) return [];
9691
+ return [createProtectedStorageKey(sessionKey, id, "document", "d", resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage")];
9692
+ },
9693
+ applyPendingEntity: ({ pendingEntity }) => {
9694
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
9695
+ updateState((draft) => Object.assign(draft, pendingEntity));
9696
+ },
9697
+ reconcileTempEntity: ({ reconciliation }) => {
9698
+ if (!reconciliation.finalData || typeof reconciliation.finalData !== "object") return;
9699
+ updateState((draft) => Object.assign(draft, reconciliation.finalData));
9700
+ },
9701
+ captureQueuedMutationOverlays: ({ sessionKey }) => {
9702
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9703
+ offlineOverlayStore.setState({ data: klona(store.state.data) });
9704
+ },
9705
+ syncEntityOverlays: ({ entities, sessionKey }) => {
9706
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9707
+ if (!entities.some((entity) => {
9708
+ return entity.entityKey === DOC_TARGET_KEY;
9709
+ })) offlineOverlayStore.setState(null);
9793
9710
  }
9794
- }) : null;
9711
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
9795
9712
  const store = new Store({
9796
9713
  debugName: id,
9797
9714
  state: () => persistence?.createInitialState({
@@ -9849,10 +9766,7 @@ function createDocumentStore(storeOptions) {
9849
9766
  }
9850
9767
  runWithoutBroadcast(() => {
9851
9768
  store.setPartialState({
9852
- data: reusePrevIfEqual({
9853
- prev: store.state.data,
9854
- current: message.data
9855
- }),
9769
+ data: reusePrevIfEqual(store.state.data, message.data),
9856
9770
  error: null,
9857
9771
  status: "success",
9858
9772
  refetchOnMount: false
@@ -9865,10 +9779,6 @@ function createDocumentStore(storeOptions) {
9865
9779
  return message.consistency === "confirmed" && scheduler.isMutationInProgress(DOC_REQUEST_ID);
9866
9780
  }
9867
9781
  function handleRemoteMessage(message) {
9868
- if (message.kind === "tab-status") {
9869
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
9870
- return;
9871
- }
9872
9782
  if (message.kind === "fetch-start") {
9873
9783
  if (!hasLocalDocumentState()) return;
9874
9784
  scheduler.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -9888,21 +9798,16 @@ function createDocumentStore(storeOptions) {
9888
9798
  }
9889
9799
  applyRemoteDocumentSnapshot(message, candidateVersion);
9890
9800
  }
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,
9801
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
9902
9802
  getWindowIsFocused,
9903
9803
  onWindowFocusChange: testOptions?.onWindowFocusChange,
9804
+ transportFactory: testOptions?.browserTabsTransportFactory,
9904
9805
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
9905
9806
  });
9807
+ const browserTabsSync = createBrowserTabsCoordinator("document", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
9808
+ lastDocumentSyncVersion = void 0;
9809
+ clearOfflineOverlay();
9810
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
9906
9811
  async function executeFetch(fetchCtx) {
9907
9812
  const currentStatus = store.state.status;
9908
9813
  const wasLoadedBeforeFetch = currentStatus === "success";
@@ -9912,10 +9817,7 @@ function createDocumentStore(storeOptions) {
9912
9817
  refetchOnMount: false
9913
9818
  }, { action: currentStatus === "success" ? "fetch-start-refetching" : "fetch-start-loading" });
9914
9819
  try {
9915
- const result = await runOfflineAwareFetch({
9916
- controller: offlineController,
9917
- fetcher: () => fetchFn(fetchCtx.signal)
9918
- });
9820
+ const result = await runOfflineAwareFetch(offlineController, () => fetchFn(fetchCtx.signal));
9919
9821
  if (!result.ok) {
9920
9822
  if (result.offline) {
9921
9823
  store.setPartialState(wasLoadedBeforeFetch ? {
@@ -9932,10 +9834,7 @@ function createDocumentStore(storeOptions) {
9932
9834
  const data = result.data;
9933
9835
  if (fetchCtx.shouldAbort()) return false;
9934
9836
  store.setPartialState({
9935
- data: reusePrevIfEqual({
9936
- prev: store.state.data,
9937
- current: data
9938
- }),
9837
+ data: reusePrevIfEqual(store.state.data, data),
9939
9838
  status: "success"
9940
9839
  }, { action: "fetch-success" });
9941
9840
  return true;
@@ -9987,19 +9886,17 @@ function createDocumentStore(storeOptions) {
9987
9886
  usesRealTimeUpdates
9988
9887
  });
9989
9888
  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
- }
10002
- });
9889
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9890
+ invalidateData("lowPriority");
9891
+ }, () => {
9892
+ invalidateData("realtimeUpdate");
9893
+ }, () => {
9894
+ scheduler.reevaluateDelayedRTU();
9895
+ }, import.meta.env.DEV ? {
9896
+ debugLogger: storeManager.debugLogger,
9897
+ storeId: id,
9898
+ storeType: "document"
9899
+ } : void 0);
10003
9900
  persistence?.attach(store);
10004
9901
  initializeOfflineStoreController(offlineController);
10005
9902
  function scheduleFetch(fetchType, options) {
@@ -10085,7 +9982,6 @@ function createDocumentStore(storeOptions) {
10085
9982
  scheduler.reset();
10086
9983
  lastDocumentSyncVersion = void 0;
10087
9984
  clearOfflineOverlay();
10088
- browserTabsPriority.reset();
10089
9985
  persistence?.dispose();
10090
9986
  persistence?.clear();
10091
9987
  store.setState({
@@ -10106,7 +10002,6 @@ function createDocumentStore(storeOptions) {
10106
10002
  lastDocumentSyncVersion = void 0;
10107
10003
  clearOfflineOverlay();
10108
10004
  browserTabsSync.close();
10109
- browserTabsPriority.close();
10110
10005
  focusLifecycle.dispose();
10111
10006
  persistence?.dispose();
10112
10007
  offlineController?.dispose();
@@ -10123,32 +10018,19 @@ function createDocumentStore(storeOptions) {
10123
10018
  updateState,
10124
10019
  currentState: store.state.data
10125
10020
  }));
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
- });
10021
+ const result = await performMutationWithLifecycle(startMutation, offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
10022
+ kind: "online",
10023
+ data: await directMutation()
10024
+ }), (exception) => {
10025
+ if (optimisticUpdate) runWithBroadcastConsistency("confirmed", () => {
10026
+ store.setKey("data", optimisticRollbackSnapshot ?? null, { action: "rollback-mutation-error" });
10027
+ publishDocumentSnapshot();
10028
+ });
10029
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
10030
+ return toStoreMutationError(exception, errorNormalizer);
10031
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data)) : void 0, (result) => {
10032
+ if (revalidateOnSuccess && result.kind === "online") invalidateData();
10033
+ }, debounce, blockWindowClose ?? void 0);
10152
10034
  storeEvents.emit("mutationEnd", {
10153
10035
  mutationId,
10154
10036
  status: result.ok ? "success" : result.error === mutationSkipped ? "skipped" : "error"
@@ -10221,16 +10103,7 @@ function createDocumentStore(storeOptions) {
10221
10103
  }
10222
10104
  if (disabled) return;
10223
10105
  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);
10106
+ 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
10107
  })();
10235
10108
  return () => {
10236
10109
  effectState.cancelled = true;
@@ -10370,7 +10243,7 @@ function toItemState(persisted, dataSchema, shouldIgnoreItem) {
10370
10243
  const validated = parsePersistedStoreData(persisted.data, dataSchema);
10371
10244
  if (validated === null) return null;
10372
10245
  if (shouldIgnoreItem(persisted.payload)) return null;
10373
- const loadedFields = Array.isArray(persisted.loadedFields) ? Array.from(new Set(persisted.loadedFields)).sort() : Object.keys(validated).sort();
10246
+ const loadedFields = persisted.loadedFields === "*" ? "*" : Array.isArray(persisted.loadedFields) ? Array.from(new Set(persisted.loadedFields)).sort() : void 0;
10374
10247
  return {
10375
10248
  item: validated,
10376
10249
  itemQuery: {
@@ -10397,14 +10270,8 @@ function readManifestGroupMeta(meta) {
10397
10270
  function setupListQueryPersistence(config, options = {}) {
10398
10271
  assertValidPersistentStoreName(config.storeName);
10399
10272
  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
- });
10273
+ const defaultMaxItemBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.item");
10274
+ const defaultMaxQueryBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.query");
10408
10275
  const maxItemBytes = config.maxItemBytes ?? defaultMaxItemBytes;
10409
10276
  const maxQueryBytes = config.maxQueryBytes ?? defaultMaxQueryBytes;
10410
10277
  const maxQuerySize = config.maxQuerySize ?? DEFAULT_MAX_QUERY_SIZE;
@@ -10431,7 +10298,7 @@ function setupListQueryPersistence(config, options = {}) {
10431
10298
  deserialize: (value, metadata) => typeof value === "object" && value !== null && "d" in value && ("p" in value || metadata?.p !== void 0) ? parsePersistedListQueryItemData({
10432
10299
  data: value.d,
10433
10300
  payload: "p" in value ? value.p : metadata?.p,
10434
- ..."lf" in value && Array.isArray(value.lf) ? { loadedFields: value.lf } : {}
10301
+ ..."lf" in value && (Array.isArray(value.lf) || value.lf === "*") ? { loadedFields: value.lf } : {}
10435
10302
  }, config.itemPayloadSchema, dataSchema) : null
10436
10303
  };
10437
10304
  const asyncItemStorageValueCodec = {
@@ -10439,7 +10306,7 @@ function setupListQueryPersistence(config, options = {}) {
10439
10306
  deserialize: (value, metadata) => metadata?.p !== void 0 ? parsePersistedListQueryItemData({
10440
10307
  data: value,
10441
10308
  payload: metadata.p,
10442
- ...Array.isArray(metadata.f) ? { loadedFields: metadata.f } : {}
10309
+ ...metadata.f !== void 0 ? { loadedFields: metadata.f } : {}
10443
10310
  }, config.itemPayloadSchema, dataSchema) : null
10444
10311
  };
10445
10312
  const queryStorageValueCodec = {
@@ -10467,7 +10334,7 @@ function setupListQueryPersistence(config, options = {}) {
10467
10334
  }, {
10468
10335
  asyncValueCodec: asyncItemStorageValueCodec,
10469
10336
  getManifestMeta: (data) => ({
10470
- ...Array.isArray(data.loadedFields) ? { f: data.loadedFields } : {},
10337
+ ...data.loadedFields !== void 0 ? { f: data.loadedFields } : {},
10471
10338
  p: data.payload
10472
10339
  }),
10473
10340
  valueCodec: itemStorageValueCodec
@@ -10483,6 +10350,45 @@ function setupListQueryPersistence(config, options = {}) {
10483
10350
  p: data.payload
10484
10351
  })
10485
10352
  });
10353
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
10354
+ function logQueryByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10355
+ const logger = config.logger;
10356
+ if (!logger) return;
10357
+ const evictedEntries = totalEntries - keptKeys.size;
10358
+ if (evictedEntries === 0) return;
10359
+ logPersistentStorageQuotaCleanup({
10360
+ adapter: quotaCleanupAdapter,
10361
+ logger,
10362
+ evictedEntries,
10363
+ keptEntries: keptKeys.size,
10364
+ maxBytes: maxQueryBytes,
10365
+ namespaceKind: "listQuery.query",
10366
+ phase,
10367
+ quota: "maxQueryBytes",
10368
+ storeName: config.storeName,
10369
+ totalEntries,
10370
+ unprotectedBytes
10371
+ });
10372
+ }
10373
+ function logItemByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10374
+ const logger = config.logger;
10375
+ if (!logger) return;
10376
+ const evictedEntries = totalEntries - keptKeys.size;
10377
+ if (evictedEntries === 0) return;
10378
+ logPersistentStorageQuotaCleanup({
10379
+ adapter: quotaCleanupAdapter,
10380
+ logger,
10381
+ evictedEntries,
10382
+ keptEntries: keptKeys.size,
10383
+ maxBytes: maxItemBytes,
10384
+ namespaceKind: "listQuery.item",
10385
+ phase,
10386
+ quota: "maxItemBytes",
10387
+ storeName: config.storeName,
10388
+ totalEntries,
10389
+ unprotectedBytes
10390
+ });
10391
+ }
10486
10392
  function getAsyncItemNamespaceScope() {
10487
10393
  if (asyncStorageAdapter === null) return null;
10488
10394
  const sessionKey = config.getSessionKey();
@@ -10507,38 +10413,18 @@ function setupListQueryPersistence(config, options = {}) {
10507
10413
  const asyncItemNamespaceScope = getAsyncItemNamespaceScope();
10508
10414
  if (asyncItemNamespaceScope === null) return JSON.stringify(args.value).length;
10509
10415
  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
- });
10416
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, args.nextCustomMetadata, args.protectedKeysSnapshotSet, asyncItemNamespaceScope, args.itemKey);
10417
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10522
10418
  }
10523
10419
  function estimateAsyncQueryEntrySizeBytes(args) {
10524
10420
  const asyncQueryNamespaceScope = getAsyncQueryNamespaceScope();
10525
10421
  if (asyncQueryNamespaceScope === null) return JSON.stringify(args.value).length;
10526
10422
  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
- });
10423
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, {
10424
+ ...args.value.hasMore ? { h: true } : {},
10425
+ p: args.value.payload
10426
+ }, args.protectedKeysSnapshotSet, asyncQueryNamespaceScope, args.queryKey);
10427
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10542
10428
  }
10543
10429
  let storeRef = null;
10544
10430
  let unsubscribe = null;
@@ -10553,6 +10439,8 @@ function setupListQueryPersistence(config, options = {}) {
10553
10439
  const querySizeBytesByKey = /* @__PURE__ */ new Map();
10554
10440
  const hydratedPersistedItemKeys = /* @__PURE__ */ new Set();
10555
10441
  const hydratedPersistedQueryKeys = /* @__PURE__ */ new Set();
10442
+ const budgetEvictedItemRecency = /* @__PURE__ */ new Map();
10443
+ const budgetEvictedQueryRecency = /* @__PURE__ */ new Map();
10556
10444
  const syncHydrationItemMissCache = createTimedKeySet();
10557
10445
  const syncHydrationQueryMissCache = createTimedKeySet();
10558
10446
  let knownPersistedItemKeys = null;
@@ -10870,13 +10758,42 @@ function setupListQueryPersistence(config, options = {}) {
10870
10758
  querySizeBytesByKey.delete(queryKey);
10871
10759
  knownPersistedQueryKeys?.delete(queryKey);
10872
10760
  }
10761
+ /**
10762
+ * Resolves the recency an in-state entry without persisted metadata should
10763
+ * compete with in the byte budget. Previously budget-evicted entries keep
10764
+ * their remembered (stale) recency while their content is unchanged, so they
10765
+ * deterministically lose again instead of churning back into storage; a
10766
+ * changed snapshot means the entry was genuinely refetched and counts as
10767
+ * freshly accessed.
10768
+ */
10769
+ function getBudgetEvictedLastAccessAt(memory, key, value, fallback) {
10770
+ const remembered = memory.get(key);
10771
+ if (remembered === void 0) return fallback;
10772
+ if (remembered.snapshot !== JSON.stringify(value)) {
10773
+ memory.delete(key);
10774
+ return fallback;
10775
+ }
10776
+ return remembered.lastAccessAt;
10777
+ }
10778
+ /**
10779
+ * Remembers an entry evicted by the byte budget while it is still in state,
10780
+ * so later flushes don't re-persist it as if it were freshly accessed (see
10781
+ * budgetEvictedQueryRecency / budgetEvictedItemRecency).
10782
+ */
10783
+ function rememberBudgetEvictedEntry(memory, key, lastAccessAt, snapshot, isInState) {
10784
+ if (!isInState || snapshot === void 0) return;
10785
+ memory.set(key, {
10786
+ lastAccessAt,
10787
+ snapshot
10788
+ });
10789
+ }
10873
10790
  function materializeHydratedItemState(itemKey, itemState) {
10874
10791
  if (!storeRef) return;
10875
10792
  suppressedPersistedStateFlushes++;
10876
10793
  storeRef.produceState((draft) => {
10877
10794
  draft.items[itemKey] = itemState.item;
10878
10795
  draft.itemQueries[itemKey] = itemState.itemQuery;
10879
- draft.itemLoadedFields[itemKey] = itemState.loadedFields;
10796
+ if (itemState.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = itemState.loadedFields;
10880
10797
  });
10881
10798
  }
10882
10799
  function materializeHydratedQueryState(queryKey, query) {
@@ -11093,8 +11010,7 @@ function setupListQueryPersistence(config, options = {}) {
11093
11010
  if (!storeRef) return false;
11094
11011
  const existingItemQuery = storeRef.state.itemQueries[itemKey];
11095
11012
  const existingItem = storeRef.state.items[itemKey];
11096
- const existingLoadedFields = storeRef.state.itemLoadedFields[itemKey];
11097
- if (existingItemQuery !== void 0 && existingItem !== void 0 && existingLoadedFields !== void 0) return existingItemQuery !== null;
11013
+ if (existingItemQuery !== void 0 && existingItem !== void 0) return existingItemQuery !== null;
11098
11014
  if (existingItemQuery === null) return false;
11099
11015
  if (localStorageAdapter !== null) {
11100
11016
  const itemState = readHydratedItem(itemKey);
@@ -11119,8 +11035,7 @@ function setupListQueryPersistence(config, options = {}) {
11119
11035
  for (const itemKey of [...new Set(itemKeys)]) {
11120
11036
  const existingItemQuery = storeRef.state.itemQueries[itemKey];
11121
11037
  const existingItem = storeRef.state.items[itemKey];
11122
- const existingLoadedFields = storeRef.state.itemLoadedFields[itemKey];
11123
- if (existingItemQuery !== void 0 && existingItem !== void 0 && existingLoadedFields !== void 0) {
11038
+ if (existingItemQuery !== void 0 && existingItem !== void 0) {
11124
11039
  resultsByKey.set(itemKey, Promise.resolve(existingItemQuery !== null));
11125
11040
  continue;
11126
11041
  }
@@ -11288,17 +11203,13 @@ function setupListQueryPersistence(config, options = {}) {
11288
11203
  };
11289
11204
  });
11290
11205
  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
- });
11206
+ const { keptKeys: keptQueryKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11207
+ logQueryByteBudgetCleanup("maintenance", filteredEntries.length, keptQueryKeys, unprotectedBytes);
11300
11208
  await Promise.all(filteredEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11301
- for (const { queryKey } of filteredEntries) if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11209
+ for (const { queryKey, lastAccessAt } of filteredEntries) if (!keptQueryKeys.has(queryKey)) {
11210
+ rememberBudgetEvictedEntry(budgetEvictedQueryRecency, queryKey, lastAccessAt, querySnapshotByKey.get(queryKey), storeRef !== null && Object.hasOwn(storeRef.state.queries, queryKey));
11211
+ forgetPersistedQuery(queryKey);
11212
+ }
11302
11213
  knownPersistedQueryKeys = keptQueryKeys;
11303
11214
  return {
11304
11215
  keptQueryKeys,
@@ -11320,19 +11231,15 @@ function setupListQueryPersistence(config, options = {}) {
11320
11231
  });
11321
11232
  }
11322
11233
  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
- });
11234
+ const { keptKeys: keptQueryKeys, unprotectedBytes: queryUnprotectedBytes } = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
11235
+ logQueryByteBudgetCleanup("maintenance", validEntries.length, keptQueryKeys, queryUnprotectedBytes);
11332
11236
  await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
11333
11237
  for (const entry of validEntries) {
11334
11238
  const { queryKey } = entry;
11335
- if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11239
+ if (!keptQueryKeys.has(queryKey)) {
11240
+ rememberBudgetEvictedEntry(budgetEvictedQueryRecency, queryKey, entry.lastAccessAt, querySnapshotByKey.get(queryKey), storeRef !== null && Object.hasOwn(storeRef.state.queries, queryKey));
11241
+ forgetPersistedQuery(queryKey);
11242
+ }
11336
11243
  }
11337
11244
  knownPersistedQueryKeys = keptQueryKeys;
11338
11245
  return {
@@ -11367,21 +11274,17 @@ function setupListQueryPersistence(config, options = {}) {
11367
11274
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11368
11275
  }
11369
11276
  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
- });
11277
+ const { keptKeys: keptItemKeys, unprotectedBytes } = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11278
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11379
11279
  const evictedItemKeys = /* @__PURE__ */ new Set();
11380
11280
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11381
11281
  evictedItemKeys.add(itemKey);
11382
11282
  return itemNamespace.remove(itemKey);
11383
11283
  }));
11384
- for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11284
+ for (const { itemKey, lastAccessAt } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) {
11285
+ rememberBudgetEvictedEntry(budgetEvictedItemRecency, itemKey, lastAccessAt, itemSnapshotByKey.get(itemKey), storeRef !== null && storeRef.state.items[itemKey] != null);
11286
+ forgetPersistedItem(itemKey);
11287
+ }
11385
11288
  knownPersistedItemKeys = keptItemKeys;
11386
11289
  if (evictedItemKeys.size === 0 || keptQueryKeys.size === 0) return;
11387
11290
  const queryEntries = managedQueryEntriesByKey ? [...managedQueryEntriesByKey.values()].filter(({ queryKey }) => keptQueryKeys.has(queryKey)) : filterAndMap([...keptQueryKeys], (queryKey) => {
@@ -11425,17 +11328,13 @@ function setupListQueryPersistence(config, options = {}) {
11425
11328
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11426
11329
  }
11427
11330
  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
- });
11331
+ const { keptKeys: keptItemKeys, unprotectedBytes } = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11332
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11437
11333
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => itemNamespace.remove(itemKey)));
11438
- for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11334
+ for (const { itemKey, lastAccessAt } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) {
11335
+ rememberBudgetEvictedEntry(budgetEvictedItemRecency, itemKey, lastAccessAt, itemSnapshotByKey.get(itemKey), storeRef !== null && storeRef.state.items[itemKey] != null);
11336
+ forgetPersistedItem(itemKey);
11337
+ }
11439
11338
  knownPersistedItemKeys = keptItemKeys;
11440
11339
  }
11441
11340
  async function flushPersistedState() {
@@ -11504,13 +11403,20 @@ function setupListQueryPersistence(config, options = {}) {
11504
11403
  }
11505
11404
  const limitedQuery = limitPersistedQueryItems(queryItemsToPersist, query.hasMore, maxQuerySize);
11506
11405
  for (const itemKey of limitedQuery.itemKeys) persistedQueryItemKeys.add(itemKey);
11507
- nextQueryKeys.add(queryKey);
11508
11406
  const nextValue = {
11509
11407
  payload: query.payload,
11510
11408
  items: limitedQuery.itemKeys,
11511
11409
  hasMore: limitedQuery.hasMore
11512
11410
  };
11513
11411
  const nextSnapshot = JSON.stringify(nextValue);
11412
+ if (!previousKnownLocalQueryKeys.has(queryKey)) {
11413
+ const evictedRecency = budgetEvictedQueryRecency.get(queryKey);
11414
+ if (evictedRecency !== void 0) {
11415
+ if (evictedRecency.snapshot === nextSnapshot) continue;
11416
+ budgetEvictedQueryRecency.delete(queryKey);
11417
+ }
11418
+ }
11419
+ nextQueryKeys.add(queryKey);
11514
11420
  if (querySnapshotByKey.get(queryKey) === nextSnapshot && previousKnownLocalQueryKeys.has(queryKey)) continue;
11515
11421
  querySnapshotByKey.set(queryKey, nextSnapshot);
11516
11422
  if (localStorageAdapter === null) querySizeBytesByKey.set(queryKey, estimateAsyncQueryEntrySizeBytes({
@@ -11529,11 +11435,12 @@ function setupListQueryPersistence(config, options = {}) {
11529
11435
  removedQueryKeys.add(queryKey);
11530
11436
  }
11531
11437
  for (const [itemKey, item] of itemEntries) {
11438
+ const hasItemInState = Object.hasOwn(state.items, itemKey);
11532
11439
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
11533
11440
  const hasLoadedFieldsInState = Object.hasOwn(state.itemLoadedFields, itemKey);
11534
11441
  const hydratedItem = hasItemQueryInState && hasLoadedFieldsInState ? void 0 : readHydratedItem(itemKey);
11535
11442
  const itemQuery = hasItemQueryInState ? state.itemQueries[itemKey] : hydratedItem?.itemQuery;
11536
- const loadedFields = hasLoadedFieldsInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11443
+ const loadedFields = hasItemInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11537
11444
  if (item === null || itemQuery == null) {
11538
11445
  if (previousKnownLocalItemKeys.has(itemKey)) {
11539
11446
  tasks.push(itemNamespace.remove(itemKey));
@@ -11570,6 +11477,16 @@ function setupListQueryPersistence(config, options = {}) {
11570
11477
  loadedFields
11571
11478
  };
11572
11479
  const nextSnapshot = JSON.stringify(nextValue);
11480
+ if (!previousKnownLocalItemKeys.has(itemKey)) {
11481
+ const evictedRecency = budgetEvictedItemRecency.get(itemKey);
11482
+ if (evictedRecency !== void 0) {
11483
+ if (evictedRecency.snapshot === nextSnapshot) {
11484
+ nextItemKeys.delete(itemKey);
11485
+ continue;
11486
+ }
11487
+ budgetEvictedItemRecency.delete(itemKey);
11488
+ }
11489
+ }
11573
11490
  if (itemSnapshotByKey.get(itemKey) === nextSnapshot && previousKnownLocalItemKeys.has(itemKey)) continue;
11574
11491
  itemSnapshotByKey.set(itemKey, nextSnapshot);
11575
11492
  if (localStorageAdapter === null) itemSizeBytesByKey.set(itemKey, estimateAsyncItemEntrySizeBytes({
@@ -11593,6 +11510,10 @@ function setupListQueryPersistence(config, options = {}) {
11593
11510
  forgetPersistedItem(itemKey);
11594
11511
  removedItemKeys.add(itemKey);
11595
11512
  }
11513
+ if (removedQueryKeys.size > 0) budgetEvictedQueryRecency.clear();
11514
+ if (removedItemKeys.size > 0) budgetEvictedItemRecency.clear();
11515
+ for (const queryKey of budgetEvictedQueryRecency.keys()) if (!Object.hasOwn(state.queries, queryKey)) budgetEvictedQueryRecency.delete(queryKey);
11516
+ for (const itemKey of budgetEvictedItemRecency.keys()) if (state.items[itemKey] == null) budgetEvictedItemRecency.delete(itemKey);
11596
11517
  await Promise.all(tasks);
11597
11518
  knownPersistedItemKeys = new Set(previousItemKeys);
11598
11519
  for (const itemKey of removedItemKeys) knownPersistedItemKeys.delete(itemKey);
@@ -11603,7 +11524,7 @@ function setupListQueryPersistence(config, options = {}) {
11603
11524
  if (localStorageAdapter !== null) {
11604
11525
  const nextKnownPersistedItemBytes = getKnownPersistedItemBytes(knownPersistedItemKeys);
11605
11526
  const nextKnownPersistedQueryBytes = getKnownPersistedQueryBytes(knownPersistedQueryKeys);
11606
- if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance({ forceManifestKeys: [maintenanceCallbackKey] });
11527
+ if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance([maintenanceCallbackKey]);
11607
11528
  return;
11608
11529
  }
11609
11530
  const sessionKey = config.getSessionKey();
@@ -11676,17 +11597,21 @@ function setupListQueryPersistence(config, options = {}) {
11676
11597
  sizeBytes: rememberQueryMetadataSize(entry.key, entry.sizeBytes)
11677
11598
  });
11678
11599
  }
11600
+ const inStateQueryLastAccessAt = /* @__PURE__ */ new Map();
11679
11601
  for (const [queryKey, queryData] of finalQueryDataByKey) {
11602
+ const existingMetadata = metadataByKey.get(queryKey);
11603
+ const lastAccessAt = existingMetadata?.lastAccessAt ?? getBudgetEvictedLastAccessAt(budgetEvictedQueryRecency, queryKey, queryData, commitTimestamp);
11604
+ inStateQueryLastAccessAt.set(queryKey, lastAccessAt);
11680
11605
  const sizeBytes = estimateAsyncQueryEntrySizeBytes({
11681
- currentCustomMetadata: metadataByKey.get(queryKey)?.customMetadata,
11682
- lastAccessAt: commitTimestamp,
11606
+ currentCustomMetadata: existingMetadata?.customMetadata,
11607
+ lastAccessAt,
11683
11608
  protectedKeysSnapshotSet: protectedRefs,
11684
11609
  queryKey,
11685
11610
  value: queryData
11686
11611
  });
11687
11612
  finalQuerySizeBytesByKey.set(queryKey, sizeBytes);
11688
11613
  candidateEntries.push({
11689
- lastAccessAt: commitTimestamp,
11614
+ lastAccessAt,
11690
11615
  offlineProtected: protectedQueryKeys.has(queryKey) || protectedRefs?.has(serializeProtectedRef$1({
11691
11616
  key: queryKey,
11692
11617
  kind: "listQuery.query",
@@ -11697,30 +11622,35 @@ function setupListQueryPersistence(config, options = {}) {
11697
11622
  sizeBytes
11698
11623
  });
11699
11624
  }
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
- });
11625
+ const { keptKeys: keptQueryKeys, unprotectedBytes: queryUnprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11626
+ logQueryByteBudgetCleanup("flush", candidateEntries.length, keptQueryKeys, queryUnprotectedBytes);
11709
11627
  finalPersistedQueryKeys.clear();
11710
- for (const queryKey of keptQueryKeys) finalPersistedQueryKeys.add(queryKey);
11628
+ for (const queryKey of keptQueryKeys) {
11629
+ finalPersistedQueryKeys.add(queryKey);
11630
+ budgetEvictedQueryRecency.delete(queryKey);
11631
+ }
11632
+ for (const queryKey of budgetEvictedQueryRecency.keys()) if (!finalQueryDataByKey.has(queryKey)) budgetEvictedQueryRecency.delete(queryKey);
11711
11633
  const evictedQueryKeys = [];
11712
11634
  for (const queryKey of finalQueryDataByKey.keys()) if (!finalPersistedQueryKeys.has(queryKey)) evictedQueryKeys.push(queryKey);
11713
- for (const queryKey of evictedQueryKeys) finalQueryDataByKey.delete(queryKey);
11635
+ for (const queryKey of evictedQueryKeys) {
11636
+ const queryData = finalQueryDataByKey.get(queryKey);
11637
+ if (queryData !== void 0) budgetEvictedQueryRecency.set(queryKey, {
11638
+ lastAccessAt: inStateQueryLastAccessAt.get(queryKey) ?? commitTimestamp,
11639
+ snapshot: JSON.stringify(queryData)
11640
+ });
11641
+ finalQueryDataByKey.delete(queryKey);
11642
+ }
11714
11643
  const persistedQueryItemKeys = /* @__PURE__ */ new Set();
11715
11644
  for (const queryData of finalQueryDataByKey.values()) for (const itemKey of queryData.items) persistedQueryItemKeys.add(itemKey);
11716
11645
  const finalItemDataByKey = /* @__PURE__ */ new Map();
11717
11646
  const finalPersistedItemKeys = new Set(previousKnownLocalItemKeys);
11718
11647
  for (const [itemKey, item] of itemEntries) {
11648
+ const hasItemInState = Object.hasOwn(state.items, itemKey);
11719
11649
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
11720
11650
  const hasLoadedFieldsInState = Object.hasOwn(state.itemLoadedFields, itemKey);
11721
11651
  const hydratedItem = hasItemQueryInState && hasLoadedFieldsInState ? void 0 : readHydratedItem(itemKey);
11722
11652
  const itemQuery = hasItemQueryInState ? state.itemQueries[itemKey] : hydratedItem?.itemQuery;
11723
- const loadedFields = hasLoadedFieldsInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11653
+ const loadedFields = hasItemInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11724
11654
  if (item === null || itemQuery == null) {
11725
11655
  if (previousKnownLocalItemKeys.has(itemKey)) finalPersistedItemKeys.delete(itemKey);
11726
11656
  continue;
@@ -11741,7 +11671,7 @@ function setupListQueryPersistence(config, options = {}) {
11741
11671
  };
11742
11672
  finalItemDataByKey.set(itemKey, {
11743
11673
  metadata: {
11744
- ...Array.isArray(loadedFields) ? { f: loadedFields } : {},
11674
+ ...loadedFields !== void 0 ? { f: loadedFields } : {},
11745
11675
  p: itemQuery.payload,
11746
11676
  ...getItemDerivedGroup ? { g: getItemDerivedGroup(item, itemQuery.payload) } : {}
11747
11677
  },
@@ -11774,12 +11704,15 @@ function setupListQueryPersistence(config, options = {}) {
11774
11704
  sizeBytes: rememberItemMetadataSize(entry.key, entry.sizeBytes)
11775
11705
  });
11776
11706
  }
11707
+ const inStateItemLastAccessAt = /* @__PURE__ */ new Map();
11777
11708
  for (const [itemKey, entry] of finalItemDataByKey) {
11778
11709
  const existingMetadata = itemMetadataByKey.get(itemKey);
11710
+ const lastAccessAt = existingMetadata?.lastAccessAt ?? getBudgetEvictedLastAccessAt(budgetEvictedItemRecency, itemKey, entry.value, itemCommitTimestamp);
11711
+ inStateItemLastAccessAt.set(itemKey, lastAccessAt);
11779
11712
  const sizeBytes = estimateAsyncItemEntrySizeBytes({
11780
11713
  currentCustomMetadata: existingMetadata?.customMetadata,
11781
11714
  itemKey,
11782
- lastAccessAt: existingMetadata?.lastAccessAt ?? itemCommitTimestamp,
11715
+ lastAccessAt,
11783
11716
  nextCustomMetadata: entry.metadata,
11784
11717
  protectedKeysSnapshotSet: protectedRefs,
11785
11718
  value: entry.value
@@ -11787,7 +11720,7 @@ function setupListQueryPersistence(config, options = {}) {
11787
11720
  finalItemSizeBytesByKey.set(itemKey, sizeBytes);
11788
11721
  itemCandidateEntries.push({
11789
11722
  itemKey,
11790
- lastAccessAt: existingMetadata?.lastAccessAt ?? itemCommitTimestamp,
11723
+ lastAccessAt,
11791
11724
  offlineProtected: protectedItemKeys.has(itemKey) || protectedRefs?.has(serializeProtectedRef$1({
11792
11725
  key: itemKey,
11793
11726
  kind: "listQuery.item",
@@ -11797,20 +11730,24 @@ function setupListQueryPersistence(config, options = {}) {
11797
11730
  sizeBytes
11798
11731
  });
11799
11732
  }
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
- });
11733
+ const { keptKeys: keptItemKeys, unprotectedBytes: itemUnprotectedBytes } = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11734
+ logItemByteBudgetCleanup("flush", itemCandidateEntries.length, keptItemKeys, itemUnprotectedBytes);
11809
11735
  finalPersistedItemKeys.clear();
11810
- for (const itemKey of keptItemKeys) finalPersistedItemKeys.add(itemKey);
11736
+ for (const itemKey of keptItemKeys) {
11737
+ finalPersistedItemKeys.add(itemKey);
11738
+ budgetEvictedItemRecency.delete(itemKey);
11739
+ }
11740
+ for (const itemKey of budgetEvictedItemRecency.keys()) if (!finalItemDataByKey.has(itemKey)) budgetEvictedItemRecency.delete(itemKey);
11811
11741
  const evictedItemKeys = [];
11812
11742
  for (const itemKey of finalItemDataByKey.keys()) if (!finalPersistedItemKeys.has(itemKey)) evictedItemKeys.push(itemKey);
11813
- for (const itemKey of evictedItemKeys) finalItemDataByKey.delete(itemKey);
11743
+ for (const itemKey of evictedItemKeys) {
11744
+ const entry = finalItemDataByKey.get(itemKey);
11745
+ if (entry !== void 0) budgetEvictedItemRecency.set(itemKey, {
11746
+ lastAccessAt: inStateItemLastAccessAt.get(itemKey) ?? itemCommitTimestamp,
11747
+ snapshot: JSON.stringify(entry.value)
11748
+ });
11749
+ finalItemDataByKey.delete(itemKey);
11750
+ }
11814
11751
  const removedQueryKeys = [...previousKnownLocalQueryKeys].filter((queryKey) => !finalPersistedQueryKeys.has(queryKey));
11815
11752
  const removedItemKeys = [...previousKnownLocalItemKeys].filter((itemKey) => !finalPersistedItemKeys.has(itemKey));
11816
11753
  const queryUpserts = /* @__PURE__ */ new Map();
@@ -11943,6 +11880,8 @@ function setupListQueryPersistence(config, options = {}) {
11943
11880
  querySnapshotByKey.clear();
11944
11881
  itemSizeBytesByKey.clear();
11945
11882
  querySizeBytesByKey.clear();
11883
+ budgetEvictedItemRecency.clear();
11884
+ budgetEvictedQueryRecency.clear();
11946
11885
  hydratedPersistedItemKeys.clear();
11947
11886
  hydratedPersistedQueryKeys.clear();
11948
11887
  syncHydrationItemMissCache.clearAll();
@@ -11968,13 +11907,63 @@ function setupListQueryPersistence(config, options = {}) {
11968
11907
  }
11969
11908
  //#endregion
11970
11909
  //#region src/listQueryStore/itemFieldUtils.ts
11971
- function fallbackItemHasRequestedFields(fallbackItemState, requestedFields) {
11972
- const loadedFields = fallbackItemState?.loadedFields ?? [];
11973
- if (requestedFields.every((field) => loadedFields.includes(field))) return true;
11910
+ function hasFullyLoadedFields(loadedFields) {
11911
+ return loadedFields === "*";
11912
+ }
11913
+ /**
11914
+ * Whether a snapshot should be treated as holding every field of the item.
11915
+ * True when the tracked `loadedFields` is the `'*'` sentinel, or when the
11916
+ * snapshot carries no field metadata but `inferFields` reports the item is
11917
+ * complete (`'*'`) — e.g. manually inserted items, offline optimistic rows, or
11918
+ * persisted fallback snapshots.
11919
+ */
11920
+ function snapshotIsFullyLoaded(loadedFields, item, inferFields) {
11921
+ if (loadedFields === "*") return true;
11922
+ if (!item) return false;
11923
+ return inferFields(item) === "*";
11924
+ }
11925
+ /**
11926
+ * Like {@link snapshotIsFullyLoaded}, but also returns `false` when the item is
11927
+ * awaiting a full ('*') re-fetch after a full invalidation. A fully-loaded
11928
+ * snapshot that was fully invalidated has its `loadedFields` reset while the
11929
+ * (now stale) item data is still present, so `inferFields` would otherwise
11930
+ * wrongly vouch for it as complete.
11931
+ */
11932
+ function snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, item, inferFields, itemsPendingFullInvalidation) {
11933
+ if (loadedFields !== "*" && itemsPendingFullInvalidation.has(itemKey)) return false;
11934
+ return snapshotIsFullyLoaded(loadedFields, item, inferFields);
11935
+ }
11936
+ /**
11937
+ * Missing requested fields for an item snapshot, letting `inferFields` vouch
11938
+ * for metadata-free item data (e.g. client-created items) — except for stale
11939
+ * fields awaiting a re-fetch after an invalidation (per-field or full), when
11940
+ * the item's stale data must not be vouched for.
11941
+ */
11942
+ function getStaleOrMissingRequestedFields(itemKey, loadedFields, item, requestedFields, inferFields, itemsPendingFullInvalidation, pendingInvalidationFields) {
11943
+ const staleRequestedFields = pendingInvalidationFields.length > 0 ? requestedFields.filter((field) => pendingInvalidationFields.includes(field)) : [];
11944
+ const missingLoadedFields = excludeLoadedFields(loadedFields, requestedFields);
11945
+ if (missingLoadedFields.length === 0) return staleRequestedFields;
11946
+ const unvouchedMissingFields = loadedFields !== "*" && itemsPendingFullInvalidation.has(itemKey) || !item ? missingLoadedFields : (() => {
11947
+ const inferredFields = inferFields(item);
11948
+ return missingLoadedFields.filter((field) => inferredFields !== "*" && !inferredFields.includes(field));
11949
+ })();
11950
+ if (staleRequestedFields.length === 0) return unvouchedMissingFields;
11951
+ const resultFields = new Set([...staleRequestedFields, ...unvouchedMissingFields]);
11952
+ return requestedFields.filter((field) => resultFields.has(field));
11953
+ }
11954
+ function fallbackItemHasRequestedFields(fallbackItemState, requestedFields, inferFields) {
11955
+ return getFallbackMissingRequestedFields(fallbackItemState, requestedFields, inferFields).length === 0;
11956
+ }
11957
+ function getFallbackMissingRequestedFields(fallbackItemState, requestedFields, inferFields) {
11958
+ const loadedFields = fallbackItemState?.loadedFields;
11959
+ if (loadedFields === "*") return [];
11960
+ const missingLoadedFields = requestedFields.filter((field) => !(loadedFields?.includes(field) ?? false));
11961
+ if (missingLoadedFields.length === 0) return [];
11974
11962
  const item = fallbackItemState?.item;
11975
- if (!item || typeof item !== "object") return false;
11976
- const itemRecord = __LEGIT_CAST__(item);
11977
- return requestedFields.every((field) => field in itemRecord && itemRecord[field] !== void 0);
11963
+ if (!item) return missingLoadedFields;
11964
+ const inferredFields = inferFields(item);
11965
+ if (inferredFields === "*") return [];
11966
+ return missingLoadedFields.filter((field) => !inferredFields.includes(field));
11978
11967
  }
11979
11968
  /**
11980
11969
  * Returns the fields from `requestedFields` that are not yet present in
@@ -11982,6 +11971,7 @@ function fallbackItemHasRequestedFields(fallbackItemState, requestedFields) {
11982
11971
  */
11983
11972
  function excludeLoadedFields(loadedFields, requestedFields) {
11984
11973
  if (!requestedFields || requestedFields.length === 0) return [];
11974
+ if (loadedFields === "*") return [];
11985
11975
  if (!loadedFields || loadedFields.length === 0) return [...requestedFields];
11986
11976
  return requestedFields.filter((field) => !loadedFields.includes(field));
11987
11977
  }
@@ -11994,15 +11984,13 @@ function excludeLoadedFields(loadedFields, requestedFields) {
11994
11984
  function applyPartialItemMerge(draft, itemKey, data, fields, partialResources) {
11995
11985
  const prev = draft.items[itemKey] ?? void 0;
11996
11986
  const merged = partialResources.mergeItems(prev, data);
11997
- draft.items[itemKey] = reusePrevIfEqual({
11998
- current: merged,
11999
- prev
12000
- });
11987
+ draft.items[itemKey] = reusePrevIfEqual(prev, merged);
12001
11988
  if (fields && fields.length > 0) {
12002
- const existingFields = draft.itemLoadedFields[itemKey] ?? [];
12003
- const fieldSet = new Set([...existingFields, ...fields]);
11989
+ const existingFields = draft.itemLoadedFields[itemKey];
11990
+ if (existingFields === "*") return merged;
11991
+ const fieldSet = new Set([...existingFields ?? [], ...fields]);
12004
11992
  draft.itemLoadedFields[itemKey] = Array.from(fieldSet).sort();
12005
- } else draft.itemLoadedFields[itemKey] = Object.keys(merged).sort();
11993
+ } else draft.itemLoadedFields[itemKey] = "*";
12006
11994
  return merged;
12007
11995
  }
12008
11996
  //#endregion
@@ -12011,10 +11999,7 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12011
11999
  const results = /* @__PURE__ */ new Map();
12012
12000
  function applyItemResult(draft, itemKey, data, fields) {
12013
12001
  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
- });
12002
+ else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12018
12003
  }
12019
12004
  function clearSatisfiedItemInvalidationFields(draft, itemKey, requestFields) {
12020
12005
  const invalidationFields = draft.itemFieldInvalidationFields[itemKey];
@@ -12057,13 +12042,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12057
12042
  payload: r.payload.payload,
12058
12043
  fields: r.payload.fields
12059
12044
  }));
12060
- const fetchResult = await runOfflineAwareFetch({
12061
- controller: offlineController,
12062
- fetcher: () => batchFetchItemFn(batchRequests, {
12063
- signal: fetchCtx.signal,
12064
- batchKey: batchKey ?? "__default__"
12065
- })
12066
- });
12045
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchItemFn(batchRequests, {
12046
+ signal: fetchCtx.signal,
12047
+ batchKey: batchKey ?? "__default__"
12048
+ }));
12067
12049
  if (!fetchResult.ok) {
12068
12050
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
12069
12051
  store.produceState((draft) => {
@@ -12139,13 +12121,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12139
12121
  }
12140
12122
  const fetchPromises = requests.map(async ({ requestId: itemKey, payload: requestData }) => {
12141
12123
  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
- });
12124
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchItemFn(klona(requestData.payload), {
12125
+ signal: fetchCtx.signal,
12126
+ fields: requestData.fields
12127
+ }));
12149
12128
  if (!fetchResult.ok) {
12150
12129
  if (fetchCtx.shouldAbort()) {
12151
12130
  results.set(itemKey, false);
@@ -12221,10 +12200,7 @@ function applyFetchedItems(draft, queryKey, items, hasMore, fields, getItemKey,
12221
12200
  if (remainingFields.length > 0) draft.itemFieldInvalidationFields[itemKey] = remainingFields;
12222
12201
  else delete draft.itemFieldInvalidationFields[itemKey];
12223
12202
  }
12224
- } else draft.items[itemKey] = reusePrevIfEqual({
12225
- current: data,
12226
- prev: draft.items[itemKey] ?? void 0
12227
- });
12203
+ } else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12228
12204
  if (!existingItemKeys.has(itemKey)) {
12229
12205
  query.items.push(itemKey);
12230
12206
  existingItemKeys.add(itemKey);
@@ -12286,13 +12262,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12286
12262
  stopOnError: true,
12287
12263
  rejectPendingOnError: true
12288
12264
  });
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) => {
12265
+ const chunkResultPromises = chunks.map((chunk) => queue.resultifyAdd(() => runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, chunk.offset, chunk.limit, {
12266
+ signal: fetchCtx.signal,
12267
+ fields
12268
+ })).then((result) => {
12296
12269
  if (!result.ok) throw result.offline ? offlineConnectivityError : result.error;
12297
12270
  return result.data;
12298
12271
  })));
@@ -12301,13 +12274,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12301
12274
  const lastChunk = successResults[successResults.length - 1];
12302
12275
  hasMore = lastChunk ? lastChunk.hasMore : false;
12303
12276
  } else {
12304
- const fetchResult = await runOfflineAwareFetch({
12305
- controller: offlineController,
12306
- fetcher: () => normalizedFetchListFn(payload, offset, limit, {
12307
- signal: fetchCtx.signal,
12308
- fields
12309
- })
12310
- });
12277
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, offset, limit, {
12278
+ signal: fetchCtx.signal,
12279
+ fields
12280
+ }));
12311
12281
  if (!fetchResult.ok) throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
12312
12282
  const result = fetchResult.data;
12313
12283
  allItems = result.items;
@@ -12349,7 +12319,7 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12349
12319
  //#endregion
12350
12320
  //#region src/listQueryStore/createFetchApi.ts
12351
12321
  /** @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 }) {
12322
+ 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, itemPendingInvalidationFields, itemsPendingFullInvalidation) {
12353
12323
  const noFetchItemFnError = "No fetchItemFn was provided";
12354
12324
  const querySchedulers = /* @__PURE__ */ new Map();
12355
12325
  const queryInitialFetchStartTime = /* @__PURE__ */ new Map();
@@ -12760,7 +12730,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12760
12730
  const materializedState = readMaterializedItemState(itemKey);
12761
12731
  const hydratedState = persistence.readHydratedItem(itemKey);
12762
12732
  const state = materializedState ?? hydratedState;
12763
- if (!state || state.item == null || state.itemQuery == null || partialResources && fields && fields.length > 0 && !fallbackItemHasRequestedFields(state, fields)) return "skipped";
12733
+ if (!state || state.item == null || state.itemQuery == null || partialResources && fields && fields.length > 0 && !fallbackItemHasRequestedFields(state, fields, partialResources.inferFields)) return "skipped";
12764
12734
  appendedItemKeys.push(itemKey);
12765
12735
  if (!materializedState && hydratedState) appendedHydratedItems.push({
12766
12736
  itemKey,
@@ -12780,7 +12750,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12780
12750
  for (const { itemKey, state } of appendedHydratedItems) {
12781
12751
  draft.items[itemKey] = state.item;
12782
12752
  draft.itemQueries[itemKey] = state.itemQuery;
12783
- draft.itemLoadedFields[itemKey] = state.loadedFields;
12753
+ if (state.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = state.loadedFields;
12784
12754
  }
12785
12755
  }, { action: "persistent-storage-load-more" });
12786
12756
  return "triggered";
@@ -12792,10 +12762,25 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12792
12762
  return item && itemPayload ? itemDataSelector(item, itemPayload, itemKey) : false;
12793
12763
  });
12794
12764
  }
12795
- function hasStaleRequestedFields(itemKey, fields) {
12796
- const invalidationFields = store.state.itemFieldInvalidationFields[itemKey];
12797
- if (!invalidationFields || invalidationFields.length === 0) return false;
12798
- return fields.some((field) => invalidationFields.includes(field));
12765
+ /**
12766
+ * Fields of an item still awaiting an invalidation re-fetch. Reads the
12767
+ * state-level record first; when a fetch already consumed it (the record is
12768
+ * deleted before the response lands), falls back to the in-memory pending
12769
+ * list minus the fields that were re-loaded since the invalidation.
12770
+ */
12771
+ function getUnresolvedPendingInvalidationFields(itemKey) {
12772
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
12773
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
12774
+ return excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
12775
+ }
12776
+ /**
12777
+ * Whether an item snapshot is fresh enough for a require-fresh
12778
+ * (`ignoreStaleState: true`) full ('*') read: no unresolved full ('*')
12779
+ * invalidation and no fields still awaiting an invalidation re-fetch.
12780
+ */
12781
+ function itemSnapshotIsFresh(itemKey) {
12782
+ if (store.state.itemLoadedFields[itemKey] !== "*" && itemsPendingFullInvalidation.has(itemKey)) return false;
12783
+ return getUnresolvedPendingInvalidationFields(itemKey).length === 0;
12799
12784
  }
12800
12785
  async function awaitListQueryFetch(params, options = {}) {
12801
12786
  const queryKey = getQueryKey(params);
@@ -12831,7 +12816,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12831
12816
  if (!hydratedItem) continue;
12832
12817
  draft.items[itemKey] = hydratedItem.item;
12833
12818
  draft.itemQueries[itemKey] = hydratedItem.itemQuery;
12834
- draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12819
+ if (hydratedItem.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12835
12820
  }
12836
12821
  }, { action: "persistent-storage-hydrate" });
12837
12822
  }
@@ -12858,11 +12843,12 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12858
12843
  async function getQueryFromStateOrFetch(params, options = {}) {
12859
12844
  const queryKey = getQueryKey(params);
12860
12845
  const fields = normalizeFieldsOption(options.fields);
12846
+ const fullFieldsRequested = options.fields === "*";
12861
12847
  const query = getQueryStateByKey(queryKey);
12862
12848
  const includeStale = !!options.ignoreStaleState;
12863
12849
  const cachedQueryCanBeUsed = !!query?.wasLoaded && (!includeStale || query.status === "success" && !query.error && !query.refetchOnMount);
12864
12850
  if (query && cachedQueryCanBeUsed) {
12865
- if (!(partialResources && Array.isArray(fields) && fields.length > 0)) return Result.ok({
12851
+ if (!(partialResources && (Array.isArray(fields) && fields.length > 0 || fullFieldsRequested))) return Result.ok({
12866
12852
  items: getQueryItems(query, (data, itemPayload) => ({
12867
12853
  data,
12868
12854
  itemPayload
@@ -12871,8 +12857,10 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12871
12857
  });
12872
12858
  if (!query.items.some((itemKey) => {
12873
12859
  const itemState = readItemState(itemKey);
12874
- const invalidation = includeStale ? store.state.itemFieldInvalidationFields[itemKey] : void 0;
12875
- return fields.some((field) => !fallbackItemHasRequestedFields(itemState, [field]) || (invalidation?.includes(field) ?? false));
12860
+ if (fullFieldsRequested) return !snapshotIsFullyLoaded(itemState?.loadedFields, itemState?.item, partialResources.inferFields) || includeStale && !itemSnapshotIsFresh(itemKey);
12861
+ const requestedFields = Array.isArray(fields) ? fields : [];
12862
+ if (includeStale) return getStaleOrMissingRequestedFields(itemKey, itemState?.loadedFields, itemState?.item, requestedFields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).length > 0;
12863
+ return getFallbackMissingRequestedFields(itemState, requestedFields, partialResources.inferFields).length > 0;
12876
12864
  })) return Result.ok({
12877
12865
  items: getQueryItems(query, (data, itemPayload) => ({
12878
12866
  data,
@@ -12933,7 +12921,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12933
12921
  store.produceState((draft) => {
12934
12922
  draft.items[itemKey] = hydratedItem.item;
12935
12923
  draft.itemQueries[itemKey] = hydratedItem.itemQuery;
12936
- draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12924
+ if (hydratedItem.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12937
12925
  }, { action: "persistent-storage-hydrate" });
12938
12926
  }
12939
12927
  }
@@ -12955,20 +12943,19 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12955
12943
  async function getItemFromStateOrFetch(itemPayload, options = {}) {
12956
12944
  const itemKey = getItemKey(itemPayload);
12957
12945
  const fields = normalizeFieldsOption(options.fields);
12946
+ const fullFieldsRequested = options.fields === "*";
12958
12947
  const itemState = readItemState(itemKey);
12959
12948
  const item = itemState?.item;
12960
12949
  const itemQuery = itemState?.itemQuery;
12961
12950
  const includeStale = !!options.ignoreStaleState;
12962
- const needsFieldCheck = partialResources && Array.isArray(fields) && fields.length > 0;
12963
- const itemHasAllFields = !needsFieldCheck || fallbackItemHasRequestedFields(itemState, fields);
12951
+ const needsFieldCheck = partialResources && (Array.isArray(fields) && fields.length > 0 || fullFieldsRequested);
12952
+ const itemHasAllFields = !needsFieldCheck || (fullFieldsRequested ? snapshotIsFullyLoaded(itemState?.loadedFields, itemState?.item, partialResources.inferFields) : fallbackItemHasRequestedFields(itemState, Array.isArray(fields) ? fields : [], partialResources.inferFields));
12964
12953
  const itemQueryFresh = itemQuery?.status === "success" && !itemQuery.error && !itemQuery.refetchOnMount;
12965
- if (item != null && itemHasAllFields && (!includeStale || itemQueryFresh && (!needsFieldCheck || !hasStaleRequestedFields(itemKey, fields)))) return Result.ok(item);
12954
+ const staleOrMissingRequestedFields = needsFieldCheck && !fullFieldsRequested && includeStale ? getStaleOrMissingRequestedFields(itemKey, itemState?.loadedFields, item, Array.isArray(fields) ? fields : [], partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)) : void 0;
12955
+ if (item != null && itemHasAllFields && (!includeStale || itemQueryFresh && (!needsFieldCheck || (fullFieldsRequested ? itemSnapshotIsFresh(itemKey) : staleOrMissingRequestedFields?.length === 0)))) return Result.ok(item);
12966
12956
  if (!fetchItemFn) throw new Error(noFetchItemFnError);
12967
12957
  let fieldsToFetch = options.fields;
12968
- if (needsFieldCheck && item != null && itemQueryFresh) {
12969
- const invalidation = includeStale ? store.state.itemFieldInvalidationFields[itemKey] : void 0;
12970
- fieldsToFetch = fields.filter((field) => !fallbackItemHasRequestedFields(itemState, [field]) || (invalidation?.includes(field) ?? false));
12971
- }
12958
+ if (needsFieldCheck && !fullFieldsRequested && item != null && itemQueryFresh) fieldsToFetch = staleOrMissingRequestedFields ?? getFallbackMissingRequestedFields(itemState, Array.isArray(fields) ? fields : [], partialResources.inferFields);
12972
12959
  const result = await awaitItemFetch(itemPayload, {
12973
12960
  timeoutMs: options.timeoutMs,
12974
12961
  fields: fieldsToFetch
@@ -12987,6 +12974,11 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12987
12974
  itemInitialFetchStartTime.clear();
12988
12975
  itemKeyToPayload.clear();
12989
12976
  }
12977
+ function reevaluateDelayedRTUs() {
12978
+ for (const scheduler of querySchedulers.values()) scheduler.reevaluateDelayedRTU();
12979
+ for (const scheduler of batchKeySchedulers.values()) scheduler.reevaluateDelayedRTU();
12980
+ for (const scheduler of perItemSchedulers.values()) scheduler.reevaluateDelayedRTU();
12981
+ }
12990
12982
  function syncRemoteFetchStart(targetKey, requestIds, startedAt) {
12991
12983
  if (targetKey.startsWith("query:")) {
12992
12984
  const scheduler = getKnownQueryScheduler(targetKey.slice(6));
@@ -13050,7 +13042,8 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
13050
13042
  syncRemoteFetchSuccess,
13051
13043
  deleteQueryFetchResources,
13052
13044
  deleteItemFetchResources,
13053
- resetSchedulers
13045
+ resetSchedulers,
13046
+ reevaluateDelayedRTUs
13054
13047
  };
13055
13048
  }
13056
13049
  //#endregion
@@ -13066,7 +13059,7 @@ const GET_ALL = () => true;
13066
13059
  //#endregion
13067
13060
  //#region src/listQueryStore/createMutationApi.ts
13068
13061
  /** @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 }) {
13062
+ function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent, itemPendingInvalidationFields, itemsPendingFullInvalidation) {
13070
13063
  const storeEvents = evtmitter();
13071
13064
  const deferredOptimisticQueryInvalidationsStack = [];
13072
13065
  const optimisticMutationQueryContextStack = [];
@@ -13126,7 +13119,6 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13126
13119
  const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
13127
13120
  const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
13128
13121
  const itemFieldInvalidationPriorities = /* @__PURE__ */ new Map();
13129
- const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
13130
13122
  function invalidateQueryAndItems(args) {
13131
13123
  const itemPayload = args.all ? GET_ALL : args.itemPayload;
13132
13124
  const queryPayload = args.all ? GET_ALL : args.queryPayload;
@@ -13166,7 +13158,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13166
13158
  for (const { itemKey } of itemsKey) {
13167
13159
  const loadedFields = draft.itemLoadedFields[itemKey];
13168
13160
  if (!loadedFields) continue;
13169
- draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !invalidateFields.includes(f));
13161
+ if (loadedFields !== "*") draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !invalidateFields.includes(f));
13170
13162
  const existingInvalidationFields = draft.itemFieldInvalidationFields[itemKey] ?? [];
13171
13163
  draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...invalidateFields])).sort();
13172
13164
  }
@@ -13187,10 +13179,28 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13187
13179
  for (const { itemKey, payload } of itemsKey) {
13188
13180
  const item = store.state.itemQueries[itemKey];
13189
13181
  if (!item) continue;
13190
- const trackedInvalidationFields = partialResources ? Array.from(new Set([...store.state.itemLoadedFields[itemKey] ?? [], ...itemPendingInvalidationFields.get(itemKey) ?? []])).sort() : [];
13191
- const trackedInvalidationPriority = trackedInvalidationFields.length > 0 ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
13182
+ let effectiveLoadedFields = store.state.itemLoadedFields[itemKey];
13183
+ if (partialResources && effectiveLoadedFields === void 0) {
13184
+ const itemState = store.state.items[itemKey];
13185
+ if (itemState) effectiveLoadedFields = partialResources.inferFields(itemState);
13186
+ }
13187
+ const itemWasFullyLoaded = partialResources && effectiveLoadedFields === "*";
13188
+ const trackedInvalidationFields = partialResources && !itemWasFullyLoaded ? Array.from(new Set([...effectiveLoadedFields === "*" ? [] : effectiveLoadedFields ?? [], ...itemPendingInvalidationFields.get(itemKey) ?? []])).sort() : [];
13189
+ const trackedInvalidationPriority = trackedInvalidationFields.length > 0 || itemsPendingFullInvalidation.has(itemKey) ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
13192
13190
  const nextInvalidationPriority = trackedInvalidationPriority && fetchTypePriority[trackedInvalidationPriority] > fetchTypePriority[priority] ? trackedInvalidationPriority : priority;
13193
13191
  if ((item.refetchOnMount ? fetchTypePriority[item.refetchOnMount] : -1) >= fetchTypePriority[nextInvalidationPriority]) continue;
13192
+ if (itemWasFullyLoaded) {
13193
+ itemsPendingFullInvalidation.add(itemKey);
13194
+ itemPendingInvalidationFields.delete(itemKey);
13195
+ itemFieldInvalidationPriorities.set(itemKey, nextInvalidationPriority);
13196
+ } else if (trackedInvalidationFields.length > 0) {
13197
+ itemPendingInvalidationFields.set(itemKey, trackedInvalidationFields);
13198
+ itemFieldInvalidationPriorities.set(itemKey, nextInvalidationPriority);
13199
+ } else {
13200
+ itemPendingInvalidationFields.delete(itemKey);
13201
+ itemFieldInvalidationPriorities.delete(itemKey);
13202
+ }
13203
+ itemInvalidationWasTriggered.delete(itemKey);
13194
13204
  store.produceState((draft) => {
13195
13205
  const query = draft.itemQueries[itemKey];
13196
13206
  if (!query) return;
@@ -13200,14 +13210,6 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13200
13210
  delete draft.itemFieldInvalidationFields[itemKey];
13201
13211
  }
13202
13212
  }, { action: "invalidate-item" });
13203
- if (trackedInvalidationFields.length > 0) {
13204
- itemPendingInvalidationFields.set(itemKey, trackedInvalidationFields);
13205
- itemFieldInvalidationPriorities.set(itemKey, nextInvalidationPriority);
13206
- } else {
13207
- itemPendingInvalidationFields.delete(itemKey);
13208
- itemFieldInvalidationPriorities.delete(itemKey);
13209
- }
13210
- itemInvalidationWasTriggered.delete(itemKey);
13211
13213
  emitInvalidateItem({
13212
13214
  priority: nextInvalidationPriority,
13213
13215
  itemKey
@@ -13425,6 +13427,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13425
13427
  for (const { itemKey } of itemsId) {
13426
13428
  itemFieldInvalidationPriorities.delete(itemKey);
13427
13429
  itemPendingInvalidationFields.delete(itemKey);
13430
+ itemsPendingFullInvalidation.delete(itemKey);
13428
13431
  itemInvalidationWasTriggered.delete(itemKey);
13429
13432
  publishItemSnapshot(itemKey);
13430
13433
  }
@@ -13436,6 +13439,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13436
13439
  itemInvalidationWasTriggered.clear();
13437
13440
  itemFieldInvalidationPriorities.clear();
13438
13441
  itemPendingInvalidationFields.clear();
13442
+ itemsPendingFullInvalidation.clear();
13439
13443
  }
13440
13444
  async function performMutation(payload, { optimisticUpdate, mutation, silentErrors, revalidateOnSuccess, onSuccess, onError, debounce, offline, upload }) {
13441
13445
  const payloadToUse = payload === null ? [] : payload;
@@ -13466,55 +13470,42 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13466
13470
  items: affectedItems
13467
13471
  });
13468
13472
  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
- });
13473
+ const result = await performMutationWithLifecycle(() => {
13474
+ const endBaseMutations = startItemMutation(payloadToUse);
13475
+ return () => {
13476
+ endBaseMutations();
13477
+ for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
13478
+ };
13479
+ }, offline ? () => runHybridOfflineMutation(offlineController, offline, upload, directMutation) : async () => ({
13480
+ kind: "online",
13481
+ data: await directMutation()
13482
+ }), (exception) => {
13483
+ const error = toStoreMutationError(exception, errorNormalizer);
13484
+ const queryRollbackSnapshots = [...optimisticMutationQueryContext.queryRollbackSnapshots.values()];
13485
+ if (itemRollbackSnapshots.length > 0 || queryRollbackSnapshots.length) restoreMutationRollbackState({
13486
+ itemSnapshots: itemRollbackSnapshots,
13487
+ querySnapshots: queryRollbackSnapshots
13488
+ });
13489
+ if (onMutationError) onMutationError(exception, { silentErrors });
13490
+ if (onError) onError(error);
13491
+ return error;
13492
+ }, optimisticUpdate ? () => {
13493
+ deferredOptimisticQueryInvalidationsStack.push(deferredOptimisticQueryInvalidations);
13494
+ optimisticMutationQueryContextStack.push(optimisticMutationQueryContext);
13495
+ try {
13496
+ return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse));
13497
+ } finally {
13498
+ optimisticMutationQueryContextStack.pop();
13499
+ deferredOptimisticQueryInvalidationsStack.pop();
13500
+ }
13501
+ } : void 0, (result) => {
13502
+ const successInvalidationQueryPayloads = result.kind === "online" ? getSuccessInvalidationQueryPayloads(deferredOptimisticQueryInvalidations, normalizedRevalidateOnSuccess.queryFilter, normalizedRevalidateOnSuccess.shouldRevalidate) : [];
13503
+ if (result.kind === "online" && (normalizedRevalidateOnSuccess.shouldRevalidate || successInvalidationQueryPayloads.length > 0)) invalidateQueryAndItems({
13504
+ itemPayload: !normalizedRevalidateOnSuccess.includeItems || affectedItems.length === 0 ? false : payloadToUse,
13505
+ queryPayload: successInvalidationQueryPayloads.length > 0 ? successInvalidationQueryPayloads : false
13506
+ });
13507
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
13508
+ }, debounce, blockWindowClose ?? void 0);
13518
13509
  storeEvents.emit("mutationEnd", {
13519
13510
  mutationId,
13520
13511
  items: affectedItems,
@@ -13528,7 +13519,6 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13528
13519
  queryInvalidationWasTriggered,
13529
13520
  itemInvalidationWasTriggered,
13530
13521
  itemFieldInvalidationPriorities,
13531
- itemPendingInvalidationFields,
13532
13522
  invalidateQueryAndItems,
13533
13523
  invalidateItem,
13534
13524
  startItemMutation,
@@ -13542,7 +13532,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13542
13532
  //#endregion
13543
13533
  //#region src/listQueryStore/listQueryCacheLimits.ts
13544
13534
  /** @internal */
13545
- function createListQueryCacheLimits({ store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup }) {
13535
+ function createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup) {
13546
13536
  let isEnforcingCacheLimits = false;
13547
13537
  function getReferencedItemKeysFromQueries(queryKeys = Object.keys(store.state.queries)) {
13548
13538
  const referencedItemKeys = /* @__PURE__ */ new Set();
@@ -13893,7 +13883,7 @@ const cacheMissError = {
13893
13883
  id: "cache-miss",
13894
13884
  message: "Cache miss"
13895
13885
  };
13896
- function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, debouncePayload }, store, events, getItemKey, registerActiveItems, touchItems, scheduleAutomaticItemFetch, preloadItems, preloadItemsBeforePaint, readFallbackItemState, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays) {
13886
+ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, debouncePayload }, store, events, getItemKey, registerActiveItems, touchItems, scheduleAutomaticItemFetch, preloadItems, preloadItemsBeforePaint, readFallbackItemState, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays) {
13897
13887
  const isOffScreenFromContext = useContext(IsOffScreenContext);
13898
13888
  const queriesWithId = useMemo(() => {
13899
13889
  return items.map((itemProps) => {
@@ -13933,6 +13923,8 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13933
13923
  const offlineEntitiesByKey = useMemo(() => createOfflineEntityLookup(offlineEntities), [offlineEntities]);
13934
13924
  const activeOfflineOverlays = useMemo(() => filterActiveOfflineOverlays(offlineEntitiesByKey, offlineOverlays), [offlineEntitiesByKey, offlineOverlays]);
13935
13925
  const getUnresolvedPendingInvalidationFields = useCallback((itemKey) => {
13926
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
13927
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
13936
13928
  return excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
13937
13929
  }, [itemPendingInvalidationFields, store]);
13938
13930
  const resultSelector = useCallback((state) => {
@@ -13996,20 +13988,23 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13996
13988
  let status = itemQuery.status;
13997
13989
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
13998
13990
  if (partialResources && Array.isArray(fields) && fields.length > 0 && (status === "success" || status === "refetching")) {
13999
- const missingFields = excludeLoadedFields(loadedFields, fields);
14000
- const hasMissingFields = missingFields.length > 0;
14001
- let missingFieldsAreAvailableInState = false;
14002
- if (hasMissingFields && rawItemState && typeof rawItemState === "object") {
14003
- const itemRecord = __LEGIT_CAST__(rawItemState);
14004
- missingFieldsAreAvailableInState = missingFields.every((f) => f in itemRecord && itemRecord[f] !== void 0);
14005
- }
14006
- if (hasMissingFields && !missingFieldsAreAvailableInState) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
13991
+ if (getFallbackMissingRequestedFields({
13992
+ item: rawItemState,
13993
+ loadedFields
13994
+ }, fields, partialResources.inferFields).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
13995
+ } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
13996
+ const isIncomplete = !snapshotIsFullyLoaded(loadedFields, rawItemState, partialResources.inferFields) && !(itemsPendingFullInvalidation.has(itemKey) && hasCachedDataInState);
13997
+ const isStale = !isIncomplete && !snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, rawItemState, partialResources.inferFields, itemsPendingFullInvalidation);
13998
+ if (isIncomplete) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
13999
+ else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
14007
14000
  }
14008
14001
  if (partialResources && showPartialAsRefetching) {
14009
14002
  if (Array.isArray(fields) && fields.length > 0) {
14010
- const pendingRequestedFields = excludeLoadedFields(loadedFields, fields);
14003
+ const pendingRequestedFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, rawItemState, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey));
14011
14004
  if (pendingRequestedFields.length > 0) loadingFields = pendingRequestedFields;
14012
- } else if (fields === "*" && itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) loadingFields = itemFieldInvalidationFields;
14005
+ } else if (fields === "*") {
14006
+ if (hasFullyLoadedFields(loadedFields) && itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) loadingFields = itemFieldInvalidationFields;
14007
+ }
14013
14008
  }
14014
14009
  if (partialResources && status === "refetching" && Array.isArray(fields) && fields.length > 0 && itemFieldInvalidationFields && !fields.some((f) => itemFieldInvalidationFields.includes(f))) status = "success";
14015
14010
  if (!returnRefetchingStatus && status === "refetching") status = "success";
@@ -14028,6 +14023,8 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14028
14023
  });
14029
14024
  }, [
14030
14025
  activeOfflineOverlays,
14026
+ getUnresolvedPendingInvalidationFields,
14027
+ itemsPendingFullInvalidation,
14031
14028
  loadFromStateOnly,
14032
14029
  offlineEntitiesByKey,
14033
14030
  partialResources,
@@ -14038,14 +14035,21 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14038
14035
  return queriesWithId.map(({ itemKey, fields }) => {
14039
14036
  const itemQuery = state.itemQueries[itemKey];
14040
14037
  const loadedFields = state.itemLoadedFields[itemKey] ?? [];
14041
- const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? excludeLoadedFields(loadedFields, fields).sort() : [];
14038
+ const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).sort() : [];
14039
+ const needsFullFetch = partialResources && fields === "*" ? !snapshotIsFullyLoaded(loadedFields, state.items[itemKey], partialResources.inferFields) || itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields) : false;
14042
14040
  return {
14043
14041
  status: itemQuery?.status ?? null,
14044
14042
  refetchOnMount: itemQuery?.refetchOnMount ?? null,
14045
- missingRequestedFieldsKey: JSON.stringify(missingRequestedFields)
14043
+ missingRequestedFieldsKey: JSON.stringify(missingRequestedFields),
14044
+ needsFullFetch
14046
14045
  };
14047
14046
  });
14048
- }, [partialResources, queriesWithId]);
14047
+ }, [
14048
+ getUnresolvedPendingInvalidationFields,
14049
+ itemsPendingFullInvalidation,
14050
+ partialResources,
14051
+ queriesWithId
14052
+ ]);
14049
14053
  const storeState = store.useSelectorRC(resultSelector, { equalityFn: deepEqual });
14050
14054
  const visibleStoreState = useMemo(() => {
14051
14055
  return storeState.map((result, index) => {
@@ -14056,7 +14060,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14056
14060
  const fallbackItemState = readFallbackItemState(query.itemKey);
14057
14061
  const overlay = activeOfflineOverlays[result.itemStateKey];
14058
14062
  const hasOverlay = overlay !== void 0;
14059
- if (!(!partialResources || query.fields === void 0 || query.fields === "*" || fallbackItemHasRequestedFields(fallbackItemState, query.fields))) return result;
14063
+ if (!(!partialResources || query.fields === void 0 || (query.fields === "*" ? snapshotIsFullyLoaded(fallbackItemState?.loadedFields, fallbackItemState?.item, partialResources.inferFields) : fallbackItemHasRequestedFields(fallbackItemState, query.fields, partialResources.inferFields)))) return result;
14060
14064
  const fallbackItemQuery = hasOverlay && overlay.item !== null && fallbackItemState?.itemQuery == null ? {
14061
14065
  status: "success",
14062
14066
  wasLoaded: true,
@@ -14176,37 +14180,39 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14176
14180
  const itemFetchIsActive = itemState?.status === "loading" || itemState?.status === "refetching";
14177
14181
  if (partialResources && !shouldFetch) {
14178
14182
  const loadedFields = store.state.itemLoadedFields[itemKey] ?? [];
14183
+ const item = store.state.items[itemKey];
14179
14184
  const unresolvedPendingInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
14180
- const invalidationPriority = unresolvedPendingInvalidationFields.length > 0 ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
14185
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields);
14186
+ const invalidationPriority = unresolvedPendingInvalidationFields.length > 0 || hasUnresolvedFullInvalidation ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
14181
14187
  if (Array.isArray(fields) && fields.length > 0) {
14182
- const missingFields = excludeLoadedFields(loadedFields, fields);
14188
+ const affectedInvalidationFields = fields.filter((field) => unresolvedPendingInvalidationFields.includes(field));
14189
+ const staleOrMissingFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, item, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields);
14190
+ const missingFields = loadedFields === "*" ? [] : staleOrMissingFields.filter((field) => !loadedFields.includes(field));
14183
14191
  const hasMissingFields = missingFields.length > 0;
14184
- const hasAffectedFieldInvalidation = unresolvedPendingInvalidationFields.length > 0 && fields.some((field) => unresolvedPendingInvalidationFields.includes(field));
14185
- if (hasMissingFields && !itemFetchIsActive) {
14192
+ const hasAffectedFieldInvalidation = affectedInvalidationFields.length > 0;
14193
+ const shouldFetchForInvalidation = hasAffectedFieldInvalidation && !ignoreItemsInRefetchOnMount.has(itemKey);
14194
+ if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive) {
14186
14195
  shouldFetch = true;
14187
14196
  requiredFetch = true;
14188
- fieldsToFetch = missingFields;
14197
+ fieldsToFetch = Array.from(new Set([...missingFields, ...affectedInvalidationFields]));
14189
14198
  if (fetchType === "lowPriority") fetchType = "highPriority";
14190
14199
  }
14191
14200
  if (hasAffectedFieldInvalidation && invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14192
- } else if (fields === "*" && unresolvedPendingInvalidationFields.length > 0 && !itemFetchIsActive && !ignoreItemsInRefetchOnMount.has(itemKey)) {
14193
- shouldFetch = true;
14194
- requiredFetch = true;
14195
- fieldsToFetch = unresolvedPendingInvalidationFields;
14196
- if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14201
+ } else if (fields === "*") {
14202
+ const missingFullItem = !snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation;
14203
+ const shouldFetchForInvalidation = !missingFullItem && unresolvedPendingInvalidationFields.length > 0 && !ignoreItemsInRefetchOnMount.has(itemKey);
14204
+ if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive) {
14205
+ shouldFetch = true;
14206
+ requiredFetch = true;
14207
+ fieldsToFetch = missingFullItem ? "*" : unresolvedPendingInvalidationFields;
14208
+ if (fetchType === "lowPriority") fetchType = "highPriority";
14209
+ if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14210
+ }
14197
14211
  }
14198
14212
  }
14199
14213
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemKey)) continue;
14200
14214
  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 });
14215
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, itemState?.status)) scheduleAutomaticItemFetch(fetchType, payload, { fields: fieldsToFetch });
14210
14216
  }
14211
14217
  for (const itemKey of removedItems) ignoreItemsInRefetchOnMount.delete(itemKey);
14212
14218
  })();
@@ -14222,6 +14228,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14222
14228
  ignoreItemsInRefetchOnMount,
14223
14229
  itemFieldInvalidationPriorities,
14224
14230
  itemPendingInvalidationFields,
14231
+ itemsPendingFullInvalidation,
14225
14232
  loadFromStateOnly,
14226
14233
  partialResources,
14227
14234
  preloadItems,
@@ -14233,7 +14240,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14233
14240
  }
14234
14241
  //#endregion
14235
14242
  //#region src/listQueryStore/useMultipleListQueries.ts
14236
- function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, omitPayload: allItemsOmitPayload, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, loadSize: allItemsLoadSize, debouncePayload }, store, events, getQueryKey, registerActiveQueries, touchQueries, getQueryState, readFallbackQueryState, preloadQueries, preloadQueriesBeforePaint, preloadDerivedQueryItems, readFallbackItemState, scheduleAutomaticListQueryFetch, queryInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, globalDisableRefetchOnMount, partialResources, derivedQueries, isOfflineMode, offlineEntities, offlineOverlays) {
14243
+ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, omitPayload: allItemsOmitPayload, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, loadSize: allItemsLoadSize, debouncePayload }, store, events, getQueryKey, registerActiveQueries, touchQueries, getQueryState, readFallbackQueryState, preloadQueries, preloadQueriesBeforePaint, preloadDerivedQueryItems, readFallbackItemState, scheduleAutomaticListQueryFetch, queryInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, partialResources, derivedQueries, isOfflineMode, offlineEntities, offlineOverlays) {
14237
14244
  const isOffScreenFromContext = useContext(IsOffScreenContext);
14238
14245
  const queriesWithId = useMemo(() => {
14239
14246
  return queries.map((queryProps) => {
@@ -14342,6 +14349,8 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14342
14349
  partialResources
14343
14350
  ]);
14344
14351
  const getUnresolvedPendingInvalidationFields = useCallback((itemKey, state) => {
14352
+ const stateInvalidationFields = (state ? state.itemFieldInvalidationFields : store.state.itemFieldInvalidationFields)[itemKey];
14353
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
14345
14354
  return excludeLoadedFields((state ? state.itemLoadedFields : store.state.itemLoadedFields)[itemKey], itemPendingInvalidationFields.get(itemKey));
14346
14355
  }, [itemPendingInvalidationFields, store]);
14347
14356
  const getHighestPendingInvalidationPriority = useCallback((itemKeys, requestedFields) => {
@@ -14483,34 +14492,49 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14483
14492
  const hasCachedItemsInState = effectiveQuery.query.items.some((itemKey) => {
14484
14493
  return state.items[itemKey] != null;
14485
14494
  });
14486
- if (partialResources && Array.isArray(fields) && fields.length > 0 && (status === "success" || status === "refetching")) {
14487
- const someItemMissingFields = effectiveQuery.query.items.some((itemKey) => {
14488
- const loadedFields = state.itemLoadedFields[itemKey] ?? [];
14489
- return fields.some((f) => !loadedFields.includes(f));
14490
- });
14491
- const someItemMissingFieldsInState = effectiveQuery.query.items.some((itemKey) => {
14492
- const item = state.items[itemKey];
14493
- if (!item || typeof item !== "object") return true;
14494
- const itemRecord = __LEGIT_CAST__(item);
14495
- return fields.some((f) => !(f in itemRecord) || itemRecord[f] === void 0);
14496
- });
14497
- if (someItemMissingFields) if (!hasCachedItemsInState) status = "loading";
14498
- else if (someItemMissingFieldsInState) status = showPartialAsRefetching ? "refetching" : "loading";
14495
+ let staleOrMissingRequestedFields;
14496
+ let hasAnyIncompleteItem = false;
14497
+ let hasAnyStaleItem = false;
14498
+ const statusCanBeOverridden = status === "success" || status === "refetching";
14499
+ if (partialResources && (statusCanBeOverridden || showPartialAsRefetching)) {
14500
+ if (Array.isArray(fields) && fields.length > 0) {
14501
+ staleOrMissingRequestedFields = /* @__PURE__ */ new Set();
14502
+ for (const itemKey of effectiveQuery.query.items) {
14503
+ for (const field of getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state))) staleOrMissingRequestedFields.add(field);
14504
+ if (staleOrMissingRequestedFields.size === fields.length || !showPartialAsRefetching && staleOrMissingRequestedFields.size > 0) break;
14505
+ }
14506
+ } else if (fields === "*") {
14507
+ hasAnyIncompleteItem = effectiveQuery.query.items.some((itemKey) => {
14508
+ const item = state.items[itemKey];
14509
+ if (snapshotIsFullyLoaded(state.itemLoadedFields[itemKey], item, partialResources.inferFields)) return false;
14510
+ return !(itemsPendingFullInvalidation.has(itemKey) && item != null);
14511
+ });
14512
+ hasAnyStaleItem = !hasAnyIncompleteItem && effectiveQuery.query.items.some((itemKey) => !snapshotIsFullyLoadedAndFresh(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], partialResources.inferFields, itemsPendingFullInvalidation));
14513
+ }
14514
+ }
14515
+ if (partialResources && Array.isArray(fields) && statusCanBeOverridden && staleOrMissingRequestedFields && staleOrMissingRequestedFields.size > 0) {
14516
+ const someItemMissingFieldDataInState = effectiveQuery.query.items.some((itemKey) => getFallbackMissingRequestedFields({
14517
+ item: state.items[itemKey],
14518
+ loadedFields: state.itemLoadedFields[itemKey]
14519
+ }, fields, partialResources.inferFields).length > 0);
14520
+ if (!hasCachedItemsInState) status = "loading";
14521
+ else if (someItemMissingFieldDataInState) status = showPartialAsRefetching ? "refetching" : "loading";
14499
14522
  else status = "refetching";
14500
- } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
14501
- if (effectiveQuery.query.items.some((itemKey) => {
14523
+ } else if (partialResources && fields === "*" && statusCanBeOverridden) {
14524
+ const hasAnyFieldInvalidation = effectiveQuery.query.items.some((itemKey) => {
14502
14525
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
14503
14526
  return !!itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0;
14504
- })) status = "refetching";
14527
+ });
14528
+ if (hasAnyIncompleteItem) if (!hasCachedItemsInState) status = "loading";
14529
+ else status = showPartialAsRefetching ? "refetching" : "loading";
14530
+ else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
14505
14531
  }
14506
14532
  if (partialResources && showPartialAsRefetching) {
14507
14533
  if (Array.isArray(fields) && fields.length > 0) {
14508
- const pendingRequestedFields = fields.filter((field) => status === "loading" && effectiveQuery.query.items.length === 0 ? true : effectiveQuery.query.items.some((itemKey) => {
14509
- return !(state.itemLoadedFields[itemKey] ?? []).includes(field);
14510
- }));
14534
+ const pendingRequestedFields = status === "loading" && effectiveQuery.query.items.length === 0 ? [...fields] : fields.filter((field) => staleOrMissingRequestedFields?.has(field) ?? false);
14511
14535
  if (pendingRequestedFields.length > 0) loadingFields = pendingRequestedFields;
14512
14536
  } else if (fields === "*") {
14513
- const pendingInvalidationFields = Array.from(new Set(effectiveQuery.query.items.flatMap((itemKey) => state.itemFieldInvalidationFields[itemKey] ?? []))).sort();
14537
+ const pendingInvalidationFields = hasAnyIncompleteItem || hasAnyStaleItem ? [] : Array.from(new Set(effectiveQuery.query.items.flatMap((itemKey) => state.itemFieldInvalidationFields[itemKey] ?? []))).sort();
14514
14538
  if (pendingInvalidationFields.length > 0) loadingFields = pendingInvalidationFields;
14515
14539
  }
14516
14540
  }
@@ -14535,8 +14559,10 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14535
14559
  };
14536
14560
  });
14537
14561
  }, [
14562
+ getUnresolvedPendingInvalidationFields,
14538
14563
  getVisibleQueryItemKeys,
14539
14564
  isOfflineMode,
14565
+ itemsPendingFullInvalidation,
14540
14566
  offlineEntitiesByKey,
14541
14567
  partialResources,
14542
14568
  queriesWithId,
@@ -14554,11 +14580,16 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14554
14580
  if (fallbackQuery && readFallbackItemState) {
14555
14581
  const visibleItemKeys = getVisibleQueryItemKeys(result.queryKey, fallbackQuery.items);
14556
14582
  const requestedFields = Array.isArray(queryConfig.fields) ? queryConfig.fields : void 0;
14583
+ const requiresFullItems = queryConfig.fields === "*";
14557
14584
  const fallbackItemStatesByKey = /* @__PURE__ */ new Map();
14558
14585
  for (const itemKey of visibleItemKeys) {
14559
14586
  const fallbackItemState = readFallbackItemState(itemKey);
14560
14587
  fallbackItemStatesByKey.set(itemKey, fallbackItemState);
14561
- if (requestedFields && partialResources && !fallbackItemHasRequestedFields(fallbackItemState, requestedFields)) return result;
14588
+ if (partialResources) {
14589
+ if (requiresFullItems) {
14590
+ if (!snapshotIsFullyLoaded(fallbackItemState?.loadedFields, fallbackItemState?.item, partialResources.inferFields)) return result;
14591
+ } else if (requestedFields && !fallbackItemHasRequestedFields(fallbackItemState, requestedFields, partialResources.inferFields)) return result;
14592
+ }
14562
14593
  }
14563
14594
  const fallbackItems = selectVisibleItems(visibleItemKeys, queryConfig.fields, (itemKey) => {
14564
14595
  const fallbackItemState = fallbackItemStatesByKey.get(itemKey);
@@ -14615,7 +14646,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14615
14646
  const unresolvedFields = Array.from(new Set(effectiveQuery.query.items.flatMap((itemKey) => getUnresolvedPendingInvalidationFields(itemKey, state)))).sort();
14616
14647
  const requestedFields = Array.isArray(queryConfig.fields) ? queryConfig.fields : void 0;
14617
14648
  const missingRequestedFields = requestedFields && requestedFields.length > 0 ? effectiveQuery.query.items.flatMap((itemKey) => {
14618
- return excludeLoadedFields(state.itemLoadedFields[itemKey], requestedFields);
14649
+ return getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], requestedFields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state));
14619
14650
  }).filter((field, index, array) => array.indexOf(field) === index).sort() : [];
14620
14651
  let unresolvedInvalidationFieldsKey = "";
14621
14652
  if (queryConfig.fields === "*") unresolvedInvalidationFieldsKey = JSON.stringify(unresolvedFields);
@@ -14634,6 +14665,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14634
14665
  }, [
14635
14666
  getHighestPendingInvalidationPriority,
14636
14667
  getUnresolvedPendingInvalidationFields,
14668
+ itemsPendingFullInvalidation,
14637
14669
  partialResources,
14638
14670
  queriesWithId,
14639
14671
  resolveEffectiveQuery
@@ -14722,10 +14754,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14722
14754
  if (partialResources && !shouldFetch && effectiveQueryState) {
14723
14755
  const isQueryFetchInFlight = effectiveQueryState.status === "loading" || effectiveQueryState.status === "refetching" || effectiveQueryState.status === "loadingMore";
14724
14756
  if (Array.isArray(fields) && fields.length > 0) {
14725
- if (effectiveQueryState.items.some((itemKey) => {
14726
- const loadedFields = store.state.itemLoadedFields[itemKey] ?? [];
14727
- return fields.some((field) => !loadedFields.includes(field));
14728
- }) && !isQueryFetchInFlight) {
14757
+ if (effectiveQueryState.items.some((itemKey) => getStaleOrMissingRequestedFields(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).length > 0) && !isQueryFetchInFlight) {
14729
14758
  shouldFetch = true;
14730
14759
  requiredFetch = true;
14731
14760
  fieldsToFetch = fields;
@@ -14742,9 +14771,11 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14742
14771
  if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14743
14772
  }
14744
14773
  } else if (fields === "*") {
14745
- if (effectiveQueryState.items.some((itemKey) => {
14774
+ const hasAnyPartialItem = effectiveQueryState.items.some((itemKey) => !snapshotIsFullyLoadedAndFresh(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], partialResources.inferFields, itemsPendingFullInvalidation));
14775
+ const hasAnyFieldInvalidation = effectiveQueryState.items.some((itemKey) => {
14746
14776
  return getUnresolvedPendingInvalidationFields(itemKey).length > 0;
14747
- }) && !isQueryFetchInFlight) {
14777
+ });
14778
+ if ((hasAnyPartialItem || hasAnyFieldInvalidation) && !isQueryFetchInFlight) {
14748
14779
  shouldFetch = true;
14749
14780
  requiredFetch = true;
14750
14781
  const invalidationPriority = getHighestPendingInvalidationPriority(effectiveQueryState.items, void 0);
@@ -14754,15 +14785,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14754
14785
  }
14755
14786
  if (!shouldFetch && ignoreQueriesInRefetchOnMount.has(queryId)) continue;
14756
14787
  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)) {
14788
+ if (shouldScheduleAutomaticFetch(effectiveQueryState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
14766
14789
  stickyDerivedQueryKeys.delete(queryId);
14767
14790
  scheduleAutomaticListQueryFetch(fetchType, payload, loadSize, { fields: fieldsToFetch });
14768
14791
  }
@@ -14788,6 +14811,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14788
14811
  automaticRetryState,
14789
14812
  itemFieldInvalidationPriorities,
14790
14813
  itemPendingInvalidationFields,
14814
+ itemsPendingFullInvalidation,
14791
14815
  getHighestPendingInvalidationPriority,
14792
14816
  getUnresolvedPendingInvalidationFields,
14793
14817
  stickyDerivedQueryKeys
@@ -14950,18 +14974,9 @@ function createListQueryStore(storeOptions) {
14950
14974
  if (fields === "*") return void 0;
14951
14975
  return fields;
14952
14976
  }
14953
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
14954
- storeManager,
14955
- storeName: id,
14956
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
14957
- });
14977
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
14958
14978
  const getSessionKeyBase = storeManager.getSessionKey;
14959
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
14960
- storeManager,
14961
- storeName: id,
14962
- offlineSession: resolvedOfflineSession,
14963
- getSessionKey: getSessionKeyBase
14964
- });
14979
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
14965
14980
  const errorNormalizer = storeManager.errorNormalizer;
14966
14981
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
14967
14982
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -14975,7 +14990,8 @@ function createListQueryStore(storeOptions) {
14975
14990
  ...persistentStorageConfig.offline,
14976
14991
  session: resolvedOfflineSessionForPersistentStorage
14977
14992
  } : void 0,
14978
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
14993
+ debugLogger: storeManager.debugLogger,
14994
+ logger: storeManager.logger,
14979
14995
  getSessionKey: getSessionKeyForRuntime,
14980
14996
  storeName: id
14981
14997
  }) : null;
@@ -15081,11 +15097,20 @@ function createListQueryStore(storeOptions) {
15081
15097
  lastFetchDuration,
15082
15098
  windowIsNotFocused: !getWindowIsFocused()
15083
15099
  });
15100
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
15101
+ getWindowIsFocused,
15102
+ onWindowFocusChange: testOptions?.onWindowFocusChange,
15103
+ transportFactory: testOptions?.browserTabsTransportFactory,
15104
+ priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
15105
+ });
15084
15106
  function getCoalescingWindowMs() {
15085
- return browserTabsPriority?.getCoalescingWindowMs(baseCoalescingWindowMs) ?? baseCoalescingWindowMs;
15107
+ return browserTabsPriority.getCoalescingWindowMs(baseCoalescingWindowMs);
15086
15108
  }
15087
- let browserTabsSync = null;
15088
- let browserTabsPriority = null;
15109
+ const browserTabsSync = createBrowserTabsCoordinator("listQuery", id, getSessionKeyForRuntime, handleRemoteBrowserTabsMessage, () => {
15110
+ lastQuerySyncVersions.clear();
15111
+ lastItemSyncVersions.clear();
15112
+ clearOfflineOverlays();
15113
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
15089
15114
  function getQueryTargetKey(queryKey) {
15090
15115
  return `query:${queryKey}`;
15091
15116
  }
@@ -15111,7 +15136,7 @@ function createListQueryStore(storeOptions) {
15111
15136
  itemKey,
15112
15137
  item: store.state.items[itemKey] ?? null,
15113
15138
  itemQuery: store.state.itemQueries[itemKey] ?? null,
15114
- loadedFields: store.state.itemLoadedFields[itemKey] ?? []
15139
+ loadedFields: store.state.itemLoadedFields[itemKey]
15115
15140
  }));
15116
15141
  }
15117
15142
  function publishQuerySnapshot(queryKey, consistency = currentBroadcastConsistency) {
@@ -15119,7 +15144,7 @@ function createListQueryStore(storeOptions) {
15119
15144
  const query = store.state.queries[queryKey];
15120
15145
  if (!query) return;
15121
15146
  const items = getQuerySnapshotItems(query);
15122
- const message = browserTabsSync?.publish({
15147
+ const message = browserTabsSync.publish({
15123
15148
  kind: "list-query-snapshot",
15124
15149
  queryKey,
15125
15150
  consistency,
@@ -15132,13 +15157,13 @@ function createListQueryStore(storeOptions) {
15132
15157
  }
15133
15158
  function publishItemSnapshot(itemKey, consistency = currentBroadcastConsistency) {
15134
15159
  if (remoteApplyDepth > 0) return;
15135
- const message = browserTabsSync?.publish({
15160
+ const message = browserTabsSync.publish({
15136
15161
  kind: "list-item-snapshot",
15137
15162
  itemKey,
15138
15163
  consistency,
15139
15164
  item: store.state.items[itemKey] ?? null,
15140
15165
  itemQuery: store.state.itemQueries[itemKey] ?? null,
15141
- loadedFields: store.state.itemLoadedFields[itemKey] ?? []
15166
+ loadedFields: store.state.itemLoadedFields[itemKey]
15142
15167
  });
15143
15168
  if (!message) return;
15144
15169
  recordItemSyncVersion(itemKey, message, consistency);
@@ -15194,217 +15219,151 @@ function createListQueryStore(storeOptions) {
15194
15219
  preloaded: results[index] ?? false
15195
15220
  }));
15196
15221
  }
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
15222
+ const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
15223
+ const itemsPendingFullInvalidation = /* @__PURE__ */ new Set();
15224
+ const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers, reevaluateDelayedRTUs } = 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) => {
15225
+ const queryKey = requests[0]?.requestId;
15226
+ if (!queryKey) return;
15227
+ browserTabsSync.publish({
15228
+ kind: "fetch-start",
15229
+ targetKey: getQueryTargetKey(queryKey),
15230
+ requestIds: requests.map(({ requestId }) => requestId),
15231
+ startedAt
15232
+ });
15233
+ }, ({ requests, results, startedAt, duration }) => {
15234
+ pruneItemInvalidationTracking();
15235
+ const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
15236
+ if (successfulQueryKeys.length > 0) {
15237
+ touchQueries(successfulQueryKeys);
15238
+ touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
15239
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15240
+ }
15241
+ const firstQueryKey = successfulQueryKeys[0];
15242
+ if (firstQueryKey) {
15243
+ browserTabsSync.publish({
15244
+ kind: "fetch-success",
15245
+ targetKey: getQueryTargetKey(firstQueryKey),
15246
+ requestIds: successfulQueryKeys,
15247
+ startedAt,
15248
+ duration
15231
15249
  });
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",
15250
+ for (const queryKey of successfulQueryKeys) publishQuerySnapshot(queryKey, "confirmed");
15251
+ }
15252
+ }, (requests, startedAt) => {
15253
+ const firstRequest = requests[0];
15254
+ if (!firstRequest) return;
15255
+ const payload = firstRequest.payload.payload;
15256
+ const batchKey = getItemBatchKey(payload);
15257
+ const targetKey = batchKey === false ? getItemTargetKey(firstRequest.requestId) : getItemBatchTargetKey(batchKey);
15258
+ browserTabsSync.publish({
15259
+ kind: "fetch-start",
15260
+ targetKey,
15261
+ requestIds: requests.map(({ requestId }) => requestId),
15262
+ startedAt
15263
+ });
15264
+ }, ({ requests, results, startedAt, duration }) => {
15265
+ pruneItemInvalidationTracking();
15266
+ const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
15267
+ if (successfulItems.length > 0) {
15268
+ touchItems(successfulItems.map(({ itemKey }) => itemKey));
15269
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15270
+ }
15271
+ const firstSuccessfulItem = successfulItems[0];
15272
+ if (firstSuccessfulItem) {
15273
+ const payload = requests[0]?.payload.payload;
15274
+ const batchKey = payload ? getItemBatchKey(payload) : false;
15275
+ const targetKey = batchKey === false ? getItemTargetKey(firstSuccessfulItem.itemKey) : getItemBatchTargetKey(batchKey);
15276
+ browserTabsSync.publish({
15277
+ kind: "fetch-success",
15241
15278
  targetKey,
15242
- requestIds: requests.map(({ requestId }) => requestId),
15243
- startedAt
15279
+ requestIds: successfulItems.map(({ itemKey }) => itemKey),
15280
+ startedAt,
15281
+ duration
15244
15282
  });
15283
+ for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
15284
+ }
15285
+ }, offlineFetchController, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15286
+ const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, 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) => {
15287
+ events.emit("invalidateQuery", event);
15288
+ }, (event) => {
15289
+ events.emit("invalidateItem", event);
15290
+ }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15291
+ if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
15292
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
15293
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
15294
+ if (normalizedRef !== null) return normalizedRef;
15295
+ return {
15296
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
15297
+ entityKind: "item"
15298
+ };
15299
+ }),
15300
+ getProtectedCacheKeys: (entityRefs) => {
15301
+ const sessionKey = getSessionKeyForRuntime();
15302
+ if (sessionKey === false) return [];
15303
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "listQuery.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
15245
15304
  },
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
- }
15305
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
15306
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
15307
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
15265
15308
  },
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);
15309
+ rollbackPendingEntity: ({ tempId }) => {
15310
+ deleteItemState(__LEGIT_CAST__(tempId));
15307
15311
  },
15308
- emitInvalidateItem: (event) => {
15309
- events.emit("invalidateItem", event);
15312
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
15313
+ const tempPayload = __LEGIT_CAST__(tempId);
15314
+ const tempItemKey = getItemKey(tempPayload);
15315
+ const currentItem = getItemState(tempPayload);
15316
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
15317
+ if (finalData === void 0) return;
15318
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
15319
+ const finalItemKey = getItemKey(finalPayload);
15320
+ const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
15321
+ queryKey,
15322
+ index: query.items.indexOf(tempItemKey)
15323
+ })).filter(({ index }) => index !== -1);
15324
+ deleteItemState(tempPayload);
15325
+ addItemToState(finalPayload, finalData);
15326
+ storeEvents.emit("tempEntityReconciled", {
15327
+ tempId: tempPayload,
15328
+ finalPayload
15329
+ });
15330
+ if (queryMemberships.length === 0) return;
15331
+ store.produceState((draft) => {
15332
+ for (const { queryKey, index } of queryMemberships) {
15333
+ const query = notNullish(draft.queries[queryKey]);
15334
+ const existingIndex = query.items.indexOf(finalItemKey);
15335
+ if (existingIndex !== -1) query.items.splice(existingIndex, 1);
15336
+ query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
15337
+ }
15338
+ }, { action: "offline-reconcile-temp-item" });
15339
+ touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
15340
+ for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
15310
15341
  },
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
- }
15342
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
15343
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15344
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
15345
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
15346
+ }));
15347
+ },
15348
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
15349
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15350
+ rebindOfflineOverlays(itemKeyRewrites);
15351
+ },
15352
+ syncEntityOverlays: ({ entities, sessionKey }) => {
15353
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15354
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
15355
+ offlineOverlayStore.produceState((draft) => {
15356
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
15357
+ });
15401
15358
  }
15402
- });
15359
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime));
15403
15360
  function applyLoadedFieldsFromSnapshot(draft, itemKey, loadedFields) {
15404
- if (loadedFields.length > 0) {
15405
- const existingLoadedFields = draft.itemLoadedFields[itemKey] ?? [];
15406
- draft.itemLoadedFields[itemKey] = Array.from(new Set([...existingLoadedFields, ...loadedFields])).sort();
15407
- } else delete draft.itemLoadedFields[itemKey];
15361
+ if (loadedFields === void 0) return;
15362
+ if (loadedFields === "*") draft.itemLoadedFields[itemKey] = "*";
15363
+ else if (loadedFields.length > 0) {
15364
+ const existingLoadedFields = draft.itemLoadedFields[itemKey];
15365
+ if (existingLoadedFields !== "*") draft.itemLoadedFields[itemKey] = Array.from(new Set([...existingLoadedFields ?? [], ...loadedFields])).sort();
15366
+ } else if (draft.itemLoadedFields[itemKey] === void 0) draft.itemLoadedFields[itemKey] = [];
15408
15367
  const invalidationFields = draft.itemFieldInvalidationFields[itemKey];
15409
15368
  if (!invalidationFields) return;
15410
15369
  const remainingFields = excludeLoadedFields(loadedFields, invalidationFields);
@@ -15414,18 +15373,27 @@ function createListQueryStore(storeOptions) {
15414
15373
  function pruneItemInvalidationTracking() {
15415
15374
  for (const [itemKey, pendingFields] of itemPendingInvalidationFields) {
15416
15375
  const remainingFields = excludeLoadedFields(store.state.itemLoadedFields[itemKey], pendingFields);
15376
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
15377
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) {
15378
+ const mergedFields = Array.from(new Set([...stateInvalidationFields, ...remainingFields])).sort();
15379
+ itemPendingInvalidationFields.set(itemKey, mergedFields);
15380
+ continue;
15381
+ }
15417
15382
  if (remainingFields.length > 0) itemPendingInvalidationFields.set(itemKey, remainingFields);
15418
15383
  else itemPendingInvalidationFields.delete(itemKey);
15419
15384
  }
15385
+ for (const itemKey of itemsPendingFullInvalidation) if (store.state.itemLoadedFields[itemKey] === "*") itemsPendingFullInvalidation.delete(itemKey);
15420
15386
  for (const itemKey of itemFieldInvalidationPriorities.keys()) {
15421
15387
  const hasPendingStateInvalidation = !!store.state.itemFieldInvalidationFields[itemKey];
15422
15388
  const hasPendingTrackedInvalidation = (itemPendingInvalidationFields.get(itemKey)?.length ?? 0) > 0;
15423
- if (!hasPendingStateInvalidation && !hasPendingTrackedInvalidation) itemFieldInvalidationPriorities.delete(itemKey);
15389
+ const hasPendingFullInvalidation = itemsPendingFullInvalidation.has(itemKey);
15390
+ if (!hasPendingStateInvalidation && !hasPendingTrackedInvalidation && !hasPendingFullInvalidation) itemFieldInvalidationPriorities.delete(itemKey);
15424
15391
  }
15425
15392
  }
15426
15393
  function cleanupItemStateMetadata(itemKey) {
15427
15394
  itemFieldInvalidationPriorities.delete(itemKey);
15428
15395
  itemPendingInvalidationFields.delete(itemKey);
15396
+ itemsPendingFullInvalidation.delete(itemKey);
15429
15397
  itemInvalidationWasTriggered.delete(itemKey);
15430
15398
  itemCacheRuntime.clear(itemKey);
15431
15399
  }
@@ -15438,16 +15406,12 @@ function createListQueryStore(storeOptions) {
15438
15406
  offlineOverlayStore.setState({});
15439
15407
  }
15440
15408
  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
- });
15409
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
15410
+ item: existingOverlay.item ?? null,
15411
+ itemPayload: store.state.itemQueries[nextItemKey]?.payload ?? existingOverlay.itemPayload,
15412
+ queryMemberships: existingOverlay.queryMemberships,
15413
+ keepVisibleWhileResolutionRequired: true
15414
+ }));
15451
15415
  }
15452
15416
  function captureOfflineOverlays(itemKeys) {
15453
15417
  const targetItemKeySet = new Set(itemKeys);
@@ -15460,18 +15424,14 @@ function createListQueryStore(storeOptions) {
15460
15424
  if (!queryMemberships) continue;
15461
15425
  queryMemberships[queryKey] = index;
15462
15426
  }
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
- }
15427
+ captureOfflineOverlayEntries(offlineOverlayStore, [...targetItemKeySet], (itemKey) => {
15428
+ const item = store.state.items[itemKey];
15429
+ const itemPayload = store.state.itemQueries[itemKey]?.payload;
15430
+ return {
15431
+ item: item == null ? null : klona(item),
15432
+ itemPayload: itemPayload === void 0 ? void 0 : klona(itemPayload),
15433
+ queryMemberships: queryMembershipsByItemKey.get(itemKey) ?? {}
15434
+ };
15475
15435
  });
15476
15436
  }
15477
15437
  function isQueryProtectedFromEviction(queryKey, query) {
@@ -15491,18 +15451,20 @@ function createListQueryStore(storeOptions) {
15491
15451
  return partialResources.mergeItems(currentItem ?? void 0, incomingItem);
15492
15452
  }
15493
15453
  function itemSnapshotSatisfiesRequestedFields(item, loadedFields, requestedFields) {
15494
- if (!partialResources || !requestedFields || requestedFields.length === 0) return true;
15454
+ if (!partialResources) return true;
15495
15455
  if (item === null) return true;
15456
+ if (loadedFields !== void 0 && loadedFields !== "*" && loadedFields.length === 0) return false;
15457
+ if (!requestedFields || requestedFields.length === 0) return snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields);
15496
15458
  return fallbackItemHasRequestedFields({
15497
15459
  item,
15498
15460
  loadedFields
15499
- }, requestedFields);
15461
+ }, requestedFields, partialResources.inferFields);
15500
15462
  }
15501
15463
  function querySnapshotSatisfiesPendingQueryFetch(message, snapshotItemsByKey, request) {
15502
15464
  const requestedEnd = request.payload.offset + request.payload.limit;
15503
15465
  if (message.query.items.length < requestedEnd && message.query.hasMore) return false;
15504
15466
  const requestedFields = request.payload.fields;
15505
- if (!partialResources || !requestedFields || requestedFields.length === 0) return true;
15467
+ if (!partialResources) return true;
15506
15468
  return message.query.items.slice(request.payload.offset, requestedEnd).every((itemKey) => {
15507
15469
  const item = snapshotItemsByKey.get(itemKey);
15508
15470
  return !!item && itemSnapshotSatisfiesRequestedFields(item.item, item.loadedFields, requestedFields);
@@ -15522,6 +15484,7 @@ function createListQueryStore(storeOptions) {
15522
15484
  };
15523
15485
  applyLoadedFieldsFromSnapshot(draft, message.itemKey, message.loadedFields);
15524
15486
  if (!message.itemQuery && message.item === null) {
15487
+ delete draft.itemLoadedFields[message.itemKey];
15525
15488
  delete draft.itemFieldInvalidationFields[message.itemKey];
15526
15489
  for (const query of Object.values(draft.queries)) query.items = query.items.filter((itemId) => itemId !== message.itemKey);
15527
15490
  }
@@ -15580,17 +15543,12 @@ function createListQueryStore(storeOptions) {
15580
15543
  }
15581
15544
  function querySnapshotHasLocallyMutatingItem(message) {
15582
15545
  for (const item of message.items) {
15583
- const localItemQuery = store.state.itemQueries[item.itemKey];
15584
- if (!localItemQuery) continue;
15585
- if (getOrCreateItemScheduler(item.itemKey, localItemQuery.payload).isMutationInProgress(item.itemKey)) return true;
15546
+ if (!store.state.itemQueries[item.itemKey]) continue;
15547
+ if (getKnownItemScheduler(item.itemKey)?.isMutationInProgress(item.itemKey)) return true;
15586
15548
  }
15587
15549
  return false;
15588
15550
  }
15589
15551
  function handleRemoteBrowserTabsMessage(message) {
15590
- if (message.kind === "tab-status") {
15591
- browserTabsPriority?.onTabStatusMessage(message.tabId, message);
15592
- return;
15593
- }
15594
15552
  if (message.kind === "fetch-start") {
15595
15553
  syncRemoteFetchStart(message.targetKey, message.requestIds, message.startedAt);
15596
15554
  return;
@@ -15603,9 +15561,7 @@ function createListQueryStore(storeOptions) {
15603
15561
  const candidateVersion = toBrowserTabsSyncVersion(message, message.consistency);
15604
15562
  if (!isBrowserTabsSyncVersionNewer(candidateVersion, lastItemSyncVersions.get(message.itemKey))) return;
15605
15563
  const localItemQuery = store.state.itemQueries[message.itemKey];
15606
- let itemScheduler = null;
15607
- if (localItemQuery === void 0) itemScheduler = getKnownItemScheduler(message.itemKey);
15608
- else if (localItemQuery !== null) itemScheduler = getOrCreateItemScheduler(message.itemKey, localItemQuery.payload);
15564
+ const itemScheduler = localItemQuery === null ? null : getKnownItemScheduler(message.itemKey);
15609
15565
  if (localItemQuery === void 0 && !itemScheduler?.hasPendingFetch) {
15610
15566
  lastItemSyncVersions.set(message.itemKey, candidateVersion);
15611
15567
  return;
@@ -15634,22 +15590,6 @@ function createListQueryStore(storeOptions) {
15634
15590
  }
15635
15591
  applyRemoteQuerySnapshot(message);
15636
15592
  }
15637
- ({coordinator: browserTabsSync, priority: browserTabsPriority} = createBrowserTabsCoordinatorWithPriority({
15638
- storeType: "listQuery",
15639
- storeKey: id,
15640
- getSessionKey: getSessionKeyForRuntime,
15641
- onMessage: handleRemoteBrowserTabsMessage,
15642
- onSessionChange() {
15643
- lastQuerySyncVersions.clear();
15644
- lastItemSyncVersions.clear();
15645
- clearOfflineOverlays();
15646
- },
15647
- transportFactory: testOptions?.browserTabsTransportFactory,
15648
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
15649
- getWindowIsFocused,
15650
- onWindowFocusChange: testOptions?.onWindowFocusChange,
15651
- priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
15652
- }));
15653
15593
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
15654
15594
  const offlineEntities = useOfflineStoreEntities({
15655
15595
  sessionKey: getSessionKeyForRuntime(),
@@ -15664,7 +15604,7 @@ function createListQueryStore(storeOptions) {
15664
15604
  return state;
15665
15605
  }, []);
15666
15606
  const offlineOverlays = offlineOverlayStore.useSelectorRC(offlineOverlaysSelector);
15667
- return useMultipleListQueries(queries, options, store, events, getQueryKey, registerActiveQueryRefs, touchQueries, getQueryState, persistence?.readHydratedQuery, persistence ? (payloads) => persistence.maybeHydrateQueries(payloads.map((payload) => getQueryKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence && derivedQueries ? (payloads) => persistence.preloadItemsByDerivedQueryGroup(payloads.map((payload) => derivedQueries.getQueryGroup(payload))) : void 0, persistence?.readHydratedItem, scheduleAutomaticListQueryFetch, queryInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, globalDisableRefetchOnMount, partialResources, derivedQueries, isStoreOfflineMode, offlineEntities, offlineOverlays);
15607
+ return useMultipleListQueries(queries, options, store, events, getQueryKey, registerActiveQueryRefs, touchQueries, getQueryState, persistence?.readHydratedQuery, persistence ? (payloads) => persistence.maybeHydrateQueries(payloads.map((payload) => getQueryKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence && derivedQueries ? (payloads) => persistence.preloadItemsByDerivedQueryGroup(payloads.map((payload) => derivedQueries.getQueryGroup(payload))) : void 0, persistence?.readHydratedItem, scheduleAutomaticListQueryFetch, queryInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, partialResources, derivedQueries, isStoreOfflineMode, offlineEntities, offlineOverlays);
15668
15608
  };
15669
15609
  const useListQuery$2 = function useListQuery$1(payload, options = {}) {
15670
15610
  return useListQuery(payload, options, store, getQueryKey, scheduleListQueryFetch, useMultipleListQueries$2);
@@ -15679,7 +15619,7 @@ function createListQueryStore(storeOptions) {
15679
15619
  return state;
15680
15620
  }, []);
15681
15621
  const offlineOverlays = offlineOverlayStore.useSelectorRC(offlineOverlaysSelector);
15682
- return useMultipleItems(items, options, store, events, getItemKey, registerActiveStandaloneItems, touchItems, scheduleAutomaticItemFetch, persistence ? (payloads) => persistence.maybeHydrateItems(payloads.map((payload) => getItemKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence?.readHydratedItem, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays);
15622
+ return useMultipleItems(items, options, store, events, getItemKey, registerActiveStandaloneItems, touchItems, scheduleAutomaticItemFetch, persistence ? (payloads) => persistence.maybeHydrateItems(payloads.map((payload) => getItemKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence?.readHydratedItem, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays);
15683
15623
  };
15684
15624
  const useItem$3 = function useItem$2(itemPayload, options = {}) {
15685
15625
  return useItem(itemPayload, options, store, scheduleItemFetch, useMultipleItems$3);
@@ -15705,43 +15645,23 @@ function createListQueryStore(storeOptions) {
15705
15645
  function useFindItem$1(findItemFn, options = {}) {
15706
15646
  return useFindItem(findItemFn, options, store, registerActiveStandaloneItems, touchItems);
15707
15647
  }
15708
- const focusLifecycle = createStoreFocusLifecycle({
15709
- revalidateOnWindowFocus: resolvedRevalidateOnWindowFocus,
15710
- usesRealTimeUpdates,
15711
- transportReconnectCooldownMs,
15712
- getWindowIsFocused,
15713
- onWindowFocus: testOptions?.onWindowFocus ?? onWindowFocus,
15714
- onWindowFocusRevalidate: () => {
15715
- invalidateQueryAndItems({
15716
- all: true,
15717
- type: "lowPriority"
15718
- });
15719
- },
15720
- onTransportReconnectRevalidate: () => {
15721
- invalidateQueryAndItems({
15722
- all: true,
15723
- type: "realtimeUpdate"
15724
- });
15725
- }
15726
- });
15727
- const { enforceCacheLimits } = createListQueryCacheLimits({
15728
- store,
15729
- maxItems,
15730
- maxQueries,
15731
- itemCacheRuntime,
15732
- queryCacheRuntime,
15733
- isQueryProtectedFromEviction,
15734
- isStandaloneItemProtectedFromEviction,
15735
- cleanupItemStateMetadata,
15736
- cleanupQueryStateMetadata,
15737
- deleteQueryFetchResources,
15738
- deleteItemFetchResources,
15739
- onStateCleanup
15740
- });
15741
- const cacheLimitEnforcementScheduler = createIdleThrottledScheduler({
15742
- throttleMs: CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS,
15743
- run: enforceCacheLimits
15744
- });
15648
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
15649
+ invalidateQueryAndItems({
15650
+ all: true,
15651
+ type: "lowPriority"
15652
+ });
15653
+ }, () => {
15654
+ invalidateQueryAndItems({
15655
+ all: true,
15656
+ type: "realtimeUpdate"
15657
+ });
15658
+ }, reevaluateDelayedRTUs, import.meta.env.DEV ? {
15659
+ debugLogger: storeManager.debugLogger,
15660
+ storeId: id,
15661
+ storeType: "listQuery"
15662
+ } : void 0);
15663
+ const { enforceCacheLimits } = createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup);
15664
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
15745
15665
  function scheduleCacheLimitEnforcement() {
15746
15666
  cacheLimitEnforcementScheduler.schedule();
15747
15667
  }
@@ -15781,7 +15701,6 @@ function createListQueryStore(storeOptions) {
15781
15701
  queryCacheRuntime.clearAll();
15782
15702
  itemCacheRuntime.clearAll();
15783
15703
  cacheLimitEnforcementScheduler.cancel();
15784
- browserTabsPriority?.reset();
15785
15704
  persistence?.dispose();
15786
15705
  persistence?.clear();
15787
15706
  store.setState(persistence?.createInitialState({
@@ -15813,8 +15732,7 @@ function createListQueryStore(storeOptions) {
15813
15732
  queryCacheRuntime.clearAll();
15814
15733
  itemCacheRuntime.clearAll();
15815
15734
  cacheLimitEnforcementScheduler.cancel();
15816
- browserTabsSync?.close();
15817
- browserTabsPriority?.close();
15735
+ browserTabsSync.close();
15818
15736
  focusLifecycle.dispose();
15819
15737
  persistence?.dispose();
15820
15738
  offlineController?.dispose();