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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as 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
@@ -7151,6 +7072,23 @@ var RequestScheduler = class {
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
+ const rtu = this.#state.pending.rtuDelayed;
7082
+ if (!rtu || !this.#dynamicRealtimeThrottleMs) return;
7083
+ const { timing } = this.#state;
7084
+ if (timing.lastFetchStartTime + timing.lastFetchDuration + this.#dynamicRealtimeThrottleMs(timing.lastFetchDuration) >= rtu.fireAt) return;
7085
+ clearTimeout(rtu.timeoutId);
7086
+ this.#state.pending.rtuDelayed = null;
7087
+ if (!this.#scheduleDelayedRTU(Date.now(), rtu.requestId, rtu.payload, rtu.remoteStartCancelable)) {
7088
+ this.#onEvent?.("scheduled-rt-fetch-started");
7089
+ this.#scheduleRequest(rtu.requestId, "highPriority", rtu.payload, void 0, rtu.remoteStartCancelable);
7090
+ }
7091
+ }
7154
7092
  cancelCoalescingRequests(requestIds) {
7155
7093
  return this.#cancelCoalescingRequests(requestIds, false, void 0);
7156
7094
  }
@@ -7479,7 +7417,8 @@ var RequestScheduler = class {
7479
7417
  payload,
7480
7418
  priority: "realtimeUpdate",
7481
7419
  addedAt: startTime,
7482
- remoteStartCancelable
7420
+ remoteStartCancelable,
7421
+ fireAt: startTime + delay
7483
7422
  };
7484
7423
  this.#onEvent?.("rt-fetch-scheduled", { delayMs: delay });
7485
7424
  return true;
@@ -7579,8 +7518,9 @@ var RequestScheduler = class {
7579
7518
  };
7580
7519
  //#endregion
7581
7520
  //#region src/storeManager.ts
7582
- const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 5;
7583
- const DEFAULT_BASE_COALESCING_WINDOW_MS = 10;
7521
+ const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 2400 * 1e3;
7522
+ const DEFAULT_BASE_COALESCING_WINDOW_MS = 16;
7523
+ const DEFAULT_BACKGROUND_COALESCING_DELAY_MS = 3e3;
7584
7524
  function defaultDynamicRealtimeThrottleMs({ windowIsNotFocused }) {
7585
7525
  return windowIsNotFocused ? 1e3 : 100;
7586
7526
  }
@@ -7628,7 +7568,8 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
7628
7568
  };
7629
7569
  }
7630
7570
  function createStoreManager(options) {
7631
- const debugLogger = import.meta.env.DEV ? resolveTSDFDebugLogger(options.debug) : void 0;
7571
+ const debugLogger = import.meta.env.DEV ? resolveTSDFLogger(options.debugLogger) : void 0;
7572
+ const logger = resolveTSDFLogger(options.logger ?? true);
7632
7573
  let resolvedOfflineSession;
7633
7574
  if (options.offlineSession) {
7634
7575
  const createOfflineSessionOptions = {
@@ -7663,6 +7604,7 @@ function createStoreManager(options) {
7663
7604
  useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
7664
7605
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
7665
7606
  const registry = {
7607
+ browserTabsPresence: void 0,
7666
7608
  nextStoreRegistrationId: 0,
7667
7609
  stores: /* @__PURE__ */ new Map()
7668
7610
  };
@@ -7674,6 +7616,7 @@ function createStoreManager(options) {
7674
7616
  storeDefaults: Object.freeze({
7675
7617
  lowPriorityThrottleMs: options.lowPriorityThrottleMs ?? DEFAULT_LOW_PRIORITY_THROTTLE_MS,
7676
7618
  baseCoalescingWindowMs: options.baseCoalescingWindowMs ?? DEFAULT_BASE_COALESCING_WINDOW_MS,
7619
+ backgroundCoalescingDelayMs: options.backgroundCoalescingDelayMs ?? DEFAULT_BACKGROUND_COALESCING_DELAY_MS,
7677
7620
  dynamicRealtimeThrottleMs: options.dynamicRealtimeThrottleMs ?? defaultDynamicRealtimeThrottleMs,
7678
7621
  blockWindowClose: options.blockWindowClose ?? null,
7679
7622
  revalidateOnWindowFocus: options.revalidateOnWindowFocus
@@ -7691,14 +7634,19 @@ function createStoreManager(options) {
7691
7634
  },
7692
7635
  ...offlineApi
7693
7636
  };
7694
- if (debugLogger !== void 0) storeManager.debugLogger = debugLogger;
7637
+ storeManager.debugLogger = debugLogger;
7638
+ storeManager.logger = logger;
7695
7639
  storeManagerRegistry.set(storeManager, registry);
7696
7640
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
7697
7641
  return storeManager;
7698
7642
  }
7699
- function registerStoreWithManager(storeManager, store) {
7643
+ function getRegistryOrThrow(storeManager) {
7700
7644
  const registry = storeManagerRegistry.get(storeManager);
7701
7645
  if (!registry) throw new Error("[tsdf] storeManager must be created with createStoreManager(...)");
7646
+ return registry;
7647
+ }
7648
+ function registerStoreWithManager(storeManager, store) {
7649
+ const registry = getRegistryOrThrow(storeManager);
7702
7650
  let hasDuplicateId = false;
7703
7651
  for (const registeredStore of registry.stores.values()) if (registeredStore.id === store.id) {
7704
7652
  hasDuplicateId = true;
@@ -7710,23 +7658,45 @@ function registerStoreWithManager(storeManager, store) {
7710
7658
  registry.stores.set(registrationId, store);
7711
7659
  return () => {
7712
7660
  registry.stores.delete(registrationId);
7661
+ if (registry.stores.size === 0) {
7662
+ registry.browserTabsPresence?.close();
7663
+ registry.browserTabsPresence = void 0;
7664
+ }
7665
+ };
7666
+ }
7667
+ function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
7668
+ const registry = getRegistryOrThrow(storeManager);
7669
+ const presence = registry.browserTabsPresence ??= createBrowserTabsPresencePriority({
7670
+ getSessionKey: storeManager.getSessionKey,
7671
+ getWindowIsFocused: options.getWindowIsFocused,
7672
+ onWindowFocusChange: options.onWindowFocusChange,
7673
+ transportFactory: options.transportFactory,
7674
+ ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
7675
+ priorityTimings: {
7676
+ backgroundCoalescingDelayMs: storeManager.storeDefaults.backgroundCoalescingDelayMs,
7677
+ ...options.priorityTimings
7678
+ }
7679
+ });
7680
+ return {
7681
+ priority: presence.priority,
7682
+ tabId: presence.tabId
7713
7683
  };
7714
7684
  }
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`);
7685
+ function resolveStoreManagerOfflineSession(storeManager, storeName, usesOfflineStorage) {
7686
+ const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(storeManager));
7687
+ if (!usesOfflineStorage) return null;
7688
+ if (!offlineSession) throw new Error(`[tsdf] Store "${storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
7719
7689
  return offlineSession;
7720
7690
  }
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}"`);
7691
+ function validateStoreManagerSessionConsistency(storeName, offlineSession, getSessionKey) {
7692
+ const sessionKey = getSessionKey();
7693
+ const offlineSessionKey = offlineSession.getSessionKey();
7694
+ if (sessionKey !== offlineSessionKey) throw new Error(`[tsdf] Store "${storeName}" is attached to offline session "${offlineSessionKey}" but storeManager.getSessionKey() returned "${sessionKey}"`);
7725
7695
  return sessionKey;
7726
7696
  }
7727
7697
  //#endregion
7728
7698
  //#region src/utils/performMutation.ts
7729
- async function performMutationWithLifecycle({ startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose }) {
7699
+ async function performMutationWithLifecycle(startMutation, mutation, onError, optimisticUpdate, onSuccess, debounce, blockWindowClose) {
7730
7700
  const endMutation = startMutation();
7731
7701
  if (optimisticUpdate?.() === false) {
7732
7702
  endMutation();
@@ -7758,7 +7728,7 @@ async function performMutationWithLifecycle({ startMutation, mutation, onError,
7758
7728
  //#endregion
7759
7729
  //#region src/utils/storeFocusLifecycle.ts
7760
7730
  /** @internal */
7761
- function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate }) {
7731
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate, onWindowFocusReevaluateDelayedRTU, debug) {
7762
7732
  let cleanupFocusListener = null;
7763
7733
  let cleanupReconnectFocusListener = null;
7764
7734
  let reconnectCooldownTimeoutId = null;
@@ -7778,6 +7748,19 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7778
7748
  if (typeof revalidateOnWindowFocus === "function") return revalidateOnWindowFocus();
7779
7749
  return !!revalidateOnWindowFocus;
7780
7750
  }
7751
+ const logWindowFocusRevalidate = import.meta.env.DEV && debug?.debugLogger ? (message, details) => {
7752
+ emitTSDFDebugLog(debug.debugLogger, {
7753
+ area: "focus",
7754
+ level: "log",
7755
+ message,
7756
+ operation: "window-focus-revalidate",
7757
+ details: {
7758
+ storeId: debug.storeId,
7759
+ storeType: debug.storeType,
7760
+ ...details
7761
+ }
7762
+ });
7763
+ } : void 0;
7781
7764
  function runTransportReconnectRevalidate() {
7782
7765
  lastTransportReconnectRevalidateAt = Date.now();
7783
7766
  onTransportReconnectRevalidate();
@@ -7816,9 +7799,29 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7816
7799
  clearReconnectCooldownTimeout();
7817
7800
  hasPendingReconnectRevalidateOnFocus = false;
7818
7801
  lastTransportReconnectRevalidateAt = Number.NEGATIVE_INFINITY;
7819
- if (!revalidateOnWindowFocus || usesRealTimeUpdates) return;
7802
+ if (usesRealTimeUpdates) {
7803
+ if (revalidateOnWindowFocus) logWindowFocusRevalidate?.("window focus revalidation skipped", {
7804
+ reason: "real-time-updates",
7805
+ status: "skipped"
7806
+ });
7807
+ cleanupFocusListener = onWindowFocus(onWindowFocusReevaluateDelayedRTU);
7808
+ return;
7809
+ }
7810
+ if (!revalidateOnWindowFocus) return;
7820
7811
  cleanupFocusListener = onWindowFocus(() => {
7821
- if (isFocusRevalidationEnabled()) onWindowFocusRevalidate();
7812
+ if (!isFocusRevalidationEnabled()) {
7813
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
7814
+ policy: "dynamic",
7815
+ reason: "dynamic-disabled",
7816
+ status: "skipped"
7817
+ });
7818
+ return;
7819
+ }
7820
+ logWindowFocusRevalidate?.("window focus revalidation triggered", {
7821
+ policy: typeof revalidateOnWindowFocus === "function" ? "dynamic" : "enabled",
7822
+ status: "triggered"
7823
+ });
7824
+ onWindowFocusRevalidate();
7822
7825
  });
7823
7826
  }
7824
7827
  function dispose() {
@@ -7852,7 +7855,7 @@ function createStoreFocusLifecycle({ revalidateOnWindowFocus, usesRealTimeUpdate
7852
7855
  //#endregion
7853
7856
  //#region src/collectionStore/collectionCacheLimits.ts
7854
7857
  /** @internal */
7855
- function createCollectionCacheLimits({ store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup }) {
7858
+ function createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup) {
7856
7859
  let isEnforcingCacheLimits = false;
7857
7860
  function enforceCacheLimits() {
7858
7861
  if (maxItems === void 0 || isEnforcingCacheLimits) return;
@@ -7897,7 +7900,7 @@ const offlineConnectivityError = {
7897
7900
  function normalizeFetchResultError(fetchResult, errorNormalizer) {
7898
7901
  return fetchResult.offline ? offlineConnectivityError : normalizeStoreError(fetchResult.error, errorNormalizer);
7899
7902
  }
7900
- async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7903
+ async function runOfflineAwareFetch(controller, fetcher, operationName) {
7901
7904
  await controller?.prepareForFetch?.();
7902
7905
  const shouldTreatFetchAsOffline = () => controller?.shouldTreatFetchAsOffline?.() ?? controller?.getSessionStatus()?.isOfflineMode ?? false;
7903
7906
  if (shouldTreatFetchAsOffline()) return {
@@ -7926,7 +7929,7 @@ async function runOfflineAwareFetch({ controller, fetcher, operationName }) {
7926
7929
  }
7927
7930
  //#endregion
7928
7931
  //#region src/utils/reusePrevIfEqual.ts
7929
- function reusePrevIfEqual({ prev, current }) {
7932
+ function reusePrevIfEqual(prev, current) {
7930
7933
  if (prev === void 0) return current;
7931
7934
  if (deepEqual(prev, current)) return prev;
7932
7935
  return current;
@@ -7963,10 +7966,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
7963
7966
  }
7964
7967
  if (batchFetchFn && requests.length > 1) try {
7965
7968
  const payloads = requests.map((r) => r.payload);
7966
- const fetchResult = await runOfflineAwareFetch({
7967
- controller: offlineController,
7968
- fetcher: () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__")
7969
- });
7969
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchFn(payloads, fetchCtx.signal, batchKey ?? "__default__"));
7970
7970
  if (!fetchResult.ok) {
7971
7971
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
7972
7972
  store.produceState((draft) => {
@@ -8000,10 +8000,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8000
8000
  item.status = "error";
8001
8001
  results.set(itemId, false);
8002
8002
  } else if (result !== void 0) try {
8003
- item.data = reusePrevIfEqual({
8004
- current: unwrapMaybeTSDFResult(result),
8005
- prev: item.data
8006
- });
8003
+ item.data = reusePrevIfEqual(item.data, unwrapMaybeTSDFResult(result));
8007
8004
  item.status = "success";
8008
8005
  item.wasLoaded = true;
8009
8006
  results.set(itemId, true);
@@ -8039,10 +8036,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8039
8036
  }
8040
8037
  const fetchPromises = requests.map(async ({ requestId: itemId, payload }) => {
8041
8038
  try {
8042
- const fetchResult = await runOfflineAwareFetch({
8043
- controller: offlineController,
8044
- fetcher: () => fetchFn(klona(payload), fetchCtx.signal)
8045
- });
8039
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchFn(klona(payload), fetchCtx.signal));
8046
8040
  if (!fetchResult.ok) {
8047
8041
  if (fetchCtx.shouldAbort()) {
8048
8042
  results.set(itemId, false);
@@ -8071,10 +8065,7 @@ async function executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchF
8071
8065
  store.produceState((draft) => {
8072
8066
  const item = draft[itemId];
8073
8067
  if (!item) return;
8074
- item.data = reusePrevIfEqual({
8075
- current: data,
8076
- prev: item.data
8077
- });
8068
+ item.data = reusePrevIfEqual(item.data, data);
8078
8069
  item.status = "success";
8079
8070
  item.wasLoaded = true;
8080
8071
  }, { action: "fetch-success" });
@@ -8307,8 +8298,7 @@ function createFieldsResourceSignature(fields) {
8307
8298
  if (fields === void 0) return "";
8308
8299
  return JSON.stringify(Array.from(new Set(fields)).sort());
8309
8300
  }
8310
- function shouldScheduleAutomaticFetch(options) {
8311
- const { wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false } = options;
8301
+ function shouldScheduleAutomaticFetch(wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, skipFreshFetch = false) {
8312
8302
  if (disableRefetches) return !wasLoaded;
8313
8303
  if (disableRefetchOnMount) return shouldFetch;
8314
8304
  if (skipFreshFetch && !shouldFetch) return false;
@@ -8503,14 +8493,7 @@ function useMultipleItems$1(items, { selector, returnIdleStatus: allItemsReturnI
8503
8493
  const shouldFetch = requiredFetch || !!itemState.refetchOnMount;
8504
8494
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemId)) continue;
8505
8495
  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);
8496
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount) && tryClaimAutomaticFetchSlot(automaticRetryState, itemId, itemState?.status)) scheduleAutomaticFetch(fetchType, payload);
8514
8497
  }
8515
8498
  }
8516
8499
  for (const itemId of removedQueries) ignoreItemsInRefetchOnMount.delete(itemId);
@@ -8551,18 +8534,9 @@ function createCollectionStore(storeOptions) {
8551
8534
  let offlineOverlaySessionKey = null;
8552
8535
  const itemCacheRuntime = createLruCacheRuntime();
8553
8536
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
8554
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
8555
- storeManager,
8556
- storeName: id,
8557
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
8558
- });
8537
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
8559
8538
  const getSessionKeyBase = storeManager.getSessionKey;
8560
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
8561
- storeManager,
8562
- storeName: id,
8563
- offlineSession: resolvedOfflineSession,
8564
- getSessionKey: getSessionKeyBase
8565
- });
8539
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
8566
8540
  const errorNormalizer = storeManager.errorNormalizer;
8567
8541
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
8568
8542
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -8575,7 +8549,8 @@ function createCollectionStore(storeOptions) {
8575
8549
  ...persistentStorageConfig.offline,
8576
8550
  session: resolvedOfflineSessionForPersistentStorage
8577
8551
  } : void 0,
8578
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8552
+ debugLogger: storeManager.debugLogger,
8553
+ logger: storeManager.logger,
8579
8554
  getSessionKey: getSessionKeyForRuntime,
8580
8555
  storeName: id
8581
8556
  }) : null;
@@ -8596,100 +8571,76 @@ function createCollectionStore(storeOptions) {
8596
8571
  offlineOverlayStore.setState({});
8597
8572
  }
8598
8573
  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
- });
8574
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
8575
+ data: existingOverlay.data ?? null,
8576
+ payload: store.state[nextItemKey]?.payload ?? existingOverlay.payload,
8577
+ keepVisibleWhileResolutionRequired: true
8578
+ }));
8608
8579
  }
8609
8580
  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
- }
8581
+ captureOfflineOverlayEntries(offlineOverlayStore, itemKeys, (itemKey) => {
8582
+ const item = store.state[itemKey];
8583
+ return {
8584
+ data: item ? klona(item.data) : null,
8585
+ payload: item ? klona(item.payload) : void 0
8586
+ };
8620
8587
  });
8621
8588
  }
8622
8589
  const resolvedOfflineConfig = resolvedPersistentStorageConfig?.offline;
8623
8590
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_COLLECTION_OFFLINE_OPERATIONS);
8624
8591
  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
- }
8592
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "collection", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
8593
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
8594
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
8595
+ if (normalizedRef !== null) return normalizedRef;
8596
+ return {
8597
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
8598
+ entityKind: "item"
8599
+ };
8600
+ }),
8601
+ getProtectedCacheKeys: (entityRefs) => {
8602
+ const sessionKey = getSessionKeyForRuntime();
8603
+ if (sessionKey === false) return [];
8604
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "collection.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
8605
+ },
8606
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
8607
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
8608
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
8609
+ },
8610
+ rollbackPendingEntity: ({ tempId }) => {
8611
+ deleteItemState(__LEGIT_CAST__(tempId));
8612
+ },
8613
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
8614
+ const tempPayload = __LEGIT_CAST__(tempId);
8615
+ const currentItem = getItemState(tempPayload);
8616
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem?.data ?? void 0;
8617
+ if (finalData === void 0) return;
8618
+ deleteItemState(tempPayload);
8619
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
8620
+ addItemToState(finalPayload, finalData);
8621
+ storeEvents.emit("tempEntityReconciled", {
8622
+ tempId: tempPayload,
8623
+ finalPayload
8624
+ });
8625
+ },
8626
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
8627
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8628
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
8629
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
8630
+ }));
8631
+ },
8632
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
8633
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8634
+ rebindOfflineOverlays(itemKeyRewrites);
8635
+ },
8636
+ syncEntityOverlays: ({ entities, sessionKey }) => {
8637
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
8638
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
8639
+ offlineOverlayStore.produceState((draft) => {
8640
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
8641
+ });
8691
8642
  }
8692
- }) : null;
8643
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
8693
8644
  function touchItems(itemKeys) {
8694
8645
  itemCacheRuntime.touch(itemKeys, (itemKey) => {
8695
8646
  return store.state[itemKey] !== void 0;
@@ -8931,10 +8882,6 @@ function createCollectionStore(storeOptions) {
8931
8882
  return getKnownScheduler(message.itemKey)?.isMutationInProgress(message.itemKey) ?? false;
8932
8883
  }
8933
8884
  function handleRemoteMessage(message) {
8934
- if (message.kind === "tab-status") {
8935
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
8936
- return;
8937
- }
8938
8885
  if (message.kind === "fetch-start") {
8939
8886
  const scheduler = getSchedulerForTargetKey(message.targetKey);
8940
8887
  scheduler?.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -8953,21 +8900,16 @@ function createCollectionStore(storeOptions) {
8953
8900
  }
8954
8901
  applyRemoteItemSnapshot(message, candidateVersion);
8955
8902
  }
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,
8903
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
8967
8904
  getWindowIsFocused,
8968
8905
  onWindowFocusChange: testOptions?.onWindowFocusChange,
8906
+ transportFactory: testOptions?.browserTabsTransportFactory,
8969
8907
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
8970
8908
  });
8909
+ const browserTabsSync = createBrowserTabsCoordinator("collection", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
8910
+ lastCollectionSyncVersions.clear();
8911
+ clearOfflineOverlays();
8912
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
8971
8913
  async function executeBatchFetch$1(requests, fetchCtx, batchKey) {
8972
8914
  const results = await executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchFn, errorNormalizer, batchKey, offlineController);
8973
8915
  const successfulRequests = requests.filter(({ requestId }) => results.get(requestId) === true);
@@ -9246,50 +9188,37 @@ function createCollectionStore(storeOptions) {
9246
9188
  item: klona(store.state[itemKey])
9247
9189
  })) : [];
9248
9190
  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" });
9191
+ const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9192
+ kind: "online",
9193
+ data: await directMutation()
9194
+ }), (exception) => {
9195
+ const error = toStoreMutationError(exception, errorNormalizer);
9196
+ if (optimisticRollbackSnapshots.length > 0) {
9197
+ const restoredItemKeys = [];
9198
+ runWithBroadcastConsistency("confirmed", () => {
9199
+ store.produceState((draft) => {
9281
9200
  for (const snapshot of optimisticRollbackSnapshots) {
9282
- if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9283
- else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9284
- publishItemSnapshot(snapshot.itemKey);
9201
+ if (snapshot.item === void 0) {
9202
+ delete draft[snapshot.itemKey];
9203
+ continue;
9204
+ }
9205
+ draft[snapshot.itemKey] = snapshot.item;
9285
9206
  }
9286
- });
9287
- if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9288
- }
9289
- if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9290
- return error;
9291
- }
9292
- });
9207
+ }, { action: "rollback-mutation-error" });
9208
+ for (const snapshot of optimisticRollbackSnapshots) {
9209
+ if (snapshot.item) restoredItemKeys.push(snapshot.itemKey);
9210
+ else cleanupItemResources(snapshot.itemKey, snapshot.payload);
9211
+ publishItemSnapshot(snapshot.itemKey);
9212
+ }
9213
+ });
9214
+ if (restoredItemKeys.length > 0) touchItemsAndMaybeEnforceLimits(restoredItemKeys);
9215
+ }
9216
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
9217
+ return error;
9218
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse)) : void 0, (result) => {
9219
+ if (revalidateOnSuccess && affectedItems.length > 0) invalidateItem(payloadToUse);
9220
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
9221
+ }, _debounce, blockWindowClose ?? void 0);
9293
9222
  storeEvents.emit("mutationEnd", {
9294
9223
  mutationId,
9295
9224
  items: affectedItems,
@@ -9298,31 +9227,20 @@ function createCollectionStore(storeOptions) {
9298
9227
  if (!offline && result.ok && result.value.kind === "online") return Result.ok(result.value.data);
9299
9228
  return result;
9300
9229
  }
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
- });
9230
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9231
+ invalidateItem(() => true, "lowPriority");
9232
+ }, () => {
9233
+ invalidateItem(() => true, "realtimeUpdate");
9234
+ }, () => {
9235
+ for (const scheduler of batchKeySchedulers.values()) scheduler.reevaluateDelayedRTU();
9236
+ for (const scheduler of perItemSchedulers.values()) scheduler.reevaluateDelayedRTU();
9237
+ }, import.meta.env.DEV ? {
9238
+ debugLogger: storeManager.debugLogger,
9239
+ storeId: id,
9240
+ storeType: "collection"
9241
+ } : void 0);
9242
+ const { enforceCacheLimits } = createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup);
9243
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
9326
9244
  function scheduleCacheLimitEnforcement() {
9327
9245
  cacheLimitEnforcementScheduler.schedule();
9328
9246
  }
@@ -9358,7 +9276,6 @@ function createCollectionStore(storeOptions) {
9358
9276
  clearOfflineOverlays();
9359
9277
  itemCacheRuntime.clearAll();
9360
9278
  cacheLimitEnforcementScheduler.cancel();
9361
- browserTabsPriority.reset();
9362
9279
  persistence?.dispose();
9363
9280
  persistence?.clear();
9364
9281
  store.setState(persistence?.createInitialState({}) ?? {});
@@ -9381,7 +9298,6 @@ function createCollectionStore(storeOptions) {
9381
9298
  itemCacheRuntime.clearAll();
9382
9299
  cacheLimitEnforcementScheduler.cancel();
9383
9300
  browserTabsSync.close();
9384
- browserTabsPriority.close();
9385
9301
  focusLifecycle.dispose();
9386
9302
  persistence?.dispose();
9387
9303
  offlineController?.dispose();
@@ -9709,18 +9625,9 @@ function createDocumentStore(storeOptions) {
9709
9625
  let initialStatus = "idle";
9710
9626
  let initialError = null;
9711
9627
  const globalDisableRefetchOnMount = usesRealTimeUpdates;
9712
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
9713
- storeManager,
9714
- storeName: id,
9715
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
9716
- });
9628
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
9717
9629
  const getSessionKeyBase = storeManager.getSessionKey;
9718
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
9719
- storeManager,
9720
- storeName: id,
9721
- offlineSession: resolvedOfflineSession,
9722
- getSessionKey: getSessionKeyBase
9723
- });
9630
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
9724
9631
  const errorNormalizer = storeManager.errorNormalizer;
9725
9632
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
9726
9633
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -9733,7 +9640,8 @@ function createDocumentStore(storeOptions) {
9733
9640
  ...persistentStorageConfig.offline,
9734
9641
  session: resolvedOfflineSessionForPersistentStorage
9735
9642
  } : void 0,
9736
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9643
+ debugLogger: storeManager.debugLogger,
9644
+ logger: storeManager.logger,
9737
9645
  getSessionKey: getSessionKeyForRuntime,
9738
9646
  storeName: id
9739
9647
  }) : null;
@@ -9743,55 +9651,39 @@ function createDocumentStore(storeOptions) {
9743
9651
  const resolvedOfflineOperations = __LEGIT_CAST__(resolvedOfflineConfig?.operations ?? EMPTY_DOCUMENT_OFFLINE_OPERATIONS);
9744
9652
  if (import.meta.env.DEV) assertDocumentOfflineOperations(__LEGIT_CAST__(resolvedOfflineOperations));
9745
9653
  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
- }
9654
+ const offlineController = resolvedPersistentStorageConfig && resolvedOfflineConfig ? createOfflineStoreController(id, "document", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
9655
+ getEntityRefs: () => [{
9656
+ entityKey: DOC_TARGET_KEY,
9657
+ entityKind: "document"
9658
+ }],
9659
+ normalizeEntityRefs: () => [{
9660
+ entityKey: DOC_TARGET_KEY,
9661
+ entityKind: "document"
9662
+ }],
9663
+ getProtectedCacheKeys: () => {
9664
+ const sessionKey = getSessionKeyForRuntime();
9665
+ if (sessionKey === false) return [];
9666
+ return [createProtectedStorageKey(sessionKey, id, "document", "d", resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage")];
9667
+ },
9668
+ applyPendingEntity: ({ pendingEntity }) => {
9669
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
9670
+ updateState((draft) => Object.assign(draft, pendingEntity));
9671
+ },
9672
+ reconcileTempEntity: ({ reconciliation }) => {
9673
+ if (!reconciliation.finalData || typeof reconciliation.finalData !== "object") return;
9674
+ updateState((draft) => Object.assign(draft, reconciliation.finalData));
9675
+ },
9676
+ captureQueuedMutationOverlays: ({ sessionKey }) => {
9677
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9678
+ offlineOverlayStore.setState({ data: klona(store.state.data) });
9679
+ },
9680
+ syncEntityOverlays: ({ entities, sessionKey }) => {
9681
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlay(sessionKey);
9682
+ if (!entities.some((entity) => {
9683
+ return entity.entityKey === DOC_TARGET_KEY;
9684
+ })) offlineOverlayStore.setState(null);
9793
9685
  }
9794
- }) : null;
9686
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime)) : null;
9795
9687
  const store = new Store({
9796
9688
  debugName: id,
9797
9689
  state: () => persistence?.createInitialState({
@@ -9849,10 +9741,7 @@ function createDocumentStore(storeOptions) {
9849
9741
  }
9850
9742
  runWithoutBroadcast(() => {
9851
9743
  store.setPartialState({
9852
- data: reusePrevIfEqual({
9853
- prev: store.state.data,
9854
- current: message.data
9855
- }),
9744
+ data: reusePrevIfEqual(store.state.data, message.data),
9856
9745
  error: null,
9857
9746
  status: "success",
9858
9747
  refetchOnMount: false
@@ -9865,10 +9754,6 @@ function createDocumentStore(storeOptions) {
9865
9754
  return message.consistency === "confirmed" && scheduler.isMutationInProgress(DOC_REQUEST_ID);
9866
9755
  }
9867
9756
  function handleRemoteMessage(message) {
9868
- if (message.kind === "tab-status") {
9869
- browserTabsPriority.onTabStatusMessage(message.tabId, message);
9870
- return;
9871
- }
9872
9757
  if (message.kind === "fetch-start") {
9873
9758
  if (!hasLocalDocumentState()) return;
9874
9759
  scheduler.syncExternalFetchStart(message.requestIds, message.startedAt);
@@ -9888,21 +9773,16 @@ function createDocumentStore(storeOptions) {
9888
9773
  }
9889
9774
  applyRemoteDocumentSnapshot(message, candidateVersion);
9890
9775
  }
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,
9776
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
9902
9777
  getWindowIsFocused,
9903
9778
  onWindowFocusChange: testOptions?.onWindowFocusChange,
9779
+ transportFactory: testOptions?.browserTabsTransportFactory,
9904
9780
  priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
9905
9781
  });
9782
+ const browserTabsSync = createBrowserTabsCoordinator("document", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
9783
+ lastDocumentSyncVersion = void 0;
9784
+ clearOfflineOverlay();
9785
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
9906
9786
  async function executeFetch(fetchCtx) {
9907
9787
  const currentStatus = store.state.status;
9908
9788
  const wasLoadedBeforeFetch = currentStatus === "success";
@@ -9912,10 +9792,7 @@ function createDocumentStore(storeOptions) {
9912
9792
  refetchOnMount: false
9913
9793
  }, { action: currentStatus === "success" ? "fetch-start-refetching" : "fetch-start-loading" });
9914
9794
  try {
9915
- const result = await runOfflineAwareFetch({
9916
- controller: offlineController,
9917
- fetcher: () => fetchFn(fetchCtx.signal)
9918
- });
9795
+ const result = await runOfflineAwareFetch(offlineController, () => fetchFn(fetchCtx.signal));
9919
9796
  if (!result.ok) {
9920
9797
  if (result.offline) {
9921
9798
  store.setPartialState(wasLoadedBeforeFetch ? {
@@ -9932,10 +9809,7 @@ function createDocumentStore(storeOptions) {
9932
9809
  const data = result.data;
9933
9810
  if (fetchCtx.shouldAbort()) return false;
9934
9811
  store.setPartialState({
9935
- data: reusePrevIfEqual({
9936
- prev: store.state.data,
9937
- current: data
9938
- }),
9812
+ data: reusePrevIfEqual(store.state.data, data),
9939
9813
  status: "success"
9940
9814
  }, { action: "fetch-success" });
9941
9815
  return true;
@@ -9987,19 +9861,17 @@ function createDocumentStore(storeOptions) {
9987
9861
  usesRealTimeUpdates
9988
9862
  });
9989
9863
  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
- });
9864
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
9865
+ invalidateData("lowPriority");
9866
+ }, () => {
9867
+ invalidateData("realtimeUpdate");
9868
+ }, () => {
9869
+ scheduler.reevaluateDelayedRTU();
9870
+ }, import.meta.env.DEV ? {
9871
+ debugLogger: storeManager.debugLogger,
9872
+ storeId: id,
9873
+ storeType: "document"
9874
+ } : void 0);
10003
9875
  persistence?.attach(store);
10004
9876
  initializeOfflineStoreController(offlineController);
10005
9877
  function scheduleFetch(fetchType, options) {
@@ -10085,7 +9957,6 @@ function createDocumentStore(storeOptions) {
10085
9957
  scheduler.reset();
10086
9958
  lastDocumentSyncVersion = void 0;
10087
9959
  clearOfflineOverlay();
10088
- browserTabsPriority.reset();
10089
9960
  persistence?.dispose();
10090
9961
  persistence?.clear();
10091
9962
  store.setState({
@@ -10106,7 +9977,6 @@ function createDocumentStore(storeOptions) {
10106
9977
  lastDocumentSyncVersion = void 0;
10107
9978
  clearOfflineOverlay();
10108
9979
  browserTabsSync.close();
10109
- browserTabsPriority.close();
10110
9980
  focusLifecycle.dispose();
10111
9981
  persistence?.dispose();
10112
9982
  offlineController?.dispose();
@@ -10123,32 +9993,19 @@ function createDocumentStore(storeOptions) {
10123
9993
  updateState,
10124
9994
  currentState: store.state.data
10125
9995
  }));
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
- });
9996
+ const result = await performMutationWithLifecycle(startMutation, offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
9997
+ kind: "online",
9998
+ data: await directMutation()
9999
+ }), (exception) => {
10000
+ if (optimisticUpdate) runWithBroadcastConsistency("confirmed", () => {
10001
+ store.setKey("data", optimisticRollbackSnapshot ?? null, { action: "rollback-mutation-error" });
10002
+ publishDocumentSnapshot();
10003
+ });
10004
+ if (resolvedOnMutationError) resolvedOnMutationError(exception, { silentErrors });
10005
+ return toStoreMutationError(exception, errorNormalizer);
10006
+ }, optimisticUpdate ? () => runWithBroadcastConsistency("optimistic", () => optimisticUpdate(store.state.data)) : void 0, (result) => {
10007
+ if (revalidateOnSuccess && result.kind === "online") invalidateData();
10008
+ }, debounce, blockWindowClose ?? void 0);
10152
10009
  storeEvents.emit("mutationEnd", {
10153
10010
  mutationId,
10154
10011
  status: result.ok ? "success" : result.error === mutationSkipped ? "skipped" : "error"
@@ -10221,16 +10078,7 @@ function createDocumentStore(storeOptions) {
10221
10078
  }
10222
10079
  if (disabled) return;
10223
10080
  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);
10081
+ 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
10082
  })();
10235
10083
  return () => {
10236
10084
  effectState.cancelled = true;
@@ -10370,7 +10218,7 @@ function toItemState(persisted, dataSchema, shouldIgnoreItem) {
10370
10218
  const validated = parsePersistedStoreData(persisted.data, dataSchema);
10371
10219
  if (validated === null) return null;
10372
10220
  if (shouldIgnoreItem(persisted.payload)) return null;
10373
- const loadedFields = Array.isArray(persisted.loadedFields) ? Array.from(new Set(persisted.loadedFields)).sort() : Object.keys(validated).sort();
10221
+ const loadedFields = persisted.loadedFields === "*" ? "*" : Array.isArray(persisted.loadedFields) ? Array.from(new Set(persisted.loadedFields)).sort() : void 0;
10374
10222
  return {
10375
10223
  item: validated,
10376
10224
  itemQuery: {
@@ -10397,14 +10245,8 @@ function readManifestGroupMeta(meta) {
10397
10245
  function setupListQueryPersistence(config, options = {}) {
10398
10246
  assertValidPersistentStoreName(config.storeName);
10399
10247
  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
- });
10248
+ const defaultMaxItemBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.item");
10249
+ const defaultMaxQueryBytes = getDefaultMaxBytesForScope(config.adapter, "listQuery.query");
10408
10250
  const maxItemBytes = config.maxItemBytes ?? defaultMaxItemBytes;
10409
10251
  const maxQueryBytes = config.maxQueryBytes ?? defaultMaxQueryBytes;
10410
10252
  const maxQuerySize = config.maxQuerySize ?? DEFAULT_MAX_QUERY_SIZE;
@@ -10431,7 +10273,7 @@ function setupListQueryPersistence(config, options = {}) {
10431
10273
  deserialize: (value, metadata) => typeof value === "object" && value !== null && "d" in value && ("p" in value || metadata?.p !== void 0) ? parsePersistedListQueryItemData({
10432
10274
  data: value.d,
10433
10275
  payload: "p" in value ? value.p : metadata?.p,
10434
- ..."lf" in value && Array.isArray(value.lf) ? { loadedFields: value.lf } : {}
10276
+ ..."lf" in value && (Array.isArray(value.lf) || value.lf === "*") ? { loadedFields: value.lf } : {}
10435
10277
  }, config.itemPayloadSchema, dataSchema) : null
10436
10278
  };
10437
10279
  const asyncItemStorageValueCodec = {
@@ -10439,7 +10281,7 @@ function setupListQueryPersistence(config, options = {}) {
10439
10281
  deserialize: (value, metadata) => metadata?.p !== void 0 ? parsePersistedListQueryItemData({
10440
10282
  data: value,
10441
10283
  payload: metadata.p,
10442
- ...Array.isArray(metadata.f) ? { loadedFields: metadata.f } : {}
10284
+ ...metadata.f !== void 0 ? { loadedFields: metadata.f } : {}
10443
10285
  }, config.itemPayloadSchema, dataSchema) : null
10444
10286
  };
10445
10287
  const queryStorageValueCodec = {
@@ -10467,7 +10309,7 @@ function setupListQueryPersistence(config, options = {}) {
10467
10309
  }, {
10468
10310
  asyncValueCodec: asyncItemStorageValueCodec,
10469
10311
  getManifestMeta: (data) => ({
10470
- ...Array.isArray(data.loadedFields) ? { f: data.loadedFields } : {},
10312
+ ...data.loadedFields !== void 0 ? { f: data.loadedFields } : {},
10471
10313
  p: data.payload
10472
10314
  }),
10473
10315
  valueCodec: itemStorageValueCodec
@@ -10483,6 +10325,45 @@ function setupListQueryPersistence(config, options = {}) {
10483
10325
  p: data.payload
10484
10326
  })
10485
10327
  });
10328
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
10329
+ function logQueryByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10330
+ const logger = config.logger;
10331
+ if (!logger) return;
10332
+ const evictedEntries = totalEntries - keptKeys.size;
10333
+ if (evictedEntries === 0) return;
10334
+ logPersistentStorageQuotaCleanup({
10335
+ adapter: quotaCleanupAdapter,
10336
+ logger,
10337
+ evictedEntries,
10338
+ keptEntries: keptKeys.size,
10339
+ maxBytes: maxQueryBytes,
10340
+ namespaceKind: "listQuery.query",
10341
+ phase,
10342
+ quota: "maxQueryBytes",
10343
+ storeName: config.storeName,
10344
+ totalEntries,
10345
+ unprotectedBytes
10346
+ });
10347
+ }
10348
+ function logItemByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10349
+ const logger = config.logger;
10350
+ if (!logger) return;
10351
+ const evictedEntries = totalEntries - keptKeys.size;
10352
+ if (evictedEntries === 0) return;
10353
+ logPersistentStorageQuotaCleanup({
10354
+ adapter: quotaCleanupAdapter,
10355
+ logger,
10356
+ evictedEntries,
10357
+ keptEntries: keptKeys.size,
10358
+ maxBytes: maxItemBytes,
10359
+ namespaceKind: "listQuery.item",
10360
+ phase,
10361
+ quota: "maxItemBytes",
10362
+ storeName: config.storeName,
10363
+ totalEntries,
10364
+ unprotectedBytes
10365
+ });
10366
+ }
10486
10367
  function getAsyncItemNamespaceScope() {
10487
10368
  if (asyncStorageAdapter === null) return null;
10488
10369
  const sessionKey = config.getSessionKey();
@@ -10507,38 +10388,18 @@ function setupListQueryPersistence(config, options = {}) {
10507
10388
  const asyncItemNamespaceScope = getAsyncItemNamespaceScope();
10508
10389
  if (asyncItemNamespaceScope === null) return JSON.stringify(args.value).length;
10509
10390
  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
- });
10391
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, args.nextCustomMetadata, args.protectedKeysSnapshotSet, asyncItemNamespaceScope, args.itemKey);
10392
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10522
10393
  }
10523
10394
  function estimateAsyncQueryEntrySizeBytes(args) {
10524
10395
  const asyncQueryNamespaceScope = getAsyncQueryNamespaceScope();
10525
10396
  if (asyncQueryNamespaceScope === null) return JSON.stringify(args.value).length;
10526
10397
  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
- });
10398
+ const customMetadata = mergeManagedAsyncStorageCustomMetadata(args.currentCustomMetadata, {
10399
+ ...args.value.hasMore ? { h: true } : {},
10400
+ p: args.value.payload
10401
+ }, args.protectedKeysSnapshotSet, asyncQueryNamespaceScope, args.queryKey);
10402
+ return estimateManagedAsyncStorageEntrySizeBytes(serializedValue.rawValue, args.lastAccessAt, version ?? 1, customMetadata);
10542
10403
  }
10543
10404
  let storeRef = null;
10544
10405
  let unsubscribe = null;
@@ -10553,6 +10414,8 @@ function setupListQueryPersistence(config, options = {}) {
10553
10414
  const querySizeBytesByKey = /* @__PURE__ */ new Map();
10554
10415
  const hydratedPersistedItemKeys = /* @__PURE__ */ new Set();
10555
10416
  const hydratedPersistedQueryKeys = /* @__PURE__ */ new Set();
10417
+ const budgetEvictedItemRecency = /* @__PURE__ */ new Map();
10418
+ const budgetEvictedQueryRecency = /* @__PURE__ */ new Map();
10556
10419
  const syncHydrationItemMissCache = createTimedKeySet();
10557
10420
  const syncHydrationQueryMissCache = createTimedKeySet();
10558
10421
  let knownPersistedItemKeys = null;
@@ -10870,13 +10733,42 @@ function setupListQueryPersistence(config, options = {}) {
10870
10733
  querySizeBytesByKey.delete(queryKey);
10871
10734
  knownPersistedQueryKeys?.delete(queryKey);
10872
10735
  }
10736
+ /**
10737
+ * Resolves the recency an in-state entry without persisted metadata should
10738
+ * compete with in the byte budget. Previously budget-evicted entries keep
10739
+ * their remembered (stale) recency while their content is unchanged, so they
10740
+ * deterministically lose again instead of churning back into storage; a
10741
+ * changed snapshot means the entry was genuinely refetched and counts as
10742
+ * freshly accessed.
10743
+ */
10744
+ function getBudgetEvictedLastAccessAt(memory, key, value, fallback) {
10745
+ const remembered = memory.get(key);
10746
+ if (remembered === void 0) return fallback;
10747
+ if (remembered.snapshot !== JSON.stringify(value)) {
10748
+ memory.delete(key);
10749
+ return fallback;
10750
+ }
10751
+ return remembered.lastAccessAt;
10752
+ }
10753
+ /**
10754
+ * Remembers an entry evicted by the byte budget while it is still in state,
10755
+ * so later flushes don't re-persist it as if it were freshly accessed (see
10756
+ * budgetEvictedQueryRecency / budgetEvictedItemRecency).
10757
+ */
10758
+ function rememberBudgetEvictedEntry(memory, key, lastAccessAt, snapshot, isInState) {
10759
+ if (!isInState || snapshot === void 0) return;
10760
+ memory.set(key, {
10761
+ lastAccessAt,
10762
+ snapshot
10763
+ });
10764
+ }
10873
10765
  function materializeHydratedItemState(itemKey, itemState) {
10874
10766
  if (!storeRef) return;
10875
10767
  suppressedPersistedStateFlushes++;
10876
10768
  storeRef.produceState((draft) => {
10877
10769
  draft.items[itemKey] = itemState.item;
10878
10770
  draft.itemQueries[itemKey] = itemState.itemQuery;
10879
- draft.itemLoadedFields[itemKey] = itemState.loadedFields;
10771
+ if (itemState.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = itemState.loadedFields;
10880
10772
  });
10881
10773
  }
10882
10774
  function materializeHydratedQueryState(queryKey, query) {
@@ -11093,8 +10985,7 @@ function setupListQueryPersistence(config, options = {}) {
11093
10985
  if (!storeRef) return false;
11094
10986
  const existingItemQuery = storeRef.state.itemQueries[itemKey];
11095
10987
  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;
10988
+ if (existingItemQuery !== void 0 && existingItem !== void 0) return existingItemQuery !== null;
11098
10989
  if (existingItemQuery === null) return false;
11099
10990
  if (localStorageAdapter !== null) {
11100
10991
  const itemState = readHydratedItem(itemKey);
@@ -11119,8 +11010,7 @@ function setupListQueryPersistence(config, options = {}) {
11119
11010
  for (const itemKey of [...new Set(itemKeys)]) {
11120
11011
  const existingItemQuery = storeRef.state.itemQueries[itemKey];
11121
11012
  const existingItem = storeRef.state.items[itemKey];
11122
- const existingLoadedFields = storeRef.state.itemLoadedFields[itemKey];
11123
- if (existingItemQuery !== void 0 && existingItem !== void 0 && existingLoadedFields !== void 0) {
11013
+ if (existingItemQuery !== void 0 && existingItem !== void 0) {
11124
11014
  resultsByKey.set(itemKey, Promise.resolve(existingItemQuery !== null));
11125
11015
  continue;
11126
11016
  }
@@ -11288,17 +11178,13 @@ function setupListQueryPersistence(config, options = {}) {
11288
11178
  };
11289
11179
  });
11290
11180
  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
- });
11181
+ const { keptKeys: keptQueryKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11182
+ logQueryByteBudgetCleanup("maintenance", filteredEntries.length, keptQueryKeys, unprotectedBytes);
11300
11183
  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);
11184
+ for (const { queryKey, lastAccessAt } of filteredEntries) if (!keptQueryKeys.has(queryKey)) {
11185
+ rememberBudgetEvictedEntry(budgetEvictedQueryRecency, queryKey, lastAccessAt, querySnapshotByKey.get(queryKey), storeRef !== null && Object.hasOwn(storeRef.state.queries, queryKey));
11186
+ forgetPersistedQuery(queryKey);
11187
+ }
11302
11188
  knownPersistedQueryKeys = keptQueryKeys;
11303
11189
  return {
11304
11190
  keptQueryKeys,
@@ -11320,19 +11206,15 @@ function setupListQueryPersistence(config, options = {}) {
11320
11206
  });
11321
11207
  }
11322
11208
  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
- });
11209
+ 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);
11210
+ logQueryByteBudgetCleanup("maintenance", validEntries.length, keptQueryKeys, queryUnprotectedBytes);
11332
11211
  await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
11333
11212
  for (const entry of validEntries) {
11334
11213
  const { queryKey } = entry;
11335
- if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11214
+ if (!keptQueryKeys.has(queryKey)) {
11215
+ rememberBudgetEvictedEntry(budgetEvictedQueryRecency, queryKey, entry.lastAccessAt, querySnapshotByKey.get(queryKey), storeRef !== null && Object.hasOwn(storeRef.state.queries, queryKey));
11216
+ forgetPersistedQuery(queryKey);
11217
+ }
11336
11218
  }
11337
11219
  knownPersistedQueryKeys = keptQueryKeys;
11338
11220
  return {
@@ -11367,21 +11249,17 @@ function setupListQueryPersistence(config, options = {}) {
11367
11249
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11368
11250
  }
11369
11251
  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
- });
11252
+ 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);
11253
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11379
11254
  const evictedItemKeys = /* @__PURE__ */ new Set();
11380
11255
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11381
11256
  evictedItemKeys.add(itemKey);
11382
11257
  return itemNamespace.remove(itemKey);
11383
11258
  }));
11384
- for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11259
+ for (const { itemKey, lastAccessAt } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) {
11260
+ rememberBudgetEvictedEntry(budgetEvictedItemRecency, itemKey, lastAccessAt, itemSnapshotByKey.get(itemKey), storeRef !== null && storeRef.state.items[itemKey] != null);
11261
+ forgetPersistedItem(itemKey);
11262
+ }
11385
11263
  knownPersistedItemKeys = keptItemKeys;
11386
11264
  if (evictedItemKeys.size === 0 || keptQueryKeys.size === 0) return;
11387
11265
  const queryEntries = managedQueryEntriesByKey ? [...managedQueryEntriesByKey.values()].filter(({ queryKey }) => keptQueryKeys.has(queryKey)) : filterAndMap([...keptQueryKeys], (queryKey) => {
@@ -11425,17 +11303,13 @@ function setupListQueryPersistence(config, options = {}) {
11425
11303
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11426
11304
  }
11427
11305
  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
- });
11306
+ 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);
11307
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11437
11308
  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);
11309
+ for (const { itemKey, lastAccessAt } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) {
11310
+ rememberBudgetEvictedEntry(budgetEvictedItemRecency, itemKey, lastAccessAt, itemSnapshotByKey.get(itemKey), storeRef !== null && storeRef.state.items[itemKey] != null);
11311
+ forgetPersistedItem(itemKey);
11312
+ }
11439
11313
  knownPersistedItemKeys = keptItemKeys;
11440
11314
  }
11441
11315
  async function flushPersistedState() {
@@ -11504,13 +11378,20 @@ function setupListQueryPersistence(config, options = {}) {
11504
11378
  }
11505
11379
  const limitedQuery = limitPersistedQueryItems(queryItemsToPersist, query.hasMore, maxQuerySize);
11506
11380
  for (const itemKey of limitedQuery.itemKeys) persistedQueryItemKeys.add(itemKey);
11507
- nextQueryKeys.add(queryKey);
11508
11381
  const nextValue = {
11509
11382
  payload: query.payload,
11510
11383
  items: limitedQuery.itemKeys,
11511
11384
  hasMore: limitedQuery.hasMore
11512
11385
  };
11513
11386
  const nextSnapshot = JSON.stringify(nextValue);
11387
+ if (!previousKnownLocalQueryKeys.has(queryKey)) {
11388
+ const evictedRecency = budgetEvictedQueryRecency.get(queryKey);
11389
+ if (evictedRecency !== void 0) {
11390
+ if (evictedRecency.snapshot === nextSnapshot) continue;
11391
+ budgetEvictedQueryRecency.delete(queryKey);
11392
+ }
11393
+ }
11394
+ nextQueryKeys.add(queryKey);
11514
11395
  if (querySnapshotByKey.get(queryKey) === nextSnapshot && previousKnownLocalQueryKeys.has(queryKey)) continue;
11515
11396
  querySnapshotByKey.set(queryKey, nextSnapshot);
11516
11397
  if (localStorageAdapter === null) querySizeBytesByKey.set(queryKey, estimateAsyncQueryEntrySizeBytes({
@@ -11529,11 +11410,12 @@ function setupListQueryPersistence(config, options = {}) {
11529
11410
  removedQueryKeys.add(queryKey);
11530
11411
  }
11531
11412
  for (const [itemKey, item] of itemEntries) {
11413
+ const hasItemInState = Object.hasOwn(state.items, itemKey);
11532
11414
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
11533
11415
  const hasLoadedFieldsInState = Object.hasOwn(state.itemLoadedFields, itemKey);
11534
11416
  const hydratedItem = hasItemQueryInState && hasLoadedFieldsInState ? void 0 : readHydratedItem(itemKey);
11535
11417
  const itemQuery = hasItemQueryInState ? state.itemQueries[itemKey] : hydratedItem?.itemQuery;
11536
- const loadedFields = hasLoadedFieldsInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11418
+ const loadedFields = hasItemInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11537
11419
  if (item === null || itemQuery == null) {
11538
11420
  if (previousKnownLocalItemKeys.has(itemKey)) {
11539
11421
  tasks.push(itemNamespace.remove(itemKey));
@@ -11570,6 +11452,16 @@ function setupListQueryPersistence(config, options = {}) {
11570
11452
  loadedFields
11571
11453
  };
11572
11454
  const nextSnapshot = JSON.stringify(nextValue);
11455
+ if (!previousKnownLocalItemKeys.has(itemKey)) {
11456
+ const evictedRecency = budgetEvictedItemRecency.get(itemKey);
11457
+ if (evictedRecency !== void 0) {
11458
+ if (evictedRecency.snapshot === nextSnapshot) {
11459
+ nextItemKeys.delete(itemKey);
11460
+ continue;
11461
+ }
11462
+ budgetEvictedItemRecency.delete(itemKey);
11463
+ }
11464
+ }
11573
11465
  if (itemSnapshotByKey.get(itemKey) === nextSnapshot && previousKnownLocalItemKeys.has(itemKey)) continue;
11574
11466
  itemSnapshotByKey.set(itemKey, nextSnapshot);
11575
11467
  if (localStorageAdapter === null) itemSizeBytesByKey.set(itemKey, estimateAsyncItemEntrySizeBytes({
@@ -11593,6 +11485,10 @@ function setupListQueryPersistence(config, options = {}) {
11593
11485
  forgetPersistedItem(itemKey);
11594
11486
  removedItemKeys.add(itemKey);
11595
11487
  }
11488
+ if (removedQueryKeys.size > 0) budgetEvictedQueryRecency.clear();
11489
+ if (removedItemKeys.size > 0) budgetEvictedItemRecency.clear();
11490
+ for (const queryKey of budgetEvictedQueryRecency.keys()) if (!Object.hasOwn(state.queries, queryKey)) budgetEvictedQueryRecency.delete(queryKey);
11491
+ for (const itemKey of budgetEvictedItemRecency.keys()) if (state.items[itemKey] == null) budgetEvictedItemRecency.delete(itemKey);
11596
11492
  await Promise.all(tasks);
11597
11493
  knownPersistedItemKeys = new Set(previousItemKeys);
11598
11494
  for (const itemKey of removedItemKeys) knownPersistedItemKeys.delete(itemKey);
@@ -11603,7 +11499,7 @@ function setupListQueryPersistence(config, options = {}) {
11603
11499
  if (localStorageAdapter !== null) {
11604
11500
  const nextKnownPersistedItemBytes = getKnownPersistedItemBytes(knownPersistedItemKeys);
11605
11501
  const nextKnownPersistedQueryBytes = getKnownPersistedQueryBytes(knownPersistedQueryKeys);
11606
- if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance({ forceManifestKeys: [maintenanceCallbackKey] });
11502
+ if (maintenanceCallbackKey !== null && (hasIgnoreItemFilter || nextKnownPersistedItemBytes === null || nextKnownPersistedQueryBytes === null || nextKnownPersistedItemBytes > maxItemBytes || nextKnownPersistedQueryBytes > maxQueryBytes)) scheduleLocalStorageMaintenance([maintenanceCallbackKey]);
11607
11503
  return;
11608
11504
  }
11609
11505
  const sessionKey = config.getSessionKey();
@@ -11676,17 +11572,21 @@ function setupListQueryPersistence(config, options = {}) {
11676
11572
  sizeBytes: rememberQueryMetadataSize(entry.key, entry.sizeBytes)
11677
11573
  });
11678
11574
  }
11575
+ const inStateQueryLastAccessAt = /* @__PURE__ */ new Map();
11679
11576
  for (const [queryKey, queryData] of finalQueryDataByKey) {
11577
+ const existingMetadata = metadataByKey.get(queryKey);
11578
+ const lastAccessAt = existingMetadata?.lastAccessAt ?? getBudgetEvictedLastAccessAt(budgetEvictedQueryRecency, queryKey, queryData, commitTimestamp);
11579
+ inStateQueryLastAccessAt.set(queryKey, lastAccessAt);
11680
11580
  const sizeBytes = estimateAsyncQueryEntrySizeBytes({
11681
- currentCustomMetadata: metadataByKey.get(queryKey)?.customMetadata,
11682
- lastAccessAt: commitTimestamp,
11581
+ currentCustomMetadata: existingMetadata?.customMetadata,
11582
+ lastAccessAt,
11683
11583
  protectedKeysSnapshotSet: protectedRefs,
11684
11584
  queryKey,
11685
11585
  value: queryData
11686
11586
  });
11687
11587
  finalQuerySizeBytesByKey.set(queryKey, sizeBytes);
11688
11588
  candidateEntries.push({
11689
- lastAccessAt: commitTimestamp,
11589
+ lastAccessAt,
11690
11590
  offlineProtected: protectedQueryKeys.has(queryKey) || protectedRefs?.has(serializeProtectedRef$1({
11691
11591
  key: queryKey,
11692
11592
  kind: "listQuery.query",
@@ -11697,30 +11597,35 @@ function setupListQueryPersistence(config, options = {}) {
11697
11597
  sizeBytes
11698
11598
  });
11699
11599
  }
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
- });
11600
+ 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);
11601
+ logQueryByteBudgetCleanup("flush", candidateEntries.length, keptQueryKeys, queryUnprotectedBytes);
11709
11602
  finalPersistedQueryKeys.clear();
11710
- for (const queryKey of keptQueryKeys) finalPersistedQueryKeys.add(queryKey);
11603
+ for (const queryKey of keptQueryKeys) {
11604
+ finalPersistedQueryKeys.add(queryKey);
11605
+ budgetEvictedQueryRecency.delete(queryKey);
11606
+ }
11607
+ for (const queryKey of budgetEvictedQueryRecency.keys()) if (!finalQueryDataByKey.has(queryKey)) budgetEvictedQueryRecency.delete(queryKey);
11711
11608
  const evictedQueryKeys = [];
11712
11609
  for (const queryKey of finalQueryDataByKey.keys()) if (!finalPersistedQueryKeys.has(queryKey)) evictedQueryKeys.push(queryKey);
11713
- for (const queryKey of evictedQueryKeys) finalQueryDataByKey.delete(queryKey);
11610
+ for (const queryKey of evictedQueryKeys) {
11611
+ const queryData = finalQueryDataByKey.get(queryKey);
11612
+ if (queryData !== void 0) budgetEvictedQueryRecency.set(queryKey, {
11613
+ lastAccessAt: inStateQueryLastAccessAt.get(queryKey) ?? commitTimestamp,
11614
+ snapshot: JSON.stringify(queryData)
11615
+ });
11616
+ finalQueryDataByKey.delete(queryKey);
11617
+ }
11714
11618
  const persistedQueryItemKeys = /* @__PURE__ */ new Set();
11715
11619
  for (const queryData of finalQueryDataByKey.values()) for (const itemKey of queryData.items) persistedQueryItemKeys.add(itemKey);
11716
11620
  const finalItemDataByKey = /* @__PURE__ */ new Map();
11717
11621
  const finalPersistedItemKeys = new Set(previousKnownLocalItemKeys);
11718
11622
  for (const [itemKey, item] of itemEntries) {
11623
+ const hasItemInState = Object.hasOwn(state.items, itemKey);
11719
11624
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
11720
11625
  const hasLoadedFieldsInState = Object.hasOwn(state.itemLoadedFields, itemKey);
11721
11626
  const hydratedItem = hasItemQueryInState && hasLoadedFieldsInState ? void 0 : readHydratedItem(itemKey);
11722
11627
  const itemQuery = hasItemQueryInState ? state.itemQueries[itemKey] : hydratedItem?.itemQuery;
11723
- const loadedFields = hasLoadedFieldsInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11628
+ const loadedFields = hasItemInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
11724
11629
  if (item === null || itemQuery == null) {
11725
11630
  if (previousKnownLocalItemKeys.has(itemKey)) finalPersistedItemKeys.delete(itemKey);
11726
11631
  continue;
@@ -11741,7 +11646,7 @@ function setupListQueryPersistence(config, options = {}) {
11741
11646
  };
11742
11647
  finalItemDataByKey.set(itemKey, {
11743
11648
  metadata: {
11744
- ...Array.isArray(loadedFields) ? { f: loadedFields } : {},
11649
+ ...loadedFields !== void 0 ? { f: loadedFields } : {},
11745
11650
  p: itemQuery.payload,
11746
11651
  ...getItemDerivedGroup ? { g: getItemDerivedGroup(item, itemQuery.payload) } : {}
11747
11652
  },
@@ -11774,12 +11679,15 @@ function setupListQueryPersistence(config, options = {}) {
11774
11679
  sizeBytes: rememberItemMetadataSize(entry.key, entry.sizeBytes)
11775
11680
  });
11776
11681
  }
11682
+ const inStateItemLastAccessAt = /* @__PURE__ */ new Map();
11777
11683
  for (const [itemKey, entry] of finalItemDataByKey) {
11778
11684
  const existingMetadata = itemMetadataByKey.get(itemKey);
11685
+ const lastAccessAt = existingMetadata?.lastAccessAt ?? getBudgetEvictedLastAccessAt(budgetEvictedItemRecency, itemKey, entry.value, itemCommitTimestamp);
11686
+ inStateItemLastAccessAt.set(itemKey, lastAccessAt);
11779
11687
  const sizeBytes = estimateAsyncItemEntrySizeBytes({
11780
11688
  currentCustomMetadata: existingMetadata?.customMetadata,
11781
11689
  itemKey,
11782
- lastAccessAt: existingMetadata?.lastAccessAt ?? itemCommitTimestamp,
11690
+ lastAccessAt,
11783
11691
  nextCustomMetadata: entry.metadata,
11784
11692
  protectedKeysSnapshotSet: protectedRefs,
11785
11693
  value: entry.value
@@ -11787,7 +11695,7 @@ function setupListQueryPersistence(config, options = {}) {
11787
11695
  finalItemSizeBytesByKey.set(itemKey, sizeBytes);
11788
11696
  itemCandidateEntries.push({
11789
11697
  itemKey,
11790
- lastAccessAt: existingMetadata?.lastAccessAt ?? itemCommitTimestamp,
11698
+ lastAccessAt,
11791
11699
  offlineProtected: protectedItemKeys.has(itemKey) || protectedRefs?.has(serializeProtectedRef$1({
11792
11700
  key: itemKey,
11793
11701
  kind: "listQuery.item",
@@ -11797,20 +11705,24 @@ function setupListQueryPersistence(config, options = {}) {
11797
11705
  sizeBytes
11798
11706
  });
11799
11707
  }
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
- });
11708
+ 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);
11709
+ logItemByteBudgetCleanup("flush", itemCandidateEntries.length, keptItemKeys, itemUnprotectedBytes);
11809
11710
  finalPersistedItemKeys.clear();
11810
- for (const itemKey of keptItemKeys) finalPersistedItemKeys.add(itemKey);
11711
+ for (const itemKey of keptItemKeys) {
11712
+ finalPersistedItemKeys.add(itemKey);
11713
+ budgetEvictedItemRecency.delete(itemKey);
11714
+ }
11715
+ for (const itemKey of budgetEvictedItemRecency.keys()) if (!finalItemDataByKey.has(itemKey)) budgetEvictedItemRecency.delete(itemKey);
11811
11716
  const evictedItemKeys = [];
11812
11717
  for (const itemKey of finalItemDataByKey.keys()) if (!finalPersistedItemKeys.has(itemKey)) evictedItemKeys.push(itemKey);
11813
- for (const itemKey of evictedItemKeys) finalItemDataByKey.delete(itemKey);
11718
+ for (const itemKey of evictedItemKeys) {
11719
+ const entry = finalItemDataByKey.get(itemKey);
11720
+ if (entry !== void 0) budgetEvictedItemRecency.set(itemKey, {
11721
+ lastAccessAt: inStateItemLastAccessAt.get(itemKey) ?? itemCommitTimestamp,
11722
+ snapshot: JSON.stringify(entry.value)
11723
+ });
11724
+ finalItemDataByKey.delete(itemKey);
11725
+ }
11814
11726
  const removedQueryKeys = [...previousKnownLocalQueryKeys].filter((queryKey) => !finalPersistedQueryKeys.has(queryKey));
11815
11727
  const removedItemKeys = [...previousKnownLocalItemKeys].filter((itemKey) => !finalPersistedItemKeys.has(itemKey));
11816
11728
  const queryUpserts = /* @__PURE__ */ new Map();
@@ -11943,6 +11855,8 @@ function setupListQueryPersistence(config, options = {}) {
11943
11855
  querySnapshotByKey.clear();
11944
11856
  itemSizeBytesByKey.clear();
11945
11857
  querySizeBytesByKey.clear();
11858
+ budgetEvictedItemRecency.clear();
11859
+ budgetEvictedQueryRecency.clear();
11946
11860
  hydratedPersistedItemKeys.clear();
11947
11861
  hydratedPersistedQueryKeys.clear();
11948
11862
  syncHydrationItemMissCache.clearAll();
@@ -11968,13 +11882,63 @@ function setupListQueryPersistence(config, options = {}) {
11968
11882
  }
11969
11883
  //#endregion
11970
11884
  //#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;
11885
+ function hasFullyLoadedFields(loadedFields) {
11886
+ return loadedFields === "*";
11887
+ }
11888
+ /**
11889
+ * Whether a snapshot should be treated as holding every field of the item.
11890
+ * True when the tracked `loadedFields` is the `'*'` sentinel, or when the
11891
+ * snapshot carries no field metadata but `inferFields` reports the item is
11892
+ * complete (`'*'`) — e.g. manually inserted items, offline optimistic rows, or
11893
+ * persisted fallback snapshots.
11894
+ */
11895
+ function snapshotIsFullyLoaded(loadedFields, item, inferFields) {
11896
+ if (loadedFields === "*") return true;
11897
+ if (!item) return false;
11898
+ return inferFields(item) === "*";
11899
+ }
11900
+ /**
11901
+ * Like {@link snapshotIsFullyLoaded}, but also returns `false` when the item is
11902
+ * awaiting a full ('*') re-fetch after a full invalidation. A fully-loaded
11903
+ * snapshot that was fully invalidated has its `loadedFields` reset while the
11904
+ * (now stale) item data is still present, so `inferFields` would otherwise
11905
+ * wrongly vouch for it as complete.
11906
+ */
11907
+ function snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, item, inferFields, itemsPendingFullInvalidation) {
11908
+ if (loadedFields !== "*" && itemsPendingFullInvalidation.has(itemKey)) return false;
11909
+ return snapshotIsFullyLoaded(loadedFields, item, inferFields);
11910
+ }
11911
+ /**
11912
+ * Missing requested fields for an item snapshot, letting `inferFields` vouch
11913
+ * for metadata-free item data (e.g. client-created items) — except for stale
11914
+ * fields awaiting a re-fetch after an invalidation (per-field or full), when
11915
+ * the item's stale data must not be vouched for.
11916
+ */
11917
+ function getStaleOrMissingRequestedFields(itemKey, loadedFields, item, requestedFields, inferFields, itemsPendingFullInvalidation, pendingInvalidationFields) {
11918
+ const staleRequestedFields = pendingInvalidationFields.length > 0 ? requestedFields.filter((field) => pendingInvalidationFields.includes(field)) : [];
11919
+ const missingLoadedFields = excludeLoadedFields(loadedFields, requestedFields);
11920
+ if (missingLoadedFields.length === 0) return staleRequestedFields;
11921
+ const unvouchedMissingFields = loadedFields !== "*" && itemsPendingFullInvalidation.has(itemKey) || !item ? missingLoadedFields : (() => {
11922
+ const inferredFields = inferFields(item);
11923
+ return missingLoadedFields.filter((field) => inferredFields !== "*" && !inferredFields.includes(field));
11924
+ })();
11925
+ if (staleRequestedFields.length === 0) return unvouchedMissingFields;
11926
+ const resultFields = new Set([...staleRequestedFields, ...unvouchedMissingFields]);
11927
+ return requestedFields.filter((field) => resultFields.has(field));
11928
+ }
11929
+ function fallbackItemHasRequestedFields(fallbackItemState, requestedFields, inferFields) {
11930
+ return getFallbackMissingRequestedFields(fallbackItemState, requestedFields, inferFields).length === 0;
11931
+ }
11932
+ function getFallbackMissingRequestedFields(fallbackItemState, requestedFields, inferFields) {
11933
+ const loadedFields = fallbackItemState?.loadedFields;
11934
+ if (loadedFields === "*") return [];
11935
+ const missingLoadedFields = requestedFields.filter((field) => !(loadedFields?.includes(field) ?? false));
11936
+ if (missingLoadedFields.length === 0) return [];
11974
11937
  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);
11938
+ if (!item) return missingLoadedFields;
11939
+ const inferredFields = inferFields(item);
11940
+ if (inferredFields === "*") return [];
11941
+ return missingLoadedFields.filter((field) => !inferredFields.includes(field));
11978
11942
  }
11979
11943
  /**
11980
11944
  * Returns the fields from `requestedFields` that are not yet present in
@@ -11982,6 +11946,7 @@ function fallbackItemHasRequestedFields(fallbackItemState, requestedFields) {
11982
11946
  */
11983
11947
  function excludeLoadedFields(loadedFields, requestedFields) {
11984
11948
  if (!requestedFields || requestedFields.length === 0) return [];
11949
+ if (loadedFields === "*") return [];
11985
11950
  if (!loadedFields || loadedFields.length === 0) return [...requestedFields];
11986
11951
  return requestedFields.filter((field) => !loadedFields.includes(field));
11987
11952
  }
@@ -11994,15 +11959,13 @@ function excludeLoadedFields(loadedFields, requestedFields) {
11994
11959
  function applyPartialItemMerge(draft, itemKey, data, fields, partialResources) {
11995
11960
  const prev = draft.items[itemKey] ?? void 0;
11996
11961
  const merged = partialResources.mergeItems(prev, data);
11997
- draft.items[itemKey] = reusePrevIfEqual({
11998
- current: merged,
11999
- prev
12000
- });
11962
+ draft.items[itemKey] = reusePrevIfEqual(prev, merged);
12001
11963
  if (fields && fields.length > 0) {
12002
- const existingFields = draft.itemLoadedFields[itemKey] ?? [];
12003
- const fieldSet = new Set([...existingFields, ...fields]);
11964
+ const existingFields = draft.itemLoadedFields[itemKey];
11965
+ if (existingFields === "*") return merged;
11966
+ const fieldSet = new Set([...existingFields ?? [], ...fields]);
12004
11967
  draft.itemLoadedFields[itemKey] = Array.from(fieldSet).sort();
12005
- } else draft.itemLoadedFields[itemKey] = Object.keys(merged).sort();
11968
+ } else draft.itemLoadedFields[itemKey] = "*";
12006
11969
  return merged;
12007
11970
  }
12008
11971
  //#endregion
@@ -12011,10 +11974,7 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12011
11974
  const results = /* @__PURE__ */ new Map();
12012
11975
  function applyItemResult(draft, itemKey, data, fields) {
12013
11976
  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
- });
11977
+ else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12018
11978
  }
12019
11979
  function clearSatisfiedItemInvalidationFields(draft, itemKey, requestFields) {
12020
11980
  const invalidationFields = draft.itemFieldInvalidationFields[itemKey];
@@ -12057,13 +12017,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12057
12017
  payload: r.payload.payload,
12058
12018
  fields: r.payload.fields
12059
12019
  }));
12060
- const fetchResult = await runOfflineAwareFetch({
12061
- controller: offlineController,
12062
- fetcher: () => batchFetchItemFn(batchRequests, {
12063
- signal: fetchCtx.signal,
12064
- batchKey: batchKey ?? "__default__"
12065
- })
12066
- });
12020
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => batchFetchItemFn(batchRequests, {
12021
+ signal: fetchCtx.signal,
12022
+ batchKey: batchKey ?? "__default__"
12023
+ }));
12067
12024
  if (!fetchResult.ok) {
12068
12025
  const error = normalizeFetchResultError(fetchResult, errorNormalizer);
12069
12026
  store.produceState((draft) => {
@@ -12139,13 +12096,10 @@ async function executeItemBatchFetch(requests, fetchCtx, store, itemKeyToPayload
12139
12096
  }
12140
12097
  const fetchPromises = requests.map(async ({ requestId: itemKey, payload: requestData }) => {
12141
12098
  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
- });
12099
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => fetchItemFn(klona(requestData.payload), {
12100
+ signal: fetchCtx.signal,
12101
+ fields: requestData.fields
12102
+ }));
12149
12103
  if (!fetchResult.ok) {
12150
12104
  if (fetchCtx.shouldAbort()) {
12151
12105
  results.set(itemKey, false);
@@ -12221,10 +12175,7 @@ function applyFetchedItems(draft, queryKey, items, hasMore, fields, getItemKey,
12221
12175
  if (remainingFields.length > 0) draft.itemFieldInvalidationFields[itemKey] = remainingFields;
12222
12176
  else delete draft.itemFieldInvalidationFields[itemKey];
12223
12177
  }
12224
- } else draft.items[itemKey] = reusePrevIfEqual({
12225
- current: data,
12226
- prev: draft.items[itemKey] ?? void 0
12227
- });
12178
+ } else draft.items[itemKey] = reusePrevIfEqual(draft.items[itemKey] ?? void 0, data);
12228
12179
  if (!existingItemKeys.has(itemKey)) {
12229
12180
  query.items.push(itemKey);
12230
12181
  existingItemKeys.add(itemKey);
@@ -12286,13 +12237,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12286
12237
  stopOnError: true,
12287
12238
  rejectPendingOnError: true
12288
12239
  });
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) => {
12240
+ const chunkResultPromises = chunks.map((chunk) => queue.resultifyAdd(() => runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, chunk.offset, chunk.limit, {
12241
+ signal: fetchCtx.signal,
12242
+ fields
12243
+ })).then((result) => {
12296
12244
  if (!result.ok) throw result.offline ? offlineConnectivityError : result.error;
12297
12245
  return result.data;
12298
12246
  })));
@@ -12301,13 +12249,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12301
12249
  const lastChunk = successResults[successResults.length - 1];
12302
12250
  hasMore = lastChunk ? lastChunk.hasMore : false;
12303
12251
  } else {
12304
- const fetchResult = await runOfflineAwareFetch({
12305
- controller: offlineController,
12306
- fetcher: () => normalizedFetchListFn(payload, offset, limit, {
12307
- signal: fetchCtx.signal,
12308
- fields
12309
- })
12310
- });
12252
+ const fetchResult = await runOfflineAwareFetch(offlineController, () => normalizedFetchListFn(payload, offset, limit, {
12253
+ signal: fetchCtx.signal,
12254
+ fields
12255
+ }));
12311
12256
  if (!fetchResult.ok) throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
12312
12257
  const result = fetchResult.data;
12313
12258
  allItems = result.items;
@@ -12349,7 +12294,7 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
12349
12294
  //#endregion
12350
12295
  //#region src/listQueryStore/createFetchApi.ts
12351
12296
  /** @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 }) {
12297
+ 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
12298
  const noFetchItemFnError = "No fetchItemFn was provided";
12354
12299
  const querySchedulers = /* @__PURE__ */ new Map();
12355
12300
  const queryInitialFetchStartTime = /* @__PURE__ */ new Map();
@@ -12760,7 +12705,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12760
12705
  const materializedState = readMaterializedItemState(itemKey);
12761
12706
  const hydratedState = persistence.readHydratedItem(itemKey);
12762
12707
  const state = materializedState ?? hydratedState;
12763
- if (!state || state.item == null || state.itemQuery == null || partialResources && fields && fields.length > 0 && !fallbackItemHasRequestedFields(state, fields)) return "skipped";
12708
+ if (!state || state.item == null || state.itemQuery == null || partialResources && fields && fields.length > 0 && !fallbackItemHasRequestedFields(state, fields, partialResources.inferFields)) return "skipped";
12764
12709
  appendedItemKeys.push(itemKey);
12765
12710
  if (!materializedState && hydratedState) appendedHydratedItems.push({
12766
12711
  itemKey,
@@ -12780,7 +12725,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12780
12725
  for (const { itemKey, state } of appendedHydratedItems) {
12781
12726
  draft.items[itemKey] = state.item;
12782
12727
  draft.itemQueries[itemKey] = state.itemQuery;
12783
- draft.itemLoadedFields[itemKey] = state.loadedFields;
12728
+ if (state.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = state.loadedFields;
12784
12729
  }
12785
12730
  }, { action: "persistent-storage-load-more" });
12786
12731
  return "triggered";
@@ -12792,10 +12737,25 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12792
12737
  return item && itemPayload ? itemDataSelector(item, itemPayload, itemKey) : false;
12793
12738
  });
12794
12739
  }
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));
12740
+ /**
12741
+ * Fields of an item still awaiting an invalidation re-fetch. Reads the
12742
+ * state-level record first; when a fetch already consumed it (the record is
12743
+ * deleted before the response lands), falls back to the in-memory pending
12744
+ * list minus the fields that were re-loaded since the invalidation.
12745
+ */
12746
+ function getUnresolvedPendingInvalidationFields(itemKey) {
12747
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
12748
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
12749
+ return excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
12750
+ }
12751
+ /**
12752
+ * Whether an item snapshot is fresh enough for a require-fresh
12753
+ * (`ignoreStaleState: true`) full ('*') read: no unresolved full ('*')
12754
+ * invalidation and no fields still awaiting an invalidation re-fetch.
12755
+ */
12756
+ function itemSnapshotIsFresh(itemKey) {
12757
+ if (store.state.itemLoadedFields[itemKey] !== "*" && itemsPendingFullInvalidation.has(itemKey)) return false;
12758
+ return getUnresolvedPendingInvalidationFields(itemKey).length === 0;
12799
12759
  }
12800
12760
  async function awaitListQueryFetch(params, options = {}) {
12801
12761
  const queryKey = getQueryKey(params);
@@ -12831,7 +12791,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12831
12791
  if (!hydratedItem) continue;
12832
12792
  draft.items[itemKey] = hydratedItem.item;
12833
12793
  draft.itemQueries[itemKey] = hydratedItem.itemQuery;
12834
- draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12794
+ if (hydratedItem.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12835
12795
  }
12836
12796
  }, { action: "persistent-storage-hydrate" });
12837
12797
  }
@@ -12858,11 +12818,12 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12858
12818
  async function getQueryFromStateOrFetch(params, options = {}) {
12859
12819
  const queryKey = getQueryKey(params);
12860
12820
  const fields = normalizeFieldsOption(options.fields);
12821
+ const fullFieldsRequested = options.fields === "*";
12861
12822
  const query = getQueryStateByKey(queryKey);
12862
12823
  const includeStale = !!options.ignoreStaleState;
12863
12824
  const cachedQueryCanBeUsed = !!query?.wasLoaded && (!includeStale || query.status === "success" && !query.error && !query.refetchOnMount);
12864
12825
  if (query && cachedQueryCanBeUsed) {
12865
- if (!(partialResources && Array.isArray(fields) && fields.length > 0)) return Result.ok({
12826
+ if (!(partialResources && (Array.isArray(fields) && fields.length > 0 || fullFieldsRequested))) return Result.ok({
12866
12827
  items: getQueryItems(query, (data, itemPayload) => ({
12867
12828
  data,
12868
12829
  itemPayload
@@ -12871,8 +12832,10 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12871
12832
  });
12872
12833
  if (!query.items.some((itemKey) => {
12873
12834
  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));
12835
+ if (fullFieldsRequested) return !snapshotIsFullyLoaded(itemState?.loadedFields, itemState?.item, partialResources.inferFields) || includeStale && !itemSnapshotIsFresh(itemKey);
12836
+ const requestedFields = Array.isArray(fields) ? fields : [];
12837
+ if (includeStale) return getStaleOrMissingRequestedFields(itemKey, itemState?.loadedFields, itemState?.item, requestedFields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).length > 0;
12838
+ return getFallbackMissingRequestedFields(itemState, requestedFields, partialResources.inferFields).length > 0;
12876
12839
  })) return Result.ok({
12877
12840
  items: getQueryItems(query, (data, itemPayload) => ({
12878
12841
  data,
@@ -12933,7 +12896,7 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12933
12896
  store.produceState((draft) => {
12934
12897
  draft.items[itemKey] = hydratedItem.item;
12935
12898
  draft.itemQueries[itemKey] = hydratedItem.itemQuery;
12936
- draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12899
+ if (hydratedItem.loadedFields !== void 0) draft.itemLoadedFields[itemKey] = hydratedItem.loadedFields;
12937
12900
  }, { action: "persistent-storage-hydrate" });
12938
12901
  }
12939
12902
  }
@@ -12955,20 +12918,19 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12955
12918
  async function getItemFromStateOrFetch(itemPayload, options = {}) {
12956
12919
  const itemKey = getItemKey(itemPayload);
12957
12920
  const fields = normalizeFieldsOption(options.fields);
12921
+ const fullFieldsRequested = options.fields === "*";
12958
12922
  const itemState = readItemState(itemKey);
12959
12923
  const item = itemState?.item;
12960
12924
  const itemQuery = itemState?.itemQuery;
12961
12925
  const includeStale = !!options.ignoreStaleState;
12962
- const needsFieldCheck = partialResources && Array.isArray(fields) && fields.length > 0;
12963
- const itemHasAllFields = !needsFieldCheck || fallbackItemHasRequestedFields(itemState, fields);
12926
+ const needsFieldCheck = partialResources && (Array.isArray(fields) && fields.length > 0 || fullFieldsRequested);
12927
+ const itemHasAllFields = !needsFieldCheck || (fullFieldsRequested ? snapshotIsFullyLoaded(itemState?.loadedFields, itemState?.item, partialResources.inferFields) : fallbackItemHasRequestedFields(itemState, Array.isArray(fields) ? fields : [], partialResources.inferFields));
12964
12928
  const itemQueryFresh = itemQuery?.status === "success" && !itemQuery.error && !itemQuery.refetchOnMount;
12965
- if (item != null && itemHasAllFields && (!includeStale || itemQueryFresh && (!needsFieldCheck || !hasStaleRequestedFields(itemKey, fields)))) return Result.ok(item);
12929
+ const staleOrMissingRequestedFields = needsFieldCheck && !fullFieldsRequested && includeStale ? getStaleOrMissingRequestedFields(itemKey, itemState?.loadedFields, item, Array.isArray(fields) ? fields : [], partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)) : void 0;
12930
+ if (item != null && itemHasAllFields && (!includeStale || itemQueryFresh && (!needsFieldCheck || (fullFieldsRequested ? itemSnapshotIsFresh(itemKey) : staleOrMissingRequestedFields?.length === 0)))) return Result.ok(item);
12966
12931
  if (!fetchItemFn) throw new Error(noFetchItemFnError);
12967
12932
  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
- }
12933
+ if (needsFieldCheck && !fullFieldsRequested && item != null && itemQueryFresh) fieldsToFetch = staleOrMissingRequestedFields ?? getFallbackMissingRequestedFields(itemState, Array.isArray(fields) ? fields : [], partialResources.inferFields);
12972
12934
  const result = await awaitItemFetch(itemPayload, {
12973
12935
  timeoutMs: options.timeoutMs,
12974
12936
  fields: fieldsToFetch
@@ -12987,6 +12949,11 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
12987
12949
  itemInitialFetchStartTime.clear();
12988
12950
  itemKeyToPayload.clear();
12989
12951
  }
12952
+ function reevaluateDelayedRTUs() {
12953
+ for (const scheduler of querySchedulers.values()) scheduler.reevaluateDelayedRTU();
12954
+ for (const scheduler of batchKeySchedulers.values()) scheduler.reevaluateDelayedRTU();
12955
+ for (const scheduler of perItemSchedulers.values()) scheduler.reevaluateDelayedRTU();
12956
+ }
12990
12957
  function syncRemoteFetchStart(targetKey, requestIds, startedAt) {
12991
12958
  if (targetKey.startsWith("query:")) {
12992
12959
  const scheduler = getKnownQueryScheduler(targetKey.slice(6));
@@ -13050,7 +13017,8 @@ function createFetchApi({ store, normalizedFetchListFn, offsetPagination, fetchI
13050
13017
  syncRemoteFetchSuccess,
13051
13018
  deleteQueryFetchResources,
13052
13019
  deleteItemFetchResources,
13053
- resetSchedulers
13020
+ resetSchedulers,
13021
+ reevaluateDelayedRTUs
13054
13022
  };
13055
13023
  }
13056
13024
  //#endregion
@@ -13066,7 +13034,7 @@ const GET_ALL = () => true;
13066
13034
  //#endregion
13067
13035
  //#region src/listQueryStore/createMutationApi.ts
13068
13036
  /** @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 }) {
13037
+ 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
13038
  const storeEvents = evtmitter();
13071
13039
  const deferredOptimisticQueryInvalidationsStack = [];
13072
13040
  const optimisticMutationQueryContextStack = [];
@@ -13126,7 +13094,6 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13126
13094
  const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
13127
13095
  const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
13128
13096
  const itemFieldInvalidationPriorities = /* @__PURE__ */ new Map();
13129
- const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
13130
13097
  function invalidateQueryAndItems(args) {
13131
13098
  const itemPayload = args.all ? GET_ALL : args.itemPayload;
13132
13099
  const queryPayload = args.all ? GET_ALL : args.queryPayload;
@@ -13166,7 +13133,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13166
13133
  for (const { itemKey } of itemsKey) {
13167
13134
  const loadedFields = draft.itemLoadedFields[itemKey];
13168
13135
  if (!loadedFields) continue;
13169
- draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !invalidateFields.includes(f));
13136
+ if (loadedFields !== "*") draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !invalidateFields.includes(f));
13170
13137
  const existingInvalidationFields = draft.itemFieldInvalidationFields[itemKey] ?? [];
13171
13138
  draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...invalidateFields])).sort();
13172
13139
  }
@@ -13187,10 +13154,28 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13187
13154
  for (const { itemKey, payload } of itemsKey) {
13188
13155
  const item = store.state.itemQueries[itemKey];
13189
13156
  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;
13157
+ let effectiveLoadedFields = store.state.itemLoadedFields[itemKey];
13158
+ if (partialResources && effectiveLoadedFields === void 0) {
13159
+ const itemState = store.state.items[itemKey];
13160
+ if (itemState) effectiveLoadedFields = partialResources.inferFields(itemState);
13161
+ }
13162
+ const itemWasFullyLoaded = partialResources && effectiveLoadedFields === "*";
13163
+ const trackedInvalidationFields = partialResources && !itemWasFullyLoaded ? Array.from(new Set([...effectiveLoadedFields === "*" ? [] : effectiveLoadedFields ?? [], ...itemPendingInvalidationFields.get(itemKey) ?? []])).sort() : [];
13164
+ const trackedInvalidationPriority = trackedInvalidationFields.length > 0 || itemsPendingFullInvalidation.has(itemKey) ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
13192
13165
  const nextInvalidationPriority = trackedInvalidationPriority && fetchTypePriority[trackedInvalidationPriority] > fetchTypePriority[priority] ? trackedInvalidationPriority : priority;
13193
13166
  if ((item.refetchOnMount ? fetchTypePriority[item.refetchOnMount] : -1) >= fetchTypePriority[nextInvalidationPriority]) continue;
13167
+ if (itemWasFullyLoaded) {
13168
+ itemsPendingFullInvalidation.add(itemKey);
13169
+ itemPendingInvalidationFields.delete(itemKey);
13170
+ itemFieldInvalidationPriorities.set(itemKey, nextInvalidationPriority);
13171
+ } else if (trackedInvalidationFields.length > 0) {
13172
+ itemPendingInvalidationFields.set(itemKey, trackedInvalidationFields);
13173
+ itemFieldInvalidationPriorities.set(itemKey, nextInvalidationPriority);
13174
+ } else {
13175
+ itemPendingInvalidationFields.delete(itemKey);
13176
+ itemFieldInvalidationPriorities.delete(itemKey);
13177
+ }
13178
+ itemInvalidationWasTriggered.delete(itemKey);
13194
13179
  store.produceState((draft) => {
13195
13180
  const query = draft.itemQueries[itemKey];
13196
13181
  if (!query) return;
@@ -13200,14 +13185,6 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13200
13185
  delete draft.itemFieldInvalidationFields[itemKey];
13201
13186
  }
13202
13187
  }, { 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
13188
  emitInvalidateItem({
13212
13189
  priority: nextInvalidationPriority,
13213
13190
  itemKey
@@ -13425,6 +13402,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13425
13402
  for (const { itemKey } of itemsId) {
13426
13403
  itemFieldInvalidationPriorities.delete(itemKey);
13427
13404
  itemPendingInvalidationFields.delete(itemKey);
13405
+ itemsPendingFullInvalidation.delete(itemKey);
13428
13406
  itemInvalidationWasTriggered.delete(itemKey);
13429
13407
  publishItemSnapshot(itemKey);
13430
13408
  }
@@ -13436,6 +13414,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13436
13414
  itemInvalidationWasTriggered.clear();
13437
13415
  itemFieldInvalidationPriorities.clear();
13438
13416
  itemPendingInvalidationFields.clear();
13417
+ itemsPendingFullInvalidation.clear();
13439
13418
  }
13440
13419
  async function performMutation(payload, { optimisticUpdate, mutation, silentErrors, revalidateOnSuccess, onSuccess, onError, debounce, offline, upload }) {
13441
13420
  const payloadToUse = payload === null ? [] : payload;
@@ -13466,55 +13445,42 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13466
13445
  items: affectedItems
13467
13446
  });
13468
13447
  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
- });
13448
+ const result = await performMutationWithLifecycle(() => {
13449
+ const endBaseMutations = startItemMutation(payloadToUse);
13450
+ return () => {
13451
+ endBaseMutations();
13452
+ for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
13453
+ };
13454
+ }, offline ? () => runHybridOfflineMutation(offlineController, offline, upload, directMutation) : async () => ({
13455
+ kind: "online",
13456
+ data: await directMutation()
13457
+ }), (exception) => {
13458
+ const error = toStoreMutationError(exception, errorNormalizer);
13459
+ const queryRollbackSnapshots = [...optimisticMutationQueryContext.queryRollbackSnapshots.values()];
13460
+ if (itemRollbackSnapshots.length > 0 || queryRollbackSnapshots.length) restoreMutationRollbackState({
13461
+ itemSnapshots: itemRollbackSnapshots,
13462
+ querySnapshots: queryRollbackSnapshots
13463
+ });
13464
+ if (onMutationError) onMutationError(exception, { silentErrors });
13465
+ if (onError) onError(error);
13466
+ return error;
13467
+ }, optimisticUpdate ? () => {
13468
+ deferredOptimisticQueryInvalidationsStack.push(deferredOptimisticQueryInvalidations);
13469
+ optimisticMutationQueryContextStack.push(optimisticMutationQueryContext);
13470
+ try {
13471
+ return runWithBroadcastConsistency("optimistic", () => optimisticUpdate(payloadToUse));
13472
+ } finally {
13473
+ optimisticMutationQueryContextStack.pop();
13474
+ deferredOptimisticQueryInvalidationsStack.pop();
13475
+ }
13476
+ } : void 0, (result) => {
13477
+ const successInvalidationQueryPayloads = result.kind === "online" ? getSuccessInvalidationQueryPayloads(deferredOptimisticQueryInvalidations, normalizedRevalidateOnSuccess.queryFilter, normalizedRevalidateOnSuccess.shouldRevalidate) : [];
13478
+ if (result.kind === "online" && (normalizedRevalidateOnSuccess.shouldRevalidate || successInvalidationQueryPayloads.length > 0)) invalidateQueryAndItems({
13479
+ itemPayload: !normalizedRevalidateOnSuccess.includeItems || affectedItems.length === 0 ? false : payloadToUse,
13480
+ queryPayload: successInvalidationQueryPayloads.length > 0 ? successInvalidationQueryPayloads : false
13481
+ });
13482
+ if (onSuccess && result.kind === "online") onSuccess(result.data, payloadToUse);
13483
+ }, debounce, blockWindowClose ?? void 0);
13518
13484
  storeEvents.emit("mutationEnd", {
13519
13485
  mutationId,
13520
13486
  items: affectedItems,
@@ -13528,7 +13494,6 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13528
13494
  queryInvalidationWasTriggered,
13529
13495
  itemInvalidationWasTriggered,
13530
13496
  itemFieldInvalidationPriorities,
13531
- itemPendingInvalidationFields,
13532
13497
  invalidateQueryAndItems,
13533
13498
  invalidateItem,
13534
13499
  startItemMutation,
@@ -13542,7 +13507,7 @@ function createMutationApi({ store, fetchItemFn, partialResources, optimisticLis
13542
13507
  //#endregion
13543
13508
  //#region src/listQueryStore/listQueryCacheLimits.ts
13544
13509
  /** @internal */
13545
- function createListQueryCacheLimits({ store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup }) {
13510
+ function createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup) {
13546
13511
  let isEnforcingCacheLimits = false;
13547
13512
  function getReferencedItemKeysFromQueries(queryKeys = Object.keys(store.state.queries)) {
13548
13513
  const referencedItemKeys = /* @__PURE__ */ new Set();
@@ -13893,7 +13858,7 @@ const cacheMissError = {
13893
13858
  id: "cache-miss",
13894
13859
  message: "Cache miss"
13895
13860
  };
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) {
13861
+ 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
13862
  const isOffScreenFromContext = useContext(IsOffScreenContext);
13898
13863
  const queriesWithId = useMemo(() => {
13899
13864
  return items.map((itemProps) => {
@@ -13933,6 +13898,8 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13933
13898
  const offlineEntitiesByKey = useMemo(() => createOfflineEntityLookup(offlineEntities), [offlineEntities]);
13934
13899
  const activeOfflineOverlays = useMemo(() => filterActiveOfflineOverlays(offlineEntitiesByKey, offlineOverlays), [offlineEntitiesByKey, offlineOverlays]);
13935
13900
  const getUnresolvedPendingInvalidationFields = useCallback((itemKey) => {
13901
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
13902
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
13936
13903
  return excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
13937
13904
  }, [itemPendingInvalidationFields, store]);
13938
13905
  const resultSelector = useCallback((state) => {
@@ -13996,20 +13963,23 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13996
13963
  let status = itemQuery.status;
13997
13964
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
13998
13965
  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";
13966
+ if (getFallbackMissingRequestedFields({
13967
+ item: rawItemState,
13968
+ loadedFields
13969
+ }, fields, partialResources.inferFields).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
13970
+ } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
13971
+ const isIncomplete = !snapshotIsFullyLoaded(loadedFields, rawItemState, partialResources.inferFields) && !(itemsPendingFullInvalidation.has(itemKey) && hasCachedDataInState);
13972
+ const isStale = !isIncomplete && !snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, rawItemState, partialResources.inferFields, itemsPendingFullInvalidation);
13973
+ if (isIncomplete) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
13974
+ else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
14007
13975
  }
14008
13976
  if (partialResources && showPartialAsRefetching) {
14009
13977
  if (Array.isArray(fields) && fields.length > 0) {
14010
- const pendingRequestedFields = excludeLoadedFields(loadedFields, fields);
13978
+ const pendingRequestedFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, rawItemState, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey));
14011
13979
  if (pendingRequestedFields.length > 0) loadingFields = pendingRequestedFields;
14012
- } else if (fields === "*" && itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) loadingFields = itemFieldInvalidationFields;
13980
+ } else if (fields === "*") {
13981
+ if (hasFullyLoadedFields(loadedFields) && itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) loadingFields = itemFieldInvalidationFields;
13982
+ }
14013
13983
  }
14014
13984
  if (partialResources && status === "refetching" && Array.isArray(fields) && fields.length > 0 && itemFieldInvalidationFields && !fields.some((f) => itemFieldInvalidationFields.includes(f))) status = "success";
14015
13985
  if (!returnRefetchingStatus && status === "refetching") status = "success";
@@ -14028,6 +13998,8 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14028
13998
  });
14029
13999
  }, [
14030
14000
  activeOfflineOverlays,
14001
+ getUnresolvedPendingInvalidationFields,
14002
+ itemsPendingFullInvalidation,
14031
14003
  loadFromStateOnly,
14032
14004
  offlineEntitiesByKey,
14033
14005
  partialResources,
@@ -14038,14 +14010,21 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14038
14010
  return queriesWithId.map(({ itemKey, fields }) => {
14039
14011
  const itemQuery = state.itemQueries[itemKey];
14040
14012
  const loadedFields = state.itemLoadedFields[itemKey] ?? [];
14041
- const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? excludeLoadedFields(loadedFields, fields).sort() : [];
14013
+ const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).sort() : [];
14014
+ const needsFullFetch = partialResources && fields === "*" ? !snapshotIsFullyLoaded(loadedFields, state.items[itemKey], partialResources.inferFields) || itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields) : false;
14042
14015
  return {
14043
14016
  status: itemQuery?.status ?? null,
14044
14017
  refetchOnMount: itemQuery?.refetchOnMount ?? null,
14045
- missingRequestedFieldsKey: JSON.stringify(missingRequestedFields)
14018
+ missingRequestedFieldsKey: JSON.stringify(missingRequestedFields),
14019
+ needsFullFetch
14046
14020
  };
14047
14021
  });
14048
- }, [partialResources, queriesWithId]);
14022
+ }, [
14023
+ getUnresolvedPendingInvalidationFields,
14024
+ itemsPendingFullInvalidation,
14025
+ partialResources,
14026
+ queriesWithId
14027
+ ]);
14049
14028
  const storeState = store.useSelectorRC(resultSelector, { equalityFn: deepEqual });
14050
14029
  const visibleStoreState = useMemo(() => {
14051
14030
  return storeState.map((result, index) => {
@@ -14056,7 +14035,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14056
14035
  const fallbackItemState = readFallbackItemState(query.itemKey);
14057
14036
  const overlay = activeOfflineOverlays[result.itemStateKey];
14058
14037
  const hasOverlay = overlay !== void 0;
14059
- if (!(!partialResources || query.fields === void 0 || query.fields === "*" || fallbackItemHasRequestedFields(fallbackItemState, query.fields))) return result;
14038
+ if (!(!partialResources || query.fields === void 0 || (query.fields === "*" ? snapshotIsFullyLoaded(fallbackItemState?.loadedFields, fallbackItemState?.item, partialResources.inferFields) : fallbackItemHasRequestedFields(fallbackItemState, query.fields, partialResources.inferFields)))) return result;
14060
14039
  const fallbackItemQuery = hasOverlay && overlay.item !== null && fallbackItemState?.itemQuery == null ? {
14061
14040
  status: "success",
14062
14041
  wasLoaded: true,
@@ -14176,37 +14155,39 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14176
14155
  const itemFetchIsActive = itemState?.status === "loading" || itemState?.status === "refetching";
14177
14156
  if (partialResources && !shouldFetch) {
14178
14157
  const loadedFields = store.state.itemLoadedFields[itemKey] ?? [];
14158
+ const item = store.state.items[itemKey];
14179
14159
  const unresolvedPendingInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
14180
- const invalidationPriority = unresolvedPendingInvalidationFields.length > 0 ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
14160
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields);
14161
+ const invalidationPriority = unresolvedPendingInvalidationFields.length > 0 || hasUnresolvedFullInvalidation ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
14181
14162
  if (Array.isArray(fields) && fields.length > 0) {
14182
- const missingFields = excludeLoadedFields(loadedFields, fields);
14163
+ const affectedInvalidationFields = fields.filter((field) => unresolvedPendingInvalidationFields.includes(field));
14164
+ const staleOrMissingFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, item, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields);
14165
+ const missingFields = loadedFields === "*" ? [] : staleOrMissingFields.filter((field) => !loadedFields.includes(field));
14183
14166
  const hasMissingFields = missingFields.length > 0;
14184
- const hasAffectedFieldInvalidation = unresolvedPendingInvalidationFields.length > 0 && fields.some((field) => unresolvedPendingInvalidationFields.includes(field));
14185
- if (hasMissingFields && !itemFetchIsActive) {
14167
+ const hasAffectedFieldInvalidation = affectedInvalidationFields.length > 0;
14168
+ const shouldFetchForInvalidation = hasAffectedFieldInvalidation && !ignoreItemsInRefetchOnMount.has(itemKey);
14169
+ if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive) {
14186
14170
  shouldFetch = true;
14187
14171
  requiredFetch = true;
14188
- fieldsToFetch = missingFields;
14172
+ fieldsToFetch = Array.from(new Set([...missingFields, ...affectedInvalidationFields]));
14189
14173
  if (fetchType === "lowPriority") fetchType = "highPriority";
14190
14174
  }
14191
14175
  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;
14176
+ } else if (fields === "*") {
14177
+ const missingFullItem = !snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation;
14178
+ const shouldFetchForInvalidation = !missingFullItem && unresolvedPendingInvalidationFields.length > 0 && !ignoreItemsInRefetchOnMount.has(itemKey);
14179
+ if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive) {
14180
+ shouldFetch = true;
14181
+ requiredFetch = true;
14182
+ fieldsToFetch = missingFullItem ? "*" : unresolvedPendingInvalidationFields;
14183
+ if (fetchType === "lowPriority") fetchType = "highPriority";
14184
+ if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14185
+ }
14197
14186
  }
14198
14187
  }
14199
14188
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemKey)) continue;
14200
14189
  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 });
14190
+ if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, itemState?.status)) scheduleAutomaticItemFetch(fetchType, payload, { fields: fieldsToFetch });
14210
14191
  }
14211
14192
  for (const itemKey of removedItems) ignoreItemsInRefetchOnMount.delete(itemKey);
14212
14193
  })();
@@ -14222,6 +14203,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14222
14203
  ignoreItemsInRefetchOnMount,
14223
14204
  itemFieldInvalidationPriorities,
14224
14205
  itemPendingInvalidationFields,
14206
+ itemsPendingFullInvalidation,
14225
14207
  loadFromStateOnly,
14226
14208
  partialResources,
14227
14209
  preloadItems,
@@ -14233,7 +14215,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14233
14215
  }
14234
14216
  //#endregion
14235
14217
  //#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) {
14218
+ 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
14219
  const isOffScreenFromContext = useContext(IsOffScreenContext);
14238
14220
  const queriesWithId = useMemo(() => {
14239
14221
  return queries.map((queryProps) => {
@@ -14342,6 +14324,8 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14342
14324
  partialResources
14343
14325
  ]);
14344
14326
  const getUnresolvedPendingInvalidationFields = useCallback((itemKey, state) => {
14327
+ const stateInvalidationFields = (state ? state.itemFieldInvalidationFields : store.state.itemFieldInvalidationFields)[itemKey];
14328
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
14345
14329
  return excludeLoadedFields((state ? state.itemLoadedFields : store.state.itemLoadedFields)[itemKey], itemPendingInvalidationFields.get(itemKey));
14346
14330
  }, [itemPendingInvalidationFields, store]);
14347
14331
  const getHighestPendingInvalidationPriority = useCallback((itemKeys, requestedFields) => {
@@ -14483,34 +14467,49 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14483
14467
  const hasCachedItemsInState = effectiveQuery.query.items.some((itemKey) => {
14484
14468
  return state.items[itemKey] != null;
14485
14469
  });
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";
14470
+ let staleOrMissingRequestedFields;
14471
+ let hasAnyIncompleteItem = false;
14472
+ let hasAnyStaleItem = false;
14473
+ const statusCanBeOverridden = status === "success" || status === "refetching";
14474
+ if (partialResources && (statusCanBeOverridden || showPartialAsRefetching)) {
14475
+ if (Array.isArray(fields) && fields.length > 0) {
14476
+ staleOrMissingRequestedFields = /* @__PURE__ */ new Set();
14477
+ for (const itemKey of effectiveQuery.query.items) {
14478
+ for (const field of getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state))) staleOrMissingRequestedFields.add(field);
14479
+ if (staleOrMissingRequestedFields.size === fields.length || !showPartialAsRefetching && staleOrMissingRequestedFields.size > 0) break;
14480
+ }
14481
+ } else if (fields === "*") {
14482
+ hasAnyIncompleteItem = effectiveQuery.query.items.some((itemKey) => {
14483
+ const item = state.items[itemKey];
14484
+ if (snapshotIsFullyLoaded(state.itemLoadedFields[itemKey], item, partialResources.inferFields)) return false;
14485
+ return !(itemsPendingFullInvalidation.has(itemKey) && item != null);
14486
+ });
14487
+ hasAnyStaleItem = !hasAnyIncompleteItem && effectiveQuery.query.items.some((itemKey) => !snapshotIsFullyLoadedAndFresh(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], partialResources.inferFields, itemsPendingFullInvalidation));
14488
+ }
14489
+ }
14490
+ if (partialResources && Array.isArray(fields) && statusCanBeOverridden && staleOrMissingRequestedFields && staleOrMissingRequestedFields.size > 0) {
14491
+ const someItemMissingFieldDataInState = effectiveQuery.query.items.some((itemKey) => getFallbackMissingRequestedFields({
14492
+ item: state.items[itemKey],
14493
+ loadedFields: state.itemLoadedFields[itemKey]
14494
+ }, fields, partialResources.inferFields).length > 0);
14495
+ if (!hasCachedItemsInState) status = "loading";
14496
+ else if (someItemMissingFieldDataInState) status = showPartialAsRefetching ? "refetching" : "loading";
14499
14497
  else status = "refetching";
14500
- } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
14501
- if (effectiveQuery.query.items.some((itemKey) => {
14498
+ } else if (partialResources && fields === "*" && statusCanBeOverridden) {
14499
+ const hasAnyFieldInvalidation = effectiveQuery.query.items.some((itemKey) => {
14502
14500
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
14503
14501
  return !!itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0;
14504
- })) status = "refetching";
14502
+ });
14503
+ if (hasAnyIncompleteItem) if (!hasCachedItemsInState) status = "loading";
14504
+ else status = showPartialAsRefetching ? "refetching" : "loading";
14505
+ else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
14505
14506
  }
14506
14507
  if (partialResources && showPartialAsRefetching) {
14507
14508
  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
- }));
14509
+ const pendingRequestedFields = status === "loading" && effectiveQuery.query.items.length === 0 ? [...fields] : fields.filter((field) => staleOrMissingRequestedFields?.has(field) ?? false);
14511
14510
  if (pendingRequestedFields.length > 0) loadingFields = pendingRequestedFields;
14512
14511
  } else if (fields === "*") {
14513
- const pendingInvalidationFields = Array.from(new Set(effectiveQuery.query.items.flatMap((itemKey) => state.itemFieldInvalidationFields[itemKey] ?? []))).sort();
14512
+ const pendingInvalidationFields = hasAnyIncompleteItem || hasAnyStaleItem ? [] : Array.from(new Set(effectiveQuery.query.items.flatMap((itemKey) => state.itemFieldInvalidationFields[itemKey] ?? []))).sort();
14514
14513
  if (pendingInvalidationFields.length > 0) loadingFields = pendingInvalidationFields;
14515
14514
  }
14516
14515
  }
@@ -14535,8 +14534,10 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14535
14534
  };
14536
14535
  });
14537
14536
  }, [
14537
+ getUnresolvedPendingInvalidationFields,
14538
14538
  getVisibleQueryItemKeys,
14539
14539
  isOfflineMode,
14540
+ itemsPendingFullInvalidation,
14540
14541
  offlineEntitiesByKey,
14541
14542
  partialResources,
14542
14543
  queriesWithId,
@@ -14554,11 +14555,16 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14554
14555
  if (fallbackQuery && readFallbackItemState) {
14555
14556
  const visibleItemKeys = getVisibleQueryItemKeys(result.queryKey, fallbackQuery.items);
14556
14557
  const requestedFields = Array.isArray(queryConfig.fields) ? queryConfig.fields : void 0;
14558
+ const requiresFullItems = queryConfig.fields === "*";
14557
14559
  const fallbackItemStatesByKey = /* @__PURE__ */ new Map();
14558
14560
  for (const itemKey of visibleItemKeys) {
14559
14561
  const fallbackItemState = readFallbackItemState(itemKey);
14560
14562
  fallbackItemStatesByKey.set(itemKey, fallbackItemState);
14561
- if (requestedFields && partialResources && !fallbackItemHasRequestedFields(fallbackItemState, requestedFields)) return result;
14563
+ if (partialResources) {
14564
+ if (requiresFullItems) {
14565
+ if (!snapshotIsFullyLoaded(fallbackItemState?.loadedFields, fallbackItemState?.item, partialResources.inferFields)) return result;
14566
+ } else if (requestedFields && !fallbackItemHasRequestedFields(fallbackItemState, requestedFields, partialResources.inferFields)) return result;
14567
+ }
14562
14568
  }
14563
14569
  const fallbackItems = selectVisibleItems(visibleItemKeys, queryConfig.fields, (itemKey) => {
14564
14570
  const fallbackItemState = fallbackItemStatesByKey.get(itemKey);
@@ -14615,7 +14621,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14615
14621
  const unresolvedFields = Array.from(new Set(effectiveQuery.query.items.flatMap((itemKey) => getUnresolvedPendingInvalidationFields(itemKey, state)))).sort();
14616
14622
  const requestedFields = Array.isArray(queryConfig.fields) ? queryConfig.fields : void 0;
14617
14623
  const missingRequestedFields = requestedFields && requestedFields.length > 0 ? effectiveQuery.query.items.flatMap((itemKey) => {
14618
- return excludeLoadedFields(state.itemLoadedFields[itemKey], requestedFields);
14624
+ return getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], requestedFields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state));
14619
14625
  }).filter((field, index, array) => array.indexOf(field) === index).sort() : [];
14620
14626
  let unresolvedInvalidationFieldsKey = "";
14621
14627
  if (queryConfig.fields === "*") unresolvedInvalidationFieldsKey = JSON.stringify(unresolvedFields);
@@ -14634,6 +14640,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14634
14640
  }, [
14635
14641
  getHighestPendingInvalidationPriority,
14636
14642
  getUnresolvedPendingInvalidationFields,
14643
+ itemsPendingFullInvalidation,
14637
14644
  partialResources,
14638
14645
  queriesWithId,
14639
14646
  resolveEffectiveQuery
@@ -14722,10 +14729,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14722
14729
  if (partialResources && !shouldFetch && effectiveQueryState) {
14723
14730
  const isQueryFetchInFlight = effectiveQueryState.status === "loading" || effectiveQueryState.status === "refetching" || effectiveQueryState.status === "loadingMore";
14724
14731
  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) {
14732
+ 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
14733
  shouldFetch = true;
14730
14734
  requiredFetch = true;
14731
14735
  fieldsToFetch = fields;
@@ -14742,9 +14746,11 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14742
14746
  if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14743
14747
  }
14744
14748
  } else if (fields === "*") {
14745
- if (effectiveQueryState.items.some((itemKey) => {
14749
+ const hasAnyPartialItem = effectiveQueryState.items.some((itemKey) => !snapshotIsFullyLoadedAndFresh(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], partialResources.inferFields, itemsPendingFullInvalidation));
14750
+ const hasAnyFieldInvalidation = effectiveQueryState.items.some((itemKey) => {
14746
14751
  return getUnresolvedPendingInvalidationFields(itemKey).length > 0;
14747
- }) && !isQueryFetchInFlight) {
14752
+ });
14753
+ if ((hasAnyPartialItem || hasAnyFieldInvalidation) && !isQueryFetchInFlight) {
14748
14754
  shouldFetch = true;
14749
14755
  requiredFetch = true;
14750
14756
  const invalidationPriority = getHighestPendingInvalidationPriority(effectiveQueryState.items, void 0);
@@ -14754,15 +14760,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14754
14760
  }
14755
14761
  if (!shouldFetch && ignoreQueriesInRefetchOnMount.has(queryId)) continue;
14756
14762
  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)) {
14763
+ if (shouldScheduleAutomaticFetch(effectiveQueryState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
14766
14764
  stickyDerivedQueryKeys.delete(queryId);
14767
14765
  scheduleAutomaticListQueryFetch(fetchType, payload, loadSize, { fields: fieldsToFetch });
14768
14766
  }
@@ -14788,6 +14786,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14788
14786
  automaticRetryState,
14789
14787
  itemFieldInvalidationPriorities,
14790
14788
  itemPendingInvalidationFields,
14789
+ itemsPendingFullInvalidation,
14791
14790
  getHighestPendingInvalidationPriority,
14792
14791
  getUnresolvedPendingInvalidationFields,
14793
14792
  stickyDerivedQueryKeys
@@ -14950,18 +14949,9 @@ function createListQueryStore(storeOptions) {
14950
14949
  if (fields === "*") return void 0;
14951
14950
  return fields;
14952
14951
  }
14953
- const resolvedOfflineSession = resolveStoreManagerOfflineSession({
14954
- storeManager,
14955
- storeName: id,
14956
- usesOfflineStorage: persistentStorageConfig?.offline !== void 0
14957
- });
14952
+ const resolvedOfflineSession = resolveStoreManagerOfflineSession(storeManager, id, persistentStorageConfig?.offline !== void 0);
14958
14953
  const getSessionKeyBase = storeManager.getSessionKey;
14959
- const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency({
14960
- storeManager,
14961
- storeName: id,
14962
- offlineSession: resolvedOfflineSession,
14963
- getSessionKey: getSessionKeyBase
14964
- });
14954
+ const getSessionKeyForRuntime = resolvedOfflineSession === null ? getSessionKeyBase : () => validateStoreManagerSessionConsistency(id, resolvedOfflineSession, getSessionKeyBase);
14965
14955
  const errorNormalizer = storeManager.errorNormalizer;
14966
14956
  const resolvedOfflineSessionForPersistentStorage = persistentStorageConfig?.offline === void 0 ? void 0 : (() => {
14967
14957
  if (resolvedOfflineSession === null) throw new Error(`[tsdf] Store "${id}" requires an offline session but none was configured on the store manager`);
@@ -14975,7 +14965,8 @@ function createListQueryStore(storeOptions) {
14975
14965
  ...persistentStorageConfig.offline,
14976
14966
  session: resolvedOfflineSessionForPersistentStorage
14977
14967
  } : void 0,
14978
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
14968
+ debugLogger: storeManager.debugLogger,
14969
+ logger: storeManager.logger,
14979
14970
  getSessionKey: getSessionKeyForRuntime,
14980
14971
  storeName: id
14981
14972
  }) : null;
@@ -15081,11 +15072,20 @@ function createListQueryStore(storeOptions) {
15081
15072
  lastFetchDuration,
15082
15073
  windowIsNotFocused: !getWindowIsFocused()
15083
15074
  });
15075
+ const { priority: browserTabsPriority, tabId: browserTabsTabId } = getOrCreateStoreManagerBrowserTabsPresence(storeManager, {
15076
+ getWindowIsFocused,
15077
+ onWindowFocusChange: testOptions?.onWindowFocusChange,
15078
+ transportFactory: testOptions?.browserTabsTransportFactory,
15079
+ priorityTimings: testOptions?.browserTabsPriorityTimings ?? testOptions?.browserTabsLeadershipTimings
15080
+ });
15084
15081
  function getCoalescingWindowMs() {
15085
- return browserTabsPriority?.getCoalescingWindowMs(baseCoalescingWindowMs) ?? baseCoalescingWindowMs;
15082
+ return browserTabsPriority.getCoalescingWindowMs(baseCoalescingWindowMs);
15086
15083
  }
15087
- let browserTabsSync = null;
15088
- let browserTabsPriority = null;
15084
+ const browserTabsSync = createBrowserTabsCoordinator("listQuery", id, getSessionKeyForRuntime, handleRemoteBrowserTabsMessage, () => {
15085
+ lastQuerySyncVersions.clear();
15086
+ lastItemSyncVersions.clear();
15087
+ clearOfflineOverlays();
15088
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
15089
15089
  function getQueryTargetKey(queryKey) {
15090
15090
  return `query:${queryKey}`;
15091
15091
  }
@@ -15111,7 +15111,7 @@ function createListQueryStore(storeOptions) {
15111
15111
  itemKey,
15112
15112
  item: store.state.items[itemKey] ?? null,
15113
15113
  itemQuery: store.state.itemQueries[itemKey] ?? null,
15114
- loadedFields: store.state.itemLoadedFields[itemKey] ?? []
15114
+ loadedFields: store.state.itemLoadedFields[itemKey]
15115
15115
  }));
15116
15116
  }
15117
15117
  function publishQuerySnapshot(queryKey, consistency = currentBroadcastConsistency) {
@@ -15119,7 +15119,7 @@ function createListQueryStore(storeOptions) {
15119
15119
  const query = store.state.queries[queryKey];
15120
15120
  if (!query) return;
15121
15121
  const items = getQuerySnapshotItems(query);
15122
- const message = browserTabsSync?.publish({
15122
+ const message = browserTabsSync.publish({
15123
15123
  kind: "list-query-snapshot",
15124
15124
  queryKey,
15125
15125
  consistency,
@@ -15132,13 +15132,13 @@ function createListQueryStore(storeOptions) {
15132
15132
  }
15133
15133
  function publishItemSnapshot(itemKey, consistency = currentBroadcastConsistency) {
15134
15134
  if (remoteApplyDepth > 0) return;
15135
- const message = browserTabsSync?.publish({
15135
+ const message = browserTabsSync.publish({
15136
15136
  kind: "list-item-snapshot",
15137
15137
  itemKey,
15138
15138
  consistency,
15139
15139
  item: store.state.items[itemKey] ?? null,
15140
15140
  itemQuery: store.state.itemQueries[itemKey] ?? null,
15141
- loadedFields: store.state.itemLoadedFields[itemKey] ?? []
15141
+ loadedFields: store.state.itemLoadedFields[itemKey]
15142
15142
  });
15143
15143
  if (!message) return;
15144
15144
  recordItemSyncVersion(itemKey, message, consistency);
@@ -15194,217 +15194,151 @@ function createListQueryStore(storeOptions) {
15194
15194
  preloaded: results[index] ?? false
15195
15195
  }));
15196
15196
  }
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
15197
+ const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
15198
+ const itemsPendingFullInvalidation = /* @__PURE__ */ new Set();
15199
+ 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) => {
15200
+ const queryKey = requests[0]?.requestId;
15201
+ if (!queryKey) return;
15202
+ browserTabsSync.publish({
15203
+ kind: "fetch-start",
15204
+ targetKey: getQueryTargetKey(queryKey),
15205
+ requestIds: requests.map(({ requestId }) => requestId),
15206
+ startedAt
15207
+ });
15208
+ }, ({ requests, results, startedAt, duration }) => {
15209
+ pruneItemInvalidationTracking();
15210
+ const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
15211
+ if (successfulQueryKeys.length > 0) {
15212
+ touchQueries(successfulQueryKeys);
15213
+ touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
15214
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15215
+ }
15216
+ const firstQueryKey = successfulQueryKeys[0];
15217
+ if (firstQueryKey) {
15218
+ browserTabsSync.publish({
15219
+ kind: "fetch-success",
15220
+ targetKey: getQueryTargetKey(firstQueryKey),
15221
+ requestIds: successfulQueryKeys,
15222
+ startedAt,
15223
+ duration
15231
15224
  });
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",
15225
+ for (const queryKey of successfulQueryKeys) publishQuerySnapshot(queryKey, "confirmed");
15226
+ }
15227
+ }, (requests, startedAt) => {
15228
+ const firstRequest = requests[0];
15229
+ if (!firstRequest) return;
15230
+ const payload = firstRequest.payload.payload;
15231
+ const batchKey = getItemBatchKey(payload);
15232
+ const targetKey = batchKey === false ? getItemTargetKey(firstRequest.requestId) : getItemBatchTargetKey(batchKey);
15233
+ browserTabsSync.publish({
15234
+ kind: "fetch-start",
15235
+ targetKey,
15236
+ requestIds: requests.map(({ requestId }) => requestId),
15237
+ startedAt
15238
+ });
15239
+ }, ({ requests, results, startedAt, duration }) => {
15240
+ pruneItemInvalidationTracking();
15241
+ const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
15242
+ if (successfulItems.length > 0) {
15243
+ touchItems(successfulItems.map(({ itemKey }) => itemKey));
15244
+ if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15245
+ }
15246
+ const firstSuccessfulItem = successfulItems[0];
15247
+ if (firstSuccessfulItem) {
15248
+ const payload = requests[0]?.payload.payload;
15249
+ const batchKey = payload ? getItemBatchKey(payload) : false;
15250
+ const targetKey = batchKey === false ? getItemTargetKey(firstSuccessfulItem.itemKey) : getItemBatchTargetKey(batchKey);
15251
+ browserTabsSync.publish({
15252
+ kind: "fetch-success",
15241
15253
  targetKey,
15242
- requestIds: requests.map(({ requestId }) => requestId),
15243
- startedAt
15254
+ requestIds: successfulItems.map(({ itemKey }) => itemKey),
15255
+ startedAt,
15256
+ duration
15244
15257
  });
15258
+ for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
15259
+ }
15260
+ }, offlineFetchController, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15261
+ 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) => {
15262
+ events.emit("invalidateQuery", event);
15263
+ }, (event) => {
15264
+ events.emit("invalidateItem", event);
15265
+ }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15266
+ if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
15267
+ normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
15268
+ const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
15269
+ if (normalizedRef !== null) return normalizedRef;
15270
+ return {
15271
+ entityKey: getItemKey(__LEGIT_CAST__(ref)),
15272
+ entityKind: "item"
15273
+ };
15274
+ }),
15275
+ getProtectedCacheKeys: (entityRefs) => {
15276
+ const sessionKey = getSessionKeyForRuntime();
15277
+ if (sessionKey === false) return [];
15278
+ return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "listQuery.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
15245
15279
  },
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
- }
15280
+ applyPendingEntity: ({ tempId, pendingEntity }) => {
15281
+ if (!pendingEntity || typeof pendingEntity !== "object") return;
15282
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
15265
15283
  },
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);
15284
+ rollbackPendingEntity: ({ tempId }) => {
15285
+ deleteItemState(__LEGIT_CAST__(tempId));
15307
15286
  },
15308
- emitInvalidateItem: (event) => {
15309
- events.emit("invalidateItem", event);
15287
+ reconcileTempEntity: ({ tempId, reconciliation }) => {
15288
+ const tempPayload = __LEGIT_CAST__(tempId);
15289
+ const tempItemKey = getItemKey(tempPayload);
15290
+ const currentItem = getItemState(tempPayload);
15291
+ const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
15292
+ if (finalData === void 0) return;
15293
+ const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
15294
+ const finalItemKey = getItemKey(finalPayload);
15295
+ const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
15296
+ queryKey,
15297
+ index: query.items.indexOf(tempItemKey)
15298
+ })).filter(({ index }) => index !== -1);
15299
+ deleteItemState(tempPayload);
15300
+ addItemToState(finalPayload, finalData);
15301
+ storeEvents.emit("tempEntityReconciled", {
15302
+ tempId: tempPayload,
15303
+ finalPayload
15304
+ });
15305
+ if (queryMemberships.length === 0) return;
15306
+ store.produceState((draft) => {
15307
+ for (const { queryKey, index } of queryMemberships) {
15308
+ const query = notNullish(draft.queries[queryKey]);
15309
+ const existingIndex = query.items.indexOf(finalItemKey);
15310
+ if (existingIndex !== -1) query.items.splice(existingIndex, 1);
15311
+ query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
15312
+ }
15313
+ }, { action: "offline-reconcile-temp-item" });
15314
+ touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
15315
+ for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
15310
15316
  },
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
- }
15317
+ captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
15318
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15319
+ captureOfflineOverlays(entityRefs.flatMap((ref) => {
15320
+ return ref.entityKind === "item" ? [ref.entityKey] : [];
15321
+ }));
15322
+ },
15323
+ rebindQueuedMutationOverlays: ({ itemKeyRewrites, sessionKey }) => {
15324
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15325
+ rebindOfflineOverlays(itemKeyRewrites);
15326
+ },
15327
+ syncEntityOverlays: ({ entities, sessionKey }) => {
15328
+ if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
15329
+ const activeItemKeys = new Set(entities.filter((entity) => entity.entityKind === "item").map((entity) => entity.entityKey));
15330
+ offlineOverlayStore.produceState((draft) => {
15331
+ for (const itemKey of Object.keys(draft)) if (!activeItemKeys.has(itemKey)) delete draft[itemKey];
15332
+ });
15401
15333
  }
15402
- });
15334
+ }, resolvedOfflineConfig.session, __LEGIT_CAST__(offlineOperationsForRuntime));
15403
15335
  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];
15336
+ if (loadedFields === void 0) return;
15337
+ if (loadedFields === "*") draft.itemLoadedFields[itemKey] = "*";
15338
+ else if (loadedFields.length > 0) {
15339
+ const existingLoadedFields = draft.itemLoadedFields[itemKey];
15340
+ if (existingLoadedFields !== "*") draft.itemLoadedFields[itemKey] = Array.from(new Set([...existingLoadedFields ?? [], ...loadedFields])).sort();
15341
+ } else if (draft.itemLoadedFields[itemKey] === void 0) draft.itemLoadedFields[itemKey] = [];
15408
15342
  const invalidationFields = draft.itemFieldInvalidationFields[itemKey];
15409
15343
  if (!invalidationFields) return;
15410
15344
  const remainingFields = excludeLoadedFields(loadedFields, invalidationFields);
@@ -15414,18 +15348,27 @@ function createListQueryStore(storeOptions) {
15414
15348
  function pruneItemInvalidationTracking() {
15415
15349
  for (const [itemKey, pendingFields] of itemPendingInvalidationFields) {
15416
15350
  const remainingFields = excludeLoadedFields(store.state.itemLoadedFields[itemKey], pendingFields);
15351
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
15352
+ if (stateInvalidationFields && stateInvalidationFields.length > 0) {
15353
+ const mergedFields = Array.from(new Set([...stateInvalidationFields, ...remainingFields])).sort();
15354
+ itemPendingInvalidationFields.set(itemKey, mergedFields);
15355
+ continue;
15356
+ }
15417
15357
  if (remainingFields.length > 0) itemPendingInvalidationFields.set(itemKey, remainingFields);
15418
15358
  else itemPendingInvalidationFields.delete(itemKey);
15419
15359
  }
15360
+ for (const itemKey of itemsPendingFullInvalidation) if (store.state.itemLoadedFields[itemKey] === "*") itemsPendingFullInvalidation.delete(itemKey);
15420
15361
  for (const itemKey of itemFieldInvalidationPriorities.keys()) {
15421
15362
  const hasPendingStateInvalidation = !!store.state.itemFieldInvalidationFields[itemKey];
15422
15363
  const hasPendingTrackedInvalidation = (itemPendingInvalidationFields.get(itemKey)?.length ?? 0) > 0;
15423
- if (!hasPendingStateInvalidation && !hasPendingTrackedInvalidation) itemFieldInvalidationPriorities.delete(itemKey);
15364
+ const hasPendingFullInvalidation = itemsPendingFullInvalidation.has(itemKey);
15365
+ if (!hasPendingStateInvalidation && !hasPendingTrackedInvalidation && !hasPendingFullInvalidation) itemFieldInvalidationPriorities.delete(itemKey);
15424
15366
  }
15425
15367
  }
15426
15368
  function cleanupItemStateMetadata(itemKey) {
15427
15369
  itemFieldInvalidationPriorities.delete(itemKey);
15428
15370
  itemPendingInvalidationFields.delete(itemKey);
15371
+ itemsPendingFullInvalidation.delete(itemKey);
15429
15372
  itemInvalidationWasTriggered.delete(itemKey);
15430
15373
  itemCacheRuntime.clear(itemKey);
15431
15374
  }
@@ -15438,16 +15381,12 @@ function createListQueryStore(storeOptions) {
15438
15381
  offlineOverlayStore.setState({});
15439
15382
  }
15440
15383
  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
- });
15384
+ rebindOfflineOverlayEntries(offlineOverlayStore, itemKeyRewrites, ({ existingOverlay, nextItemKey }) => ({
15385
+ item: existingOverlay.item ?? null,
15386
+ itemPayload: store.state.itemQueries[nextItemKey]?.payload ?? existingOverlay.itemPayload,
15387
+ queryMemberships: existingOverlay.queryMemberships,
15388
+ keepVisibleWhileResolutionRequired: true
15389
+ }));
15451
15390
  }
15452
15391
  function captureOfflineOverlays(itemKeys) {
15453
15392
  const targetItemKeySet = new Set(itemKeys);
@@ -15460,18 +15399,14 @@ function createListQueryStore(storeOptions) {
15460
15399
  if (!queryMemberships) continue;
15461
15400
  queryMemberships[queryKey] = index;
15462
15401
  }
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
- }
15402
+ captureOfflineOverlayEntries(offlineOverlayStore, [...targetItemKeySet], (itemKey) => {
15403
+ const item = store.state.items[itemKey];
15404
+ const itemPayload = store.state.itemQueries[itemKey]?.payload;
15405
+ return {
15406
+ item: item == null ? null : klona(item),
15407
+ itemPayload: itemPayload === void 0 ? void 0 : klona(itemPayload),
15408
+ queryMemberships: queryMembershipsByItemKey.get(itemKey) ?? {}
15409
+ };
15475
15410
  });
15476
15411
  }
15477
15412
  function isQueryProtectedFromEviction(queryKey, query) {
@@ -15491,18 +15426,20 @@ function createListQueryStore(storeOptions) {
15491
15426
  return partialResources.mergeItems(currentItem ?? void 0, incomingItem);
15492
15427
  }
15493
15428
  function itemSnapshotSatisfiesRequestedFields(item, loadedFields, requestedFields) {
15494
- if (!partialResources || !requestedFields || requestedFields.length === 0) return true;
15429
+ if (!partialResources) return true;
15495
15430
  if (item === null) return true;
15431
+ if (loadedFields !== void 0 && loadedFields !== "*" && loadedFields.length === 0) return false;
15432
+ if (!requestedFields || requestedFields.length === 0) return snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields);
15496
15433
  return fallbackItemHasRequestedFields({
15497
15434
  item,
15498
15435
  loadedFields
15499
- }, requestedFields);
15436
+ }, requestedFields, partialResources.inferFields);
15500
15437
  }
15501
15438
  function querySnapshotSatisfiesPendingQueryFetch(message, snapshotItemsByKey, request) {
15502
15439
  const requestedEnd = request.payload.offset + request.payload.limit;
15503
15440
  if (message.query.items.length < requestedEnd && message.query.hasMore) return false;
15504
15441
  const requestedFields = request.payload.fields;
15505
- if (!partialResources || !requestedFields || requestedFields.length === 0) return true;
15442
+ if (!partialResources) return true;
15506
15443
  return message.query.items.slice(request.payload.offset, requestedEnd).every((itemKey) => {
15507
15444
  const item = snapshotItemsByKey.get(itemKey);
15508
15445
  return !!item && itemSnapshotSatisfiesRequestedFields(item.item, item.loadedFields, requestedFields);
@@ -15522,6 +15459,7 @@ function createListQueryStore(storeOptions) {
15522
15459
  };
15523
15460
  applyLoadedFieldsFromSnapshot(draft, message.itemKey, message.loadedFields);
15524
15461
  if (!message.itemQuery && message.item === null) {
15462
+ delete draft.itemLoadedFields[message.itemKey];
15525
15463
  delete draft.itemFieldInvalidationFields[message.itemKey];
15526
15464
  for (const query of Object.values(draft.queries)) query.items = query.items.filter((itemId) => itemId !== message.itemKey);
15527
15465
  }
@@ -15580,17 +15518,12 @@ function createListQueryStore(storeOptions) {
15580
15518
  }
15581
15519
  function querySnapshotHasLocallyMutatingItem(message) {
15582
15520
  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;
15521
+ if (!store.state.itemQueries[item.itemKey]) continue;
15522
+ if (getKnownItemScheduler(item.itemKey)?.isMutationInProgress(item.itemKey)) return true;
15586
15523
  }
15587
15524
  return false;
15588
15525
  }
15589
15526
  function handleRemoteBrowserTabsMessage(message) {
15590
- if (message.kind === "tab-status") {
15591
- browserTabsPriority?.onTabStatusMessage(message.tabId, message);
15592
- return;
15593
- }
15594
15527
  if (message.kind === "fetch-start") {
15595
15528
  syncRemoteFetchStart(message.targetKey, message.requestIds, message.startedAt);
15596
15529
  return;
@@ -15603,9 +15536,7 @@ function createListQueryStore(storeOptions) {
15603
15536
  const candidateVersion = toBrowserTabsSyncVersion(message, message.consistency);
15604
15537
  if (!isBrowserTabsSyncVersionNewer(candidateVersion, lastItemSyncVersions.get(message.itemKey))) return;
15605
15538
  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);
15539
+ const itemScheduler = localItemQuery === null ? null : getKnownItemScheduler(message.itemKey);
15609
15540
  if (localItemQuery === void 0 && !itemScheduler?.hasPendingFetch) {
15610
15541
  lastItemSyncVersions.set(message.itemKey, candidateVersion);
15611
15542
  return;
@@ -15634,22 +15565,6 @@ function createListQueryStore(storeOptions) {
15634
15565
  }
15635
15566
  applyRemoteQuerySnapshot(message);
15636
15567
  }
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
15568
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
15654
15569
  const offlineEntities = useOfflineStoreEntities({
15655
15570
  sessionKey: getSessionKeyForRuntime(),
@@ -15664,7 +15579,7 @@ function createListQueryStore(storeOptions) {
15664
15579
  return state;
15665
15580
  }, []);
15666
15581
  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);
15582
+ 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
15583
  };
15669
15584
  const useListQuery$2 = function useListQuery$1(payload, options = {}) {
15670
15585
  return useListQuery(payload, options, store, getQueryKey, scheduleListQueryFetch, useMultipleListQueries$2);
@@ -15679,7 +15594,7 @@ function createListQueryStore(storeOptions) {
15679
15594
  return state;
15680
15595
  }, []);
15681
15596
  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);
15597
+ 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
15598
  };
15684
15599
  const useItem$3 = function useItem$2(itemPayload, options = {}) {
15685
15600
  return useItem(itemPayload, options, store, scheduleItemFetch, useMultipleItems$3);
@@ -15705,43 +15620,23 @@ function createListQueryStore(storeOptions) {
15705
15620
  function useFindItem$1(findItemFn, options = {}) {
15706
15621
  return useFindItem(findItemFn, options, store, registerActiveStandaloneItems, touchItems);
15707
15622
  }
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
- });
15623
+ const focusLifecycle = createStoreFocusLifecycle(resolvedRevalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, testOptions?.onWindowFocus ?? onWindowFocus, () => {
15624
+ invalidateQueryAndItems({
15625
+ all: true,
15626
+ type: "lowPriority"
15627
+ });
15628
+ }, () => {
15629
+ invalidateQueryAndItems({
15630
+ all: true,
15631
+ type: "realtimeUpdate"
15632
+ });
15633
+ }, reevaluateDelayedRTUs, import.meta.env.DEV ? {
15634
+ debugLogger: storeManager.debugLogger,
15635
+ storeId: id,
15636
+ storeType: "listQuery"
15637
+ } : void 0);
15638
+ const { enforceCacheLimits } = createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup);
15639
+ const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
15745
15640
  function scheduleCacheLimitEnforcement() {
15746
15641
  cacheLimitEnforcementScheduler.schedule();
15747
15642
  }
@@ -15781,7 +15676,6 @@ function createListQueryStore(storeOptions) {
15781
15676
  queryCacheRuntime.clearAll();
15782
15677
  itemCacheRuntime.clearAll();
15783
15678
  cacheLimitEnforcementScheduler.cancel();
15784
- browserTabsPriority?.reset();
15785
15679
  persistence?.dispose();
15786
15680
  persistence?.clear();
15787
15681
  store.setState(persistence?.createInitialState({
@@ -15813,8 +15707,7 @@ function createListQueryStore(storeOptions) {
15813
15707
  queryCacheRuntime.clearAll();
15814
15708
  itemCacheRuntime.clearAll();
15815
15709
  cacheLimitEnforcementScheduler.cancel();
15816
- browserTabsSync?.close();
15817
- browserTabsPriority?.close();
15710
+ browserTabsSync.close();
15818
15711
  focusLifecycle.dispose();
15819
15712
  persistence?.dispose();
15820
15713
  offlineController?.dispose();