tsdf 17.0.0-rc.1 → 17.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as isModeEffectivelyActive, B as parseCompactLocalStorageEntry, C as isQuotaExceededError, D as compactOfflineStatusSnapshotSchema, E as OfflineResolutionConflictParseError, F as getSessionProtectedKeysSnapshot, I as setSessionProtectedKeysSnapshot, J as parsePersistedAsyncNamespaceKind, L as getNavigatorLockManager, M as offlineItemEntityRefSchema, N as offlineResolutionRecordSchema, O as defaultOfflineRuntimeConfig, P as clearSessionProtectedKeysSnapshot, R as warnIfNavigatorLockUnavailable, S as getSerializedStringSize, T as serializeJsonForStorage, W as getPayloadRecordKey, X as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, Y as serializeProtectedRef, Z as scheduleIdleCleanup, _ as getTSDFDebugTimingMs, a as estimateManagedAsyncStorageEntrySizeBytes, b as createShouldIgnoreItemPredicate, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as emitTSDFDebugLog, h as logPersistentStorageQuotaCleanup, j as isOfflineModeStatusValue, k as getIsOfflineModeFromStatus, l as registerAsyncStartupStoreCleanup, m as getOfflineSessionStatusStorageKey, o as getProtectedKeysFromMetadata, p as OFFLINE_SESSION_STATUS_STORE_NAME, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as resolveTSDFLogger, w as keepEntriesWithinByteBudget, x as createTimedKeySet, y as getDefaultMaxBytesForScope, z as createCompactLocalStorageEntry } from "./asyncStorageAdapter-BBKVK1S_.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-B_lVflof.js";
1
+ import { $ as scheduleIdleCleanup, A as getIsOfflineModeFromStatus, B as createCompactLocalStorageEntry, C as isQuotaExceededError, D as OfflineResolutionConflictParseError, E as serializeJsonForStorage, F as clearSessionProtectedKeysSnapshot, G as getPayloadRecordKey, I as getSessionProtectedKeysSnapshot, L as setSessionProtectedKeysSnapshot, M as isOfflineModeStatusValue, N as offlineItemEntityRefSchema, O as compactOfflineStatusSnapshotSchema, P as offlineResolutionRecordSchema, Q as createIdleCleanupContext, R as getNavigatorLockManager, S as getSerializedStringSize, T as keepEntriesWithinByteBudgetDuringIdle, V as parseCompactLocalStorageEntry, X as serializeProtectedRef, Y as parsePersistedAsyncNamespaceKind, Z as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, _ as getTSDFDebugTimingMs, a as estimateManagedAsyncStorageEntrySizeBytes, b as createShouldIgnoreItemPredicate, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as emitTSDFDebugLog, h as logPersistentStorageQuotaCleanup, j as isModeEffectivelyActive, k as defaultOfflineRuntimeConfig, l as registerAsyncStartupStoreCleanup, m as getOfflineSessionStatusStorageKey, o as getProtectedKeysFromMetadata, p as OFFLINE_SESSION_STATUS_STORE_NAME, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as resolveTSDFLogger, w as keepEntriesWithinByteBudget, x as createTimedKeySet, y as getDefaultMaxBytesForScope, z as warnIfNavigatorLockUnavailable } from "./asyncStorageAdapter-BuGjbXYA.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-D_k77Srq.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";
@@ -260,20 +260,30 @@ const SINGLE_MANIFEST_KEY_PREFIX = `${MANIFEST_KEY_PREFIX}s:`;
260
260
  const NAMESPACE_MANIFEST_KEY_PREFIX = `${MANIFEST_KEY_PREFIX}n:`;
261
261
  const DEFAULT_LOCAL_STORAGE_CLEANUP_INTERVAL_MS = 1440 * 60 * 1e3;
262
262
  const DEFAULT_LOCAL_STORAGE_MAX_AGE_MS = 10080 * 60 * 1e3;
263
+ const MANAGED_LOCAL_STORAGE_MAINTENANCE_CHUNK_SIZE = 25;
263
264
  const maintenanceCallbacks = /* @__PURE__ */ new Map();
264
265
  let managedLocalStorageRuntimeConfig = {
265
266
  cleanupIntervalMs: DEFAULT_LOCAL_STORAGE_CLEANUP_INTERVAL_MS,
266
267
  maxAgeMs: DEFAULT_LOCAL_STORAGE_MAX_AGE_MS
267
268
  };
269
+ const managedLocalStorageMutationListeners = /* @__PURE__ */ new Set();
270
+ function addManagedLocalStorageMutationListener(listener) {
271
+ managedLocalStorageMutationListeners.add(listener);
272
+ return () => managedLocalStorageMutationListeners.delete(listener);
273
+ }
274
+ function notifyManagedLocalStorageMutation(key) {
275
+ for (const listener of managedLocalStorageMutationListeners) listener(key);
276
+ }
268
277
  const directManagedLocalStorageIo = {
269
278
  getItem(key) {
270
279
  return localStorage.getItem(key);
271
280
  },
272
281
  setItem(key, value) {
273
- setManagedLocalStorageItemWithQuotaRecovery(key, value, directManagedLocalStorageIo);
282
+ if (setManagedLocalStorageItemWithQuotaRecovery(key, value, directManagedLocalStorageIo)) notifyManagedLocalStorageMutation(key);
274
283
  },
275
284
  removeItem(key) {
276
285
  localStorage.removeItem(key);
286
+ notifyManagedLocalStorageMutation(key);
277
287
  },
278
288
  listKeys() {
279
289
  const keys = [];
@@ -869,6 +879,45 @@ function removeManagedLocalStorageNamespacePayload(payloadKey, storagePrefix, io
869
879
  removeManifestEntry(current.manifestKey, current.entry.entryKey, io);
870
880
  return true;
871
881
  }
882
+ /**
883
+ * Removes a deadline-bounded batch from one namespace and rewrites its
884
+ * manifest once. The access timestamp is an optimistic concurrency token: a
885
+ * payload refreshed between maintenance slices is left untouched and can be
886
+ * reconsidered by a later pass.
887
+ */
888
+ function removeManagedLocalStorageNamespaceEntriesIfUnchanged(storagePrefix, candidates, candidateIndex, shouldYield, io = directManagedLocalStorageIo) {
889
+ const manifestKey = getManagedLocalStorageManifestKeyForPrefix(storagePrefix);
890
+ const manifest = readParsedManifest(manifestKey, io);
891
+ if (manifest === null) return {
892
+ processedCount: candidates.length - candidateIndex,
893
+ removedEntryKeys: [],
894
+ staleEntryKeys: candidates.slice(candidateIndex).map((candidate) => candidate.entryKey)
895
+ };
896
+ const nextEntries = new Map(manifest.entries);
897
+ const removedEntryKeys = [];
898
+ const staleEntryKeys = [];
899
+ let processedCount = 0;
900
+ for (let index = candidateIndex; index < candidates.length; index++) {
901
+ if (processedCount > 0 && shouldYield()) break;
902
+ processedCount++;
903
+ const candidate = candidates[index];
904
+ if (candidate === void 0) continue;
905
+ const currentEntry = nextEntries.get(candidate.entryKey);
906
+ if (currentEntry?.lastAccessAt !== candidate.lastAccessAt || isManagedLocalStorageEntryOfflineProtected(currentEntry.meta) !== candidate.offlineProtected) {
907
+ staleEntryKeys.push(candidate.entryKey);
908
+ continue;
909
+ }
910
+ io.removeItem(`${storagePrefix}${candidate.entryKey}`);
911
+ nextEntries.delete(candidate.entryKey);
912
+ removedEntryKeys.push(candidate.entryKey);
913
+ }
914
+ if (removedEntryKeys.length > 0) writeManifest(manifestKey, { entries: nextEntries }, io);
915
+ return {
916
+ processedCount,
917
+ removedEntryKeys,
918
+ staleEntryKeys
919
+ };
920
+ }
872
921
  function removeManagedLocalStorageSinglePayload(payloadKey, io = directManagedLocalStorageIo) {
873
922
  const current = readSingleManifestEntryByPayload(payloadKey, io);
874
923
  if (!current) return false;
@@ -903,17 +952,13 @@ function getSessionKeyForManifestLocation(manifestLocation) {
903
952
  if (namespaceRootEnd === -1) return null;
904
953
  return getSessionKeyFromStorageIdentity(trimmedPrefix.slice(0, namespaceRootEnd));
905
954
  }
906
- function getCachedOfflineStatus(sessionKey, io, cache) {
907
- const cached = cache.get(sessionKey);
908
- if (cached !== void 0) return cached;
909
- const result = isSessionOfflineDuringManagedCleanup(sessionKey, io);
910
- cache.set(sessionKey, result);
911
- return result;
912
- }
913
955
  function isSessionOfflineDuringManagedCleanup(sessionKey, io) {
914
956
  const rawStatus = parseCompactLocalStorageEntry(io.getItem(getOfflineSessionStatusStorageKey(sessionKey)))?.value;
915
957
  return isOfflineModeStatusValue(isObject(rawStatus) && isObject(rawStatus.d) ? rawStatus.d : rawStatus ?? null);
916
958
  }
959
+ function readOfflineStatus(sessionKey, io) {
960
+ return isSessionOfflineDuringManagedCleanup(sessionKey, io);
961
+ }
917
962
  function clearManagedLocalStorageSession(sessionKey, io = directManagedLocalStorageIo) {
918
963
  const payloadPrefix = `tsdf.${sessionKey}.`;
919
964
  for (const key of io.listKeys()) {
@@ -945,57 +990,110 @@ function isMaintenanceDue(state) {
945
990
  if (state.lastCleanupAt === null) return true;
946
991
  return Date.now() - state.lastCleanupAt >= managedLocalStorageRuntimeConfig.cleanupIntervalMs;
947
992
  }
948
- function runStrictTsdfLocalStorageCleanup(io) {
949
- const tsdfKeys = io.listKeys().filter((key) => key.startsWith("tsdf."));
993
+ const MANIFEST_NAMESPACE_ENTRY_PREFIXES = [
994
+ "ci",
995
+ "li",
996
+ "lq",
997
+ "oq",
998
+ "oc",
999
+ "oe"
1000
+ ];
1001
+ function isManifestBackedPayloadCurrentlyOwned(payloadKey, io) {
1002
+ for (const entryPrefix of MANIFEST_NAMESPACE_ENTRY_PREFIXES) {
1003
+ const namespaceMarker = `.${entryPrefix}.`;
1004
+ let markerIndex = payloadKey.indexOf(namespaceMarker);
1005
+ while (markerIndex !== -1) {
1006
+ const storagePrefix = payloadKey.slice(0, markerIndex + namespaceMarker.length);
1007
+ const entryKey = payloadKey.slice(storagePrefix.length);
1008
+ if (readParsedManifest(getManagedLocalStorageManifestKeyForPrefix(storagePrefix), io)?.entries.has(entryKey) === true) return true;
1009
+ markerIndex = payloadKey.indexOf(namespaceMarker, markerIndex + 1);
1010
+ }
1011
+ }
1012
+ return readParsedManifest(getManagedLocalStorageManifestKeyForSingle(payloadKey), io)?.entries.has(void 0) === true;
1013
+ }
1014
+ function shouldRunGenericCleanupForManifestLocation(location) {
1015
+ if (location.kind === "single") return !isOfflinePayloadKey(location.payloadKey);
1016
+ return !isOfflineNamespaceStoragePrefix(location.storagePrefix);
1017
+ }
1018
+ async function runGlobalTsdfLocalStorageCleanup(runLocked, context) {
1019
+ const allKeys = await runLocked((io) => io.listKeys());
1020
+ const tsdfKeys = allKeys.filter((key) => key.startsWith("tsdf."));
1021
+ const knownKeys = new Set(allKeys);
950
1022
  const manifestOwnedPayloadKeys = /* @__PURE__ */ new Set();
1023
+ const removedPayloadKeys = /* @__PURE__ */ new Set();
951
1024
  const manifestBackedPayloadKeys = [];
952
- for (const key of tsdfKeys) {
953
- const classification = classifyTsdfLocalStorageKey(key);
954
- if (classification === null) continue;
955
- switch (classification.kind) {
956
- case "global-maintenance":
957
- if (readParsedMetadataJson(key, managedLocalStorageGlobalMaintenanceSchema, io) === null) removeMetadataJson(key, io);
958
- break;
959
- case "async-global-maintenance":
960
- if (readParsedMetadataJson(key, managedLocalStorageGlobalMaintenanceSchema, io) === null) removeMetadataJson(key, io);
961
- break;
962
- case "manifest": {
963
- const manifest = readParsedManifest(key, io);
964
- if (manifest === null) {
965
- removeMetadataJson(key, io);
966
- break;
967
- }
968
- for (const entry of manifest.entries.values()) {
969
- const payloadKey = getPayloadKeyForManifestEntry(classification.manifestLocation, entry.entryKey);
970
- if (payloadKey !== null) manifestOwnedPayloadKeys.add(payloadKey);
1025
+ const manifestTargets = [];
1026
+ const manifestOwnershipSnapshots = [];
1027
+ let keyIndex = 0;
1028
+ while (keyIndex < tsdfKeys.length) {
1029
+ if (!await context.yieldIfNeeded()) return null;
1030
+ await runLocked((io) => {
1031
+ let processedCount = 0;
1032
+ while (keyIndex < tsdfKeys.length) {
1033
+ if (processedCount > 0 && context.shouldYield()) break;
1034
+ const key = tsdfKeys[keyIndex];
1035
+ keyIndex++;
1036
+ processedCount++;
1037
+ if (key === void 0) continue;
1038
+ const classification = classifyTsdfLocalStorageKey(key);
1039
+ if (classification === null) continue;
1040
+ switch (classification.kind) {
1041
+ case "global-maintenance":
1042
+ if (readParsedMetadataJson(key, managedLocalStorageGlobalMaintenanceSchema, io) === null) removeMetadataJson(key, io);
1043
+ break;
1044
+ case "async-global-maintenance":
1045
+ if (readParsedMetadataJson(key, managedLocalStorageGlobalMaintenanceSchema, io) === null) removeMetadataJson(key, io);
1046
+ break;
1047
+ case "manifest":
1048
+ manifestTargets.push({
1049
+ cleanEntries: shouldRunGenericCleanupForManifestLocation(classification.manifestLocation),
1050
+ manifestKey: key
1051
+ });
1052
+ break;
1053
+ case "compact-list-query":
1054
+ if (readCompactListQueryEntry(key, io) === null) io.removeItem(key);
1055
+ break;
1056
+ case "manifest-backed-payload":
1057
+ manifestBackedPayloadKeys.push(key);
1058
+ break;
1059
+ case "unknown-tsdf":
1060
+ io.removeItem(key);
1061
+ break;
971
1062
  }
972
- break;
973
1063
  }
974
- case "compact-list-query":
975
- if (readCompactListQueryEntry(key, io) === null) io.removeItem(key);
976
- break;
977
- case "manifest-backed-payload":
978
- manifestBackedPayloadKeys.push(key);
979
- break;
980
- case "unknown-tsdf":
981
- io.removeItem(key);
982
- break;
983
- }
1064
+ });
984
1065
  }
985
- for (const payloadKey of manifestBackedPayloadKeys) if (!manifestOwnedPayloadKeys.has(payloadKey)) io.removeItem(payloadKey);
986
- }
987
- function collectManagedLocalStorageSweepTargets(io) {
988
- const allKeys = io.listKeys();
989
- return {
990
- manifestKeys: allKeys.filter((key) => {
991
- if (!isManagedLocalStorageManifestKey(key)) return false;
992
- const manifestLocation = parseManagedLocalStorageManifestKey(key);
993
- if (manifestLocation?.kind === "single" && isOfflinePayloadKey(manifestLocation.payloadKey)) return false;
994
- if (manifestLocation?.kind === "namespace" && isOfflineNamespaceStoragePrefix(manifestLocation.storagePrefix)) return false;
995
- return true;
996
- }),
997
- knownKeys: new Set(allKeys)
998
- };
1066
+ const manifestKeys = [];
1067
+ for (const { cleanEntries, manifestKey } of manifestTargets) if (!await runGenericCleanupForManifest(manifestKey, knownKeys, runLocked, context, cleanEntries, removedPayloadKeys, (location, entryKeys) => {
1068
+ manifestOwnershipSnapshots.push({
1069
+ entryKeys,
1070
+ location
1071
+ });
1072
+ if (cleanEntries) manifestKeys.push(manifestKey);
1073
+ })) return null;
1074
+ for (const snapshot of manifestOwnershipSnapshots) for (const [entryIndex, entryKey] of snapshot.entryKeys.entries()) {
1075
+ if (entryIndex % MANAGED_LOCAL_STORAGE_MAINTENANCE_CHUNK_SIZE === 0 && !await context.yieldIfNeeded()) return null;
1076
+ const payloadKey = getPayloadKeyForManifestEntry(snapshot.location, entryKey);
1077
+ if (payloadKey !== null) manifestOwnedPayloadKeys.add(payloadKey);
1078
+ }
1079
+ let orphanIndex = 0;
1080
+ while (orphanIndex < manifestBackedPayloadKeys.length) {
1081
+ if (!await context.yieldIfNeeded()) return null;
1082
+ await runLocked((io) => {
1083
+ let processedCount = 0;
1084
+ while (orphanIndex < manifestBackedPayloadKeys.length) {
1085
+ if (processedCount > 0 && context.shouldYield()) break;
1086
+ const payloadKey = manifestBackedPayloadKeys[orphanIndex];
1087
+ orphanIndex++;
1088
+ processedCount++;
1089
+ if (payloadKey === void 0) continue;
1090
+ if (manifestOwnedPayloadKeys.has(payloadKey)) continue;
1091
+ if (removedPayloadKeys.has(payloadKey)) continue;
1092
+ if (!isManifestBackedPayloadCurrentlyOwned(payloadKey, io)) io.removeItem(payloadKey);
1093
+ }
1094
+ });
1095
+ }
1096
+ return { manifestKeys };
999
1097
  }
1000
1098
  /**
1001
1099
  * Offline-owned payload keys, excluding the session status entry (which is
@@ -1004,60 +1102,99 @@ function collectManagedLocalStorageSweepTargets(io) {
1004
1102
  function isOfflinePayloadKey(payloadKey) {
1005
1103
  return payloadKey.includes(OFFLINE_ROOT_KEY_INFIX) && !payloadKey.endsWith(OFFLINE_SESSION_STATUS_KEY_SUFFIX);
1006
1104
  }
1007
- function runGenericCleanupForManifest(manifestKey, knownKeys, io, offlineSessionCache) {
1105
+ async function runGenericCleanupForManifest(manifestKey, knownKeys, runLocked, context, cleanEntries = true, removedPayloadKeys, onManifestCleaned) {
1008
1106
  const manifestLocation = parseManagedLocalStorageManifestKey(manifestKey);
1009
1107
  if (!manifestLocation) {
1010
- removeMetadataJson(manifestKey, io);
1011
- return;
1012
- }
1013
- const manifest = readParsedManifest(manifestKey, io);
1014
- if (!manifest) {
1015
- if (io.getItem(manifestKey) !== null) removeMetadataJson(manifestKey, io);
1016
- return;
1108
+ await runLocked((io) => removeMetadataJson(manifestKey, io));
1109
+ return true;
1017
1110
  }
1018
- const now = Date.now();
1019
1111
  const sessionKey = getSessionKeyForManifestLocation(manifestLocation);
1020
- const offlineStatusKey = sessionKey === null ? null : getOfflineSessionStatusStorageKey(sessionKey);
1021
- const skipExpiration = sessionKey !== null && offlineStatusKey !== null && knownKeys !== null && knownKeys.has(offlineStatusKey) && getCachedOfflineStatus(sessionKey, io, offlineSessionCache);
1022
- const nextEntries = /* @__PURE__ */ new Map();
1023
- for (const entry of manifest.entries.values()) {
1024
- const payloadKey = getPayloadKeyForManifestEntry(manifestLocation, entry.entryKey);
1025
- if (payloadKey === null) continue;
1026
- if (knownKeys !== null && !knownKeys.has(payloadKey)) continue;
1027
- if (!isOfflinePayloadKey(payloadKey) && !isManagedLocalStorageEntryOfflineProtected(entry.meta) && !skipExpiration && now - entry.lastAccessAt > managedLocalStorageRuntimeConfig.maxAgeMs) {
1028
- io.removeItem(payloadKey);
1029
- continue;
1030
- }
1031
- nextEntries.set(entry.entryKey, entry);
1032
- }
1033
- if (nextEntries.size === manifest.entries.size) return;
1034
- writeManifest(manifestKey, { entries: nextEntries }, io);
1112
+ const manifestUsesOfflineStorageRoot = isOfflineOwnedManifestLocation(manifestLocation);
1113
+ let entryKeys = [];
1114
+ let manifestInitialized = false;
1115
+ let entryIndex = 0;
1116
+ do {
1117
+ if (!await context.yieldIfNeeded()) return false;
1118
+ await runLocked((io) => {
1119
+ const manifest = readParsedManifest(manifestKey, io);
1120
+ if (manifest === null) {
1121
+ if (io.getItem(manifestKey) !== null) removeMetadataJson(manifestKey, io);
1122
+ manifestInitialized = true;
1123
+ entryIndex = entryKeys.length;
1124
+ return;
1125
+ }
1126
+ if (!manifestInitialized) {
1127
+ entryKeys = [...manifest.entries.keys()];
1128
+ manifestInitialized = true;
1129
+ }
1130
+ if (!cleanEntries) {
1131
+ entryIndex = entryKeys.length;
1132
+ onManifestCleaned?.(manifestLocation, entryKeys);
1133
+ return;
1134
+ }
1135
+ const nextEntries = new Map(manifest.entries);
1136
+ let skipExpiration;
1137
+ let manifestChanged = false;
1138
+ let processedCount = 0;
1139
+ while (entryIndex < entryKeys.length) {
1140
+ if (processedCount > 0 && context.shouldYield()) break;
1141
+ const entryKey = entryKeys[entryIndex];
1142
+ entryIndex++;
1143
+ processedCount++;
1144
+ const entry = nextEntries.get(entryKey);
1145
+ if (entry === void 0) continue;
1146
+ const payloadKey = getPayloadKeyForManifestEntry(manifestLocation, entry.entryKey);
1147
+ if (payloadKey === null) {
1148
+ nextEntries.delete(entryKey);
1149
+ manifestChanged = true;
1150
+ continue;
1151
+ }
1152
+ const payloadMissing = knownKeys !== null && !knownKeys.has(payloadKey) && io.getItem(payloadKey) === null;
1153
+ const expired = !payloadMissing && !isOfflinePayloadKey(payloadKey) && !isManagedLocalStorageEntryOfflineProtected(entry.meta) && Date.now() - entry.lastAccessAt > managedLocalStorageRuntimeConfig.maxAgeMs && !(skipExpiration ??= knownKeys !== null && sessionKey !== null && !manifestUsesOfflineStorageRoot && readOfflineStatus(sessionKey, io));
1154
+ if (!payloadMissing && !expired) continue;
1155
+ if (expired) {
1156
+ io.removeItem(payloadKey);
1157
+ removedPayloadKeys?.add(payloadKey);
1158
+ }
1159
+ nextEntries.delete(entryKey);
1160
+ manifestChanged = true;
1161
+ }
1162
+ if (manifestChanged) writeManifest(manifestKey, { entries: nextEntries }, io);
1163
+ if (entryIndex >= entryKeys.length) onManifestCleaned?.(manifestLocation, [...nextEntries.keys()]);
1164
+ });
1165
+ } while (entryIndex < entryKeys.length);
1166
+ return true;
1035
1167
  }
1036
- async function runManagedLocalStorageMaintenance(io = directManagedLocalStorageIo, { forceManifestKeys = [] } = {}) {
1168
+ async function runManagedLocalStorageMaintenance({ context, forceManifestKeys = [], runLocked }) {
1037
1169
  const forcedManifestKeys = new Set(forceManifestKeys);
1038
1170
  const runGlobalSweep = forcedManifestKeys.size === 0;
1039
- if (runGlobalSweep && !isMaintenanceDue(readGlobalMaintenanceState(io))) return;
1040
- if (runGlobalSweep) runStrictTsdfLocalStorageCleanup(io);
1041
- const { manifestKeys, knownKeys } = runGlobalSweep ? collectManagedLocalStorageSweepTargets(io) : {
1042
- manifestKeys: [...forcedManifestKeys],
1043
- knownKeys: null
1044
- };
1171
+ if (runGlobalSweep) {
1172
+ if (!await runLocked((io) => isMaintenanceDue(readGlobalMaintenanceState(io)))) return;
1173
+ }
1174
+ const globalCleanupResult = runGlobalSweep ? await runGlobalTsdfLocalStorageCleanup(runLocked, context) : null;
1175
+ if (runGlobalSweep && globalCleanupResult === null) return;
1176
+ const manifestKeys = runGlobalSweep ? globalCleanupResult?.manifestKeys ?? [] : [...forcedManifestKeys];
1045
1177
  const invokedCallbacks = /* @__PURE__ */ new Set();
1046
- const offlineSessionCache = /* @__PURE__ */ new Map();
1047
1178
  for (const manifestKey of manifestKeys) {
1048
- runGenericCleanupForManifest(manifestKey, knownKeys, io, offlineSessionCache);
1179
+ if (!runGlobalSweep) {
1180
+ if (!await runGenericCleanupForManifest(manifestKey, null, runLocked, context)) return;
1181
+ }
1049
1182
  const callback = maintenanceCallbacks.get(manifestKey);
1050
1183
  if (!callback || invokedCallbacks.has(callback)) continue;
1051
1184
  invokedCallbacks.add(callback);
1052
- await callback();
1185
+ await callback(context);
1186
+ if (context.isCanceled()) return;
1053
1187
  }
1054
1188
  if (runGlobalSweep) {
1055
1189
  for (const callback of maintenanceCallbacks.values()) {
1056
1190
  if (invokedCallbacks.has(callback)) continue;
1057
1191
  invokedCallbacks.add(callback);
1058
- await callback();
1192
+ await callback(context);
1193
+ if (context.isCanceled()) return;
1059
1194
  }
1060
- writeGlobalMaintenanceState({ lastCleanupAt: Date.now() }, io);
1195
+ await runLocked((io) => {
1196
+ writeGlobalMaintenanceState({ lastCleanupAt: Date.now() }, io);
1197
+ });
1061
1198
  }
1062
1199
  }
1063
1200
  //#endregion
@@ -1209,6 +1346,39 @@ async function clearRegisteredOfflineUploadStorage(sessionKey) {
1209
1346
  const MANAGED_LOCAL_STORAGE_LOCK_NAME = "tsdf-local-storage-metadata";
1210
1347
  const MANAGED_LOCAL_STORAGE_LOCK_WARNING = "[TSDF] navigator.locks is unavailable; localPersistentStorage is using unlocked localStorage coordination.";
1211
1348
  const managedLocalStorageIoStack = [];
1349
+ const sharedManifestRawCache = /* @__PURE__ */ new Map();
1350
+ let sharedManifestCacheClearScheduled = false;
1351
+ function isManagedLocalStorageManifestCacheKey(key) {
1352
+ return key.startsWith("tsdf._m.r.");
1353
+ }
1354
+ function rememberSharedManifestRaw(key, raw) {
1355
+ sharedManifestRawCache.set(key, raw);
1356
+ if (sharedManifestCacheClearScheduled) return;
1357
+ sharedManifestCacheClearScheduled = true;
1358
+ queueMicrotask(() => {
1359
+ sharedManifestCacheClearScheduled = false;
1360
+ sharedManifestRawCache.clear();
1361
+ });
1362
+ }
1363
+ const sharedDirectManagedLocalStorageIo = {
1364
+ getItem(key) {
1365
+ if (!isManagedLocalStorageManifestCacheKey(key)) return directManagedLocalStorageIo.getItem(key);
1366
+ ensureManagedStorageInvalidationListener();
1367
+ if (sharedManifestRawCache.has(key)) return sharedManifestRawCache.get(key) ?? null;
1368
+ const raw = directManagedLocalStorageIo.getItem(key);
1369
+ rememberSharedManifestRaw(key, raw);
1370
+ return raw;
1371
+ },
1372
+ setItem(key, value) {
1373
+ directManagedLocalStorageIo.setItem(key, value);
1374
+ },
1375
+ removeItem(key) {
1376
+ directManagedLocalStorageIo.removeItem(key);
1377
+ },
1378
+ listKeys() {
1379
+ return directManagedLocalStorageIo.listKeys();
1380
+ }
1381
+ };
1212
1382
  function createCachedManagedLocalStorageIo() {
1213
1383
  const VALUE_NOT_LOADED = Symbol("VALUE_NOT_LOADED");
1214
1384
  const cache = /* @__PURE__ */ new Map();
@@ -1248,22 +1418,29 @@ function createCachedManagedLocalStorageIo() {
1248
1418
  });
1249
1419
  }
1250
1420
  const io = {
1421
+ invalidate(key) {
1422
+ cache.delete(key);
1423
+ allKeysLoaded = false;
1424
+ },
1251
1425
  getItem(key) {
1252
1426
  if (!active) return localStorage.getItem(key);
1253
1427
  if (cache.has(key)) {
1254
1428
  const cachedValue = cache.get(key);
1255
1429
  if (cachedValue !== VALUE_NOT_LOADED) return cachedValue ?? null;
1256
1430
  }
1257
- const raw = localStorage.getItem(key);
1431
+ const raw = sharedDirectManagedLocalStorageIo.getItem(key);
1258
1432
  cache.set(key, raw);
1259
1433
  return raw;
1260
1434
  },
1261
1435
  setItem(key, value) {
1262
- if (setManagedLocalStorageItemWithQuotaRecovery(key, value, io) && active) cache.set(key, value);
1436
+ const written = setManagedLocalStorageItemWithQuotaRecovery(key, value, io);
1437
+ if (written && active) cache.set(key, value);
1438
+ if (written) invalidateManagedStorageCachesAfterMutation(key, io);
1263
1439
  },
1264
1440
  removeItem(key) {
1265
1441
  if (active) cache.set(key, null);
1266
1442
  localStorage.removeItem(key);
1443
+ invalidateManagedStorageCachesAfterMutation(key, io);
1267
1444
  },
1268
1445
  listKeys() {
1269
1446
  if (!active) return directManagedLocalStorageIo.listKeys();
@@ -1281,6 +1458,7 @@ function createCachedManagedLocalStorageIo() {
1281
1458
  if (value !== null && isLocalStorageQuotaWritesDisabled()) return;
1282
1459
  cache.set(key, value);
1283
1460
  pendingManifestWrites.set(key, value);
1461
+ invalidateManagedStorageCachesAfterMutation(key, io);
1284
1462
  schedulePendingManifestFlush();
1285
1463
  }
1286
1464
  };
@@ -1290,9 +1468,49 @@ function createCachedManagedLocalStorageIo() {
1290
1468
  active = false;
1291
1469
  cache.clear();
1292
1470
  },
1293
- io
1471
+ flush: flushPendingManifestWrites,
1472
+ invalidateAll() {
1473
+ cache.clear();
1474
+ allKeysLoaded = false;
1475
+ },
1476
+ io,
1477
+ reset() {
1478
+ flushPendingManifestWrites();
1479
+ cache.clear();
1480
+ allKeysLoaded = false;
1481
+ }
1294
1482
  };
1295
1483
  }
1484
+ const activeMaintenanceCaches = /* @__PURE__ */ new Set();
1485
+ let managedStorageInvalidationListenerReady = false;
1486
+ function invalidateManagedStorageCachesAfterMutation(key, source) {
1487
+ sharedManifestRawCache.delete(key);
1488
+ for (const cache of activeMaintenanceCaches) if (cache.io !== source) cache.io.invalidate?.(key);
1489
+ }
1490
+ function ensureManagedStorageInvalidationListener() {
1491
+ if (managedStorageInvalidationListenerReady) return;
1492
+ addManagedLocalStorageMutationListener((key) => {
1493
+ invalidateManagedStorageCachesAfterMutation(key, directManagedLocalStorageIo);
1494
+ });
1495
+ window.addEventListener("storage", (event) => {
1496
+ if (event.storageArea !== null && event.storageArea !== localStorage) return;
1497
+ if (event.key === null) sharedManifestRawCache.clear();
1498
+ else sharedManifestRawCache.delete(event.key);
1499
+ for (const cache of activeMaintenanceCaches) if (event.key === null) cache.invalidateAll();
1500
+ else cache.io.invalidate?.(event.key);
1501
+ });
1502
+ managedStorageInvalidationListenerReady = true;
1503
+ }
1504
+ const maintenanceIoCaches = /* @__PURE__ */ new WeakMap();
1505
+ async function withExistingManagedLocalStorageIoCache(cachedIo, callback) {
1506
+ managedLocalStorageIoStack.push(cachedIo.io);
1507
+ try {
1508
+ return await callback();
1509
+ } finally {
1510
+ cachedIo.flush();
1511
+ managedLocalStorageIoStack.pop();
1512
+ }
1513
+ }
1296
1514
  async function withManagedLocalStorageIoCache(callback) {
1297
1515
  const cachedIo = createCachedManagedLocalStorageIo();
1298
1516
  managedLocalStorageIoStack.push(cachedIo.io);
@@ -1307,20 +1525,20 @@ function getManagedLocalStorageIo() {
1307
1525
  return managedLocalStorageIoStack[managedLocalStorageIoStack.length - 1];
1308
1526
  }
1309
1527
  function getActiveManagedLocalStorageIo() {
1310
- return getManagedLocalStorageIo() ?? directManagedLocalStorageIo;
1528
+ return getManagedLocalStorageIo() ?? sharedDirectManagedLocalStorageIo;
1311
1529
  }
1312
1530
  function getManagedLocalStorageIoWithWarning() {
1313
1531
  warnIfNavigatorLockUnavailable(MANAGED_LOCAL_STORAGE_LOCK_WARNING);
1314
1532
  return getActiveManagedLocalStorageIo();
1315
1533
  }
1316
- async function runWithManagedLocalStorageLock(callback) {
1534
+ async function runWithManagedLocalStorageLock(callback, existingCachedIo) {
1317
1535
  if (getManagedLocalStorageIo() !== void 0) return await callback();
1318
1536
  const lockManager = getNavigatorLockManager();
1319
1537
  if (lockManager === null) {
1320
1538
  warnIfNavigatorLockUnavailable(MANAGED_LOCAL_STORAGE_LOCK_WARNING);
1321
- return await trackManagedLocalStorageMutationWrites(callback);
1539
+ return await trackManagedLocalStorageMutationWrites(() => existingCachedIo === void 0 ? callback() : withExistingManagedLocalStorageIoCache(existingCachedIo, callback));
1322
1540
  }
1323
- return lockManager.request(MANAGED_LOCAL_STORAGE_LOCK_NAME, () => trackManagedLocalStorageMutationWrites(() => withManagedLocalStorageIoCache(callback)));
1541
+ return lockManager.request(MANAGED_LOCAL_STORAGE_LOCK_NAME, () => trackManagedLocalStorageMutationWrites(() => existingCachedIo === void 0 ? withManagedLocalStorageIoCache(callback) : withExistingManagedLocalStorageIoCache(existingCachedIo, callback)));
1324
1542
  }
1325
1543
  const localPersistentStorage = {
1326
1544
  /** Identifier for adapter type and sync runtime behavior. */
@@ -1328,6 +1546,16 @@ const localPersistentStorage = {
1328
1546
  runLocked(callback) {
1329
1547
  return runWithManagedLocalStorageLock(callback);
1330
1548
  },
1549
+ runMaintenanceLocked(context, callback) {
1550
+ const maintenanceIo = maintenanceIoCaches.get(context);
1551
+ if (maintenanceIo === void 0) return runWithManagedLocalStorageLock(callback);
1552
+ const continuationCount = context.getContinuationCount();
1553
+ if (continuationCount !== maintenanceIo.continuationCount) {
1554
+ maintenanceIo.cache.reset();
1555
+ maintenanceIo.continuationCount = continuationCount;
1556
+ }
1557
+ return runWithManagedLocalStorageLock(callback, maintenanceIo.cache);
1558
+ },
1331
1559
  readRaw(key) {
1332
1560
  return getManagedLocalStorageIoWithWarning().getItem(key);
1333
1561
  },
@@ -1396,6 +1624,9 @@ const localPersistentStorage = {
1396
1624
  touchNamespaceEntry(payloadKey, namespacePrefix) {
1397
1625
  return touchManagedLocalStorageNamespacePayload(payloadKey, namespacePrefix, getManagedLocalStorageIoWithWarning());
1398
1626
  },
1627
+ removeNamespaceEntriesIfUnchanged(storagePrefix, candidates, candidateIndex, shouldYield) {
1628
+ return removeManagedLocalStorageNamespaceEntriesIfUnchanged(storagePrefix, candidates, candidateIndex, shouldYield, getManagedLocalStorageIoWithWarning());
1629
+ },
1399
1630
  clearManifest(manifestKey) {
1400
1631
  clearManagedLocalStorageManifest(manifestKey, getManagedLocalStorageIoWithWarning());
1401
1632
  },
@@ -1410,8 +1641,23 @@ const localPersistentStorage = {
1410
1641
  warnIfNavigatorLockUnavailable(MANAGED_LOCAL_STORAGE_LOCK_WARNING);
1411
1642
  unregisterManagedLocalStorageMaintenanceCallback(manifestKey);
1412
1643
  },
1413
- runMaintenance(forceManifestKeys) {
1414
- return runWithManagedLocalStorageLock(() => runManagedLocalStorageMaintenance(getManagedLocalStorageIoWithWarning(), { forceManifestKeys }));
1644
+ runMaintenance(forceManifestKeys, context) {
1645
+ const cache = createCachedManagedLocalStorageIo();
1646
+ ensureManagedStorageInvalidationListener();
1647
+ activeMaintenanceCaches.add(cache);
1648
+ maintenanceIoCaches.set(context, {
1649
+ cache,
1650
+ continuationCount: context.getContinuationCount()
1651
+ });
1652
+ return runManagedLocalStorageMaintenance({
1653
+ context,
1654
+ forceManifestKeys,
1655
+ runLocked: (callback) => localPersistentStorage.runMaintenanceLocked(context, () => callback(getManagedLocalStorageIoWithWarning()))
1656
+ }).finally(() => {
1657
+ maintenanceIoCaches.delete(context);
1658
+ activeMaintenanceCaches.delete(cache);
1659
+ cache.deactivate();
1660
+ });
1415
1661
  },
1416
1662
  readProtectedStorageKeys(sessionKey) {
1417
1663
  return readManagedLocalStorageProtectedKeys(sessionKey, getManagedLocalStorageIoWithWarning());
@@ -1427,6 +1673,8 @@ let localStorageExpirationScanScheduled = false;
1427
1673
  let scannedAsyncAdapters = /* @__PURE__ */ new WeakSet();
1428
1674
  let localStorageTouchTimestamps = /* @__PURE__ */ new Map();
1429
1675
  let cancelScheduledLocalStorageMaintenance = null;
1676
+ let localStorageMaintenanceRunning = false;
1677
+ let localStorageMaintenanceGeneration = 0;
1430
1678
  let localStorageGlobalMaintenanceRequested = false;
1431
1679
  let scheduledLocalStorageMaintenanceManifestKeys = /* @__PURE__ */ new Set();
1432
1680
  const scheduledAsyncMaintenance = /* @__PURE__ */ new Map();
@@ -1516,13 +1764,23 @@ function scheduleLocalStorageMaintenance(forceManifestKeys) {
1516
1764
  localStorageGlobalMaintenanceRequested = true;
1517
1765
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1518
1766
  } else if (!localStorageGlobalMaintenanceRequested) for (const manifestKey of forceManifestKeys) scheduledLocalStorageMaintenanceManifestKeys.add(manifestKey);
1519
- if (cancelScheduledLocalStorageMaintenance !== null) return;
1520
- cancelScheduledLocalStorageMaintenance = scheduleIdleCleanup(() => {
1767
+ scheduleQueuedLocalStorageMaintenance();
1768
+ }
1769
+ function scheduleQueuedLocalStorageMaintenance() {
1770
+ if (cancelScheduledLocalStorageMaintenance !== null || localStorageMaintenanceRunning) return;
1771
+ cancelScheduledLocalStorageMaintenance = scheduleIdleCleanup((deadline) => {
1521
1772
  cancelScheduledLocalStorageMaintenance = null;
1773
+ const generation = localStorageMaintenanceGeneration;
1522
1774
  const maintenanceManifestKeys = localStorageGlobalMaintenanceRequested ? void 0 : [...scheduledLocalStorageMaintenanceManifestKeys];
1523
1775
  localStorageGlobalMaintenanceRequested = false;
1524
1776
  scheduledLocalStorageMaintenanceManifestKeys.clear();
1525
- localPersistentStorage.runMaintenance(maintenanceManifestKeys);
1777
+ const context = createIdleCleanupContext(deadline);
1778
+ localStorageMaintenanceRunning = true;
1779
+ localPersistentStorage.runMaintenance(maintenanceManifestKeys, context).catch(handleManagedLocalStorageBackgroundError).finally(() => {
1780
+ if (generation !== localStorageMaintenanceGeneration) return;
1781
+ localStorageMaintenanceRunning = false;
1782
+ if (localStorageGlobalMaintenanceRequested || scheduledLocalStorageMaintenanceManifestKeys.size > 0) scheduleQueuedLocalStorageMaintenance();
1783
+ });
1526
1784
  });
1527
1785
  }
1528
1786
  function preserveOfflineProtectionFlag(sessionKey, storageKey, nextMeta, currentMeta) {
@@ -2154,9 +2412,68 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2154
2412
  key: entryKey
2155
2413
  }] });
2156
2414
  }
2415
+ async function replaceAll(entries) {
2416
+ const replaceEntries = async () => {
2417
+ const nextKeys = new Set(entries.map((entry) => entry.key));
2418
+ await commit({
2419
+ removes: (await listKeys()).filter((key) => !nextKeys.has(key)),
2420
+ upserts: entries
2421
+ });
2422
+ };
2423
+ if (asyncAdapter === null) {
2424
+ await runLocalStorageMutation(replaceEntries);
2425
+ return;
2426
+ }
2427
+ await replaceEntries();
2428
+ }
2157
2429
  async function remove(entryKey) {
2158
2430
  await commit({ removes: [entryKey] });
2159
2431
  }
2432
+ async function removeLocalEntriesIfUnchanged(entries, context, shouldContinue) {
2433
+ const removedKeys = /* @__PURE__ */ new Set();
2434
+ const staleKeys = /* @__PURE__ */ new Set();
2435
+ const prefix = getPrefix();
2436
+ if (asyncAdapter !== null || prefix === false) return {
2437
+ completed: false,
2438
+ removedKeys,
2439
+ staleKeys
2440
+ };
2441
+ const candidates = entries.map((entry) => ({
2442
+ entryKey: entry.key,
2443
+ lastAccessAt: entry.lastAccessAt,
2444
+ offlineProtected: entry.offlineProtected
2445
+ }));
2446
+ let entryIndex = 0;
2447
+ while (entryIndex < entries.length) {
2448
+ if (shouldContinue?.() === false) return {
2449
+ completed: false,
2450
+ removedKeys,
2451
+ staleKeys
2452
+ };
2453
+ if (!await context.yieldIfNeeded()) return {
2454
+ completed: false,
2455
+ removedKeys,
2456
+ staleKeys
2457
+ };
2458
+ const result = await localPersistentStorage.runMaintenanceLocked(context, () => {
2459
+ if (shouldContinue?.() === false) return null;
2460
+ return localPersistentStorage.removeNamespaceEntriesIfUnchanged(prefix, candidates, entryIndex, () => context.shouldYield());
2461
+ });
2462
+ if (result === null) return {
2463
+ completed: false,
2464
+ removedKeys,
2465
+ staleKeys
2466
+ };
2467
+ entryIndex += result.processedCount;
2468
+ for (const entryKey of result.removedEntryKeys) removedKeys.add(entryKey);
2469
+ for (const entryKey of result.staleEntryKeys) staleKeys.add(entryKey);
2470
+ }
2471
+ return {
2472
+ completed: true,
2473
+ removedKeys,
2474
+ staleKeys
2475
+ };
2476
+ }
2160
2477
  async function listMetadata(args = {}) {
2161
2478
  const startTime = import.meta.env.DEV ? startPersistentStorageDebugTiming(debugContext) : null;
2162
2479
  try {
@@ -2339,10 +2656,12 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2339
2656
  load,
2340
2657
  loadMany,
2341
2658
  save,
2659
+ replaceAll,
2342
2660
  remove,
2343
2661
  listKeys,
2344
2662
  listMetadata,
2345
2663
  listMetadataByFilter,
2664
+ removeLocalEntriesIfUnchanged,
2346
2665
  clear,
2347
2666
  dispose
2348
2667
  };
@@ -2439,7 +2758,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2439
2758
  }
2440
2759
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2441
2760
  async function clearAllSessionStorage(sessionKey) {
2442
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-CkGt87Po.js");
2761
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-ClUvxNQA.js");
2443
2762
  await Promise.all([
2444
2763
  clearSessionStorage(sessionKey, "local-sync"),
2445
2764
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -2513,6 +2832,7 @@ function scheduleAsyncStorageMaintenance(maintenanceKey, callback) {
2513
2832
  //#endregion
2514
2833
  //#region src/persistentStorage/collectionStorePersistence.ts
2515
2834
  const SAVE_DEBOUNCE_MS$1 = 1e3;
2835
+ const MAINTENANCE_SCAN_CHUNK_SIZE$1 = 25;
2516
2836
  function toCollectionItemState(persisted, dataSchema, shouldIgnoreItem) {
2517
2837
  const validated = parsePersistedStoreData(persisted.data, dataSchema);
2518
2838
  if (validated === null) return null;
@@ -2912,23 +3232,27 @@ function setupCollectionPersistence(config, options = {}) {
2912
3232
  async function maybeHydrateItems(itemKeys) {
2913
3233
  return preloadItems(itemKeys);
2914
3234
  }
2915
- async function evictStoredItems() {
3235
+ async function evictStoredItems(idleContext) {
2916
3236
  syncMaintenanceRegistration();
2917
3237
  const sessionKey = config.getSessionKey();
2918
3238
  const prefix = getCollectionPrefix();
2919
3239
  if (sessionKey === false || prefix === false) return;
2920
3240
  if (localStorageAdapter !== null) {
2921
- const metadataEntries = localStorageAdapter.listManifestEntries(prefix);
3241
+ const metadataEntries = await (idleContext === void 0 ? localStorageAdapter.runLocked(() => localStorageAdapter.listManifestEntries(prefix)) : localStorageAdapter.runMaintenanceLocked(idleContext, () => localStorageAdapter.listManifestEntries(prefix)));
2922
3242
  if (metadataEntries.length === 0) return;
2923
- const protectedItemKeys = new Set(metadataEntries.flatMap((entry) => isManagedLocalStorageEntryOfflineProtected(entry.meta) ? [entry.entryKey] : []));
2924
- const metadataEntriesWithPayload = metadataEntries.map((entry) => ({
2925
- itemKey: entry.entryKey,
2926
- lastAccessAt: entry.lastAccessAt,
2927
- sizeBytes: rememberPersistedMetadataSize(entry.entryKey, entry.sizeBytes),
2928
- payload: validateWithSchema(config.payloadSchema, readManifestPayloadMeta(entry.meta))
2929
- }));
3243
+ const protectedItemKeys = /* @__PURE__ */ new Set();
3244
+ const metadataEntriesWithPayload = [];
3245
+ for (const [entryIndex, entry] of metadataEntries.entries()) {
3246
+ if (idleContext !== void 0 && entryIndex % MAINTENANCE_SCAN_CHUNK_SIZE$1 === 0 && !await idleContext.yieldIfNeeded()) return;
3247
+ if (isManagedLocalStorageEntryOfflineProtected(entry.meta)) protectedItemKeys.add(entry.entryKey);
3248
+ metadataEntriesWithPayload.push({
3249
+ itemKey: entry.entryKey,
3250
+ lastAccessAt: entry.lastAccessAt,
3251
+ sizeBytes: rememberPersistedMetadataSize(entry.entryKey, entry.sizeBytes),
3252
+ payload: validateWithSchema(config.payloadSchema, readManifestPayloadMeta(entry.meta))
3253
+ });
3254
+ }
2930
3255
  const invalidEntries = filterAndMap(metadataEntriesWithPayload, ({ itemKey, payload }) => payload === null ? { itemKey } : false);
2931
- if (invalidEntries.length > 0) await Promise.all(invalidEntries.map(({ itemKey }) => namespace.remove(itemKey)));
2932
3256
  const persistedEntries = filterAndMap(metadataEntriesWithPayload, ({ itemKey, lastAccessAt, payload, sizeBytes }) => payload === null ? false : {
2933
3257
  itemKey,
2934
3258
  lastAccessAt,
@@ -2937,15 +3261,41 @@ function setupCollectionPersistence(config, options = {}) {
2937
3261
  });
2938
3262
  const filteredEntries = persistedEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
2939
3263
  const ignoredEntries = persistedEntries.filter(({ payload }) => shouldIgnoreItem(payload));
2940
- if (ignoredEntries.length > 0) {
2941
- await Promise.all(ignoredEntries.map(({ itemKey }) => namespace.remove(itemKey)));
2942
- for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
3264
+ const byteBudgetResult = idleContext === void 0 ? keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes) : await keepEntriesWithinByteBudgetDuringIdle(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes, idleContext);
3265
+ if (byteBudgetResult === null) return;
3266
+ const { keptKeys, unprotectedBytes } = byteBudgetResult;
3267
+ const ignoredItemKeys = new Set(ignoredEntries.map(({ itemKey }) => itemKey));
3268
+ const budgetEvictedItemKeys = new Set(filteredEntries.flatMap(({ itemKey }) => keptKeys.has(itemKey) ? [] : [itemKey]));
3269
+ const removalItemKeys = new Set([
3270
+ ...invalidEntries.map(({ itemKey }) => itemKey),
3271
+ ...ignoredItemKeys,
3272
+ ...budgetEvictedItemKeys
3273
+ ]);
3274
+ const removalEntries = metadataEntriesWithPayload.flatMap((entry) => removalItemKeys.has(entry.itemKey) ? [{
3275
+ key: entry.itemKey,
3276
+ lastAccessAt: entry.lastAccessAt,
3277
+ offlineProtected: protectedItemKeys.has(entry.itemKey)
3278
+ }] : []);
3279
+ const removalResult = idleContext === void 0 ? await (async () => {
3280
+ await namespace.commit({ removes: removalEntries.map(({ key }) => key) });
3281
+ return {
3282
+ completed: true,
3283
+ removedKeys: removalItemKeys,
3284
+ staleKeys: /* @__PURE__ */ new Set()
3285
+ };
3286
+ })() : await namespace.removeLocalEntriesIfUnchanged(removalEntries, idleContext);
3287
+ for (const itemKey of removalResult.removedKeys) if (ignoredItemKeys.has(itemKey) || budgetEvictedItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
3288
+ if (!removalResult.completed) {
3289
+ knownPersistedKeys = null;
3290
+ return;
3291
+ }
3292
+ if (removalResult.staleKeys.size > 0) {
3293
+ knownPersistedKeys = null;
3294
+ if (maintenanceManifestKey !== null) scheduleLocalStorageMaintenance([maintenanceManifestKey]);
3295
+ return;
2943
3296
  }
2944
- 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);
2945
- logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
2946
- await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2947
- for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2948
- knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
3297
+ knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => !removalResult.removedKeys.has(itemKey)).map(({ itemKey }) => itemKey));
3298
+ logByteBudgetCleanup("maintenance", filteredEntries.length, knownPersistedKeys, unprotectedBytes);
2949
3299
  return;
2950
3300
  }
2951
3301
  const metadataEntries = await listAllPersistentStorageNamespaceMetadata(namespace, { order: "lru-desc" });
@@ -3455,6 +3805,9 @@ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWin
3455
3805
  //#region src/utils/browserTabsSync.ts
3456
3806
  const PROTOCOL_VERSION = 1;
3457
3807
  const CHANNEL_PREFIX = "tsdf";
3808
+ function createBrowserTabsChannelName(storeType, storeKey, appVersion) {
3809
+ return `${CHANNEL_PREFIX}${appVersion === void 0 ? "" : `:app:${encodeURIComponent(appVersion)}`}:${storeType}:${storeKey}`;
3810
+ }
3458
3811
  const rawBrowserTabsMessageSchema = rc_object({
3459
3812
  protocolVersion: rc_number,
3460
3813
  messageId: rc_string,
@@ -3489,10 +3842,10 @@ function getDefaultTransportFactory() {
3489
3842
  };
3490
3843
  }
3491
3844
  /** @internal */
3492
- function createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, tabId = createBrowserTabsTabId()) {
3845
+ function createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, tabId = createBrowserTabsTabId(), appVersion) {
3493
3846
  const resolvedTransportFactory = transportFactory ?? getDefaultTransportFactory();
3494
3847
  const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3495
- const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3848
+ const channelName = createBrowserTabsChannelName(storeType, storeKey, appVersion);
3496
3849
  let seq = 0;
3497
3850
  const lastSeenSeqByTab = /* @__PURE__ */ new Map();
3498
3851
  let currentSessionKey;
@@ -3632,15 +3985,15 @@ function createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMess
3632
3985
  };
3633
3986
  }
3634
3987
  /** @internal */
3635
- function createBrowserTabsCoordinatorWithPriority(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, getWindowIsFocused, onWindowFocusChange, priorityTimings, tabId) {
3988
+ function createBrowserTabsCoordinatorWithPriority(storeType, storeKey, getSessionKey, onMessage, onSessionChange, transportFactory, debugLoggerInput, getWindowIsFocused, onWindowFocusChange, priorityTimings, tabId, appVersion) {
3636
3989
  const debugLogger = import.meta.env.DEV ? debugLoggerInput : void 0;
3637
- const channelName = `${CHANNEL_PREFIX}:${storeType}:${storeKey}`;
3990
+ const channelName = createBrowserTabsChannelName(storeType, storeKey, appVersion);
3638
3991
  const priorityRef = { current: null };
3639
3992
  const coordinator = createBrowserTabsCoordinator(storeType, storeKey, getSessionKey, onMessage, (sessionKey, previousSessionKey) => {
3640
3993
  priorityRef.current?.reset();
3641
3994
  if (sessionKey !== false && coordinator.enabled) priorityRef.current?.publishLocalStatus();
3642
3995
  onSessionChange?.(sessionKey, previousSessionKey);
3643
- }, transportFactory, debugLoggerInput, tabId);
3996
+ }, transportFactory, debugLoggerInput, tabId, appVersion);
3644
3997
  const priority = createBrowserTabsPriority(coordinator.enabled, () => coordinator.isSessionActive(), coordinator.tabId, getWindowIsFocused, onWindowFocusChange, (status) => {
3645
3998
  coordinator.publish(__LEGIT_CAST__(status));
3646
3999
  }, priorityTimings, import.meta.env.DEV ? (details) => {
@@ -3670,7 +4023,7 @@ function createBrowserTabsPresencePriority(options) {
3670
4023
  const priorityRef = { current: null };
3671
4024
  const { coordinator, priority } = createBrowserTabsCoordinatorWithPriority("presence", "manager", options.getSessionKey, (message) => {
3672
4025
  priorityRef.current?.onTabStatusMessage(message.tabId, message);
3673
- }, void 0, options.transportFactory, import.meta.env.DEV ? options.debugLogger : void 0, options.getWindowIsFocused, options.onWindowFocusChange, options.priorityTimings);
4026
+ }, void 0, options.transportFactory, import.meta.env.DEV ? options.debugLogger : void 0, options.getWindowIsFocused, options.onWindowFocusChange, options.priorityTimings, void 0, options.appVersion);
3674
4027
  priorityRef.current = priority;
3675
4028
  return {
3676
4029
  priority,
@@ -3772,6 +4125,7 @@ const defaultGetIsOffline = () => !navigator.onLine;
3772
4125
  const defaultStatusBySession = /* @__PURE__ */ new Map();
3773
4126
  const registry = /* @__PURE__ */ new Map();
3774
4127
  const uploadsConfigByOfflineSession = /* @__PURE__ */ new WeakMap();
4128
+ const appVersionByOfflineSession = /* @__PURE__ */ new WeakMap();
3775
4129
  const DEFAULT_UPLOAD_CONCURRENCY = 3;
3776
4130
  const OFFLINE_UPLOAD_RETENTION_MS = 10080 * 60 * 1e3;
3777
4131
  const OFFLINE_UPLOAD_RETENTION_STABLE_ONLINE_MS = 5e3;
@@ -4056,7 +4410,7 @@ var SessionOfflineCoordinator = class {
4056
4410
  return;
4057
4411
  }
4058
4412
  this.#applyRemoteSnapshot(message);
4059
- }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, void 0, void 0);
4413
+ }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, void 0, void 0, void 0, options.appVersion);
4060
4414
  this.#refreshLeadership();
4061
4415
  if (shouldBootstrapFromStorage) this.hydrate();
4062
4416
  if (this.#hasCanonicalConfig) this.#refreshNetworkConfig();
@@ -4948,6 +5302,7 @@ function getOrCreateSessionOfflineCoordinator(sessionKey, options = {}) {
4948
5302
  }
4949
5303
  const created = new SessionOfflineCoordinator({
4950
5304
  sessionKey,
5305
+ ...options.appVersion !== void 0 ? { appVersion: options.appVersion } : void 0,
4951
5306
  adapter: options.adapter,
4952
5307
  onPersistentStorageError: options.onPersistentStorageError,
4953
5308
  ...import.meta.env.DEV ? { debugLogger: options.debugLogger } : void 0,
@@ -4982,6 +5337,9 @@ function getGlobalOfflineResolutions(sessionKey) {
4982
5337
  function getOfflineSessionUploadsConfig(session) {
4983
5338
  return __LEGIT_CAST__(uploadsConfigByOfflineSession.get(eraseOfflineSession(session)));
4984
5339
  }
5340
+ function getOfflineSessionAppVersion(session) {
5341
+ return appVersionByOfflineSession.get(session);
5342
+ }
4985
5343
  function createOfflineSession(args) {
4986
5344
  const getSessionKey = args.getSessionKey ?? (() => false);
4987
5345
  const { config } = args;
@@ -5000,6 +5358,7 @@ function createOfflineSession(args) {
5000
5358
  if (sessionKey === false) return null;
5001
5359
  return getOrCreateSessionOfflineCoordinator(sessionKey, {
5002
5360
  config,
5361
+ ...args.appVersion !== void 0 ? { appVersion: args.appVersion } : void 0,
5003
5362
  ...import.meta.env.DEV ? { debugLogger: args.debugLogger } : void 0,
5004
5363
  uploads: eraseUploadsConfig(uploads),
5005
5364
  bootstrapStatusFromLocalStorage
@@ -5007,7 +5366,7 @@ function createOfflineSession(args) {
5007
5366
  }
5008
5367
  function useSessionCoordinator() {
5009
5368
  const activeSessionKey = getSessionKey();
5010
- return useConfiguredSessionOfflineCoordinator(activeSessionKey === false ? resolveOfflineSessionScope(false, inactiveScope) : activeSessionKey, activeSessionKey === false ? void 0 : config, eraseUploadsConfig(activeSessionKey === false ? void 0 : uploads), activeSessionKey !== false, import.meta.env.DEV ? args.debugLogger : void 0);
5369
+ return useConfiguredSessionOfflineCoordinator(activeSessionKey === false ? resolveOfflineSessionScope(false, inactiveScope) : activeSessionKey, activeSessionKey === false ? void 0 : config, eraseUploadsConfig(activeSessionKey === false ? void 0 : uploads), activeSessionKey !== false, import.meta.env.DEV ? args.debugLogger : void 0, args.appVersion);
5011
5370
  }
5012
5371
  const session = {
5013
5372
  getSessionKey,
@@ -5099,18 +5458,21 @@ function createOfflineSession(args) {
5099
5458
  }
5100
5459
  };
5101
5460
  uploadsConfigByOfflineSession.set(eraseOfflineSession(session), eraseUploadsConfig(uploads));
5461
+ appVersionByOfflineSession.set(eraseOfflineSession(session), args.appVersion);
5102
5462
  return session;
5103
5463
  }
5104
5464
  function useSessionOfflineCoordinator(sessionKey, bootstrapStatusFromLocalStorage = false) {
5105
5465
  return useMemo(() => registry.get(sessionKey) ?? getOrCreateSessionOfflineCoordinator(sessionKey, { bootstrapStatusFromLocalStorage }), [bootstrapStatusFromLocalStorage, sessionKey]);
5106
5466
  }
5107
- function useConfiguredSessionOfflineCoordinator(sessionKey, config, uploads, bootstrapStatusFromLocalStorage = false, debugLogger) {
5467
+ function useConfiguredSessionOfflineCoordinator(sessionKey, config, uploads, bootstrapStatusFromLocalStorage = false, debugLogger, appVersion) {
5108
5468
  return useMemo(() => getOrCreateSessionOfflineCoordinator(sessionKey, {
5109
5469
  config,
5470
+ ...appVersion !== void 0 ? { appVersion } : void 0,
5110
5471
  ...import.meta.env.DEV ? { debugLogger } : void 0,
5111
5472
  uploads,
5112
5473
  bootstrapStatusFromLocalStorage
5113
5474
  }), [
5475
+ appVersion,
5114
5476
  bootstrapStatusFromLocalStorage,
5115
5477
  config,
5116
5478
  debugLogger,
@@ -5357,6 +5719,7 @@ function initializeOfflineStoreController(controller) {
5357
5719
  }
5358
5720
  function createOfflineStoreController(storeName, storeType, getSessionKey, onPersistentStorageError, debugLogger, adapter, storeAdapter, offlineSession, operations) {
5359
5721
  const sessionConfig = offlineSession.getConfig();
5722
+ const appVersion = getOfflineSessionAppVersion(offlineSession);
5360
5723
  const activeDebugLogger = import.meta.env.DEV ? debugLogger : void 0;
5361
5724
  const replayQueue = createAsyncQueue({
5362
5725
  concurrency: 1,
@@ -5483,6 +5846,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
5483
5846
  if (activeSession?.sessionKey === targetSessionKey) return activeSession;
5484
5847
  teardownActiveSession();
5485
5848
  const session = getOrCreateSessionOfflineCoordinator(targetSessionKey, {
5849
+ ...appVersion !== void 0 ? { appVersion } : void 0,
5486
5850
  adapter,
5487
5851
  onPersistentStorageError,
5488
5852
  ...import.meta.env.DEV ? { debugLogger: activeDebugLogger } : void 0,
@@ -5888,9 +6252,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
5888
6252
  syncEntityNamespace(sessionState, entities);
5889
6253
  }
5890
6254
  async function syncEntityNamespace(current, entities) {
5891
- const existingKeys = await current.entityNamespace.listKeys();
5892
- const nextKeys = new Set(entities.map((entity) => entity.entityKey));
5893
- await Promise.all([...entities.map((entity) => current.entityNamespace.save(entity.entityKey, entity)), ...existingKeys.filter((key) => !nextKeys.has(key)).map((key) => current.entityNamespace.remove(key))]);
6255
+ await current.entityNamespace.replaceAll(entities.map((entity) => ({
6256
+ data: entity,
6257
+ key: entity.entityKey
6258
+ })));
5894
6259
  }
5895
6260
  function getSortedEntries() {
5896
6261
  return [...queueEntries.values()].sort(compareQueueEntries);
@@ -7865,13 +8230,15 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
7865
8230
  };
7866
8231
  }
7867
8232
  function createStoreManager(options) {
8233
+ const appVersion = options.getAppVersion?.();
7868
8234
  const debugLogger = import.meta.env.DEV ? resolveTSDFLogger(options.debugLogger) : void 0;
7869
8235
  const logger = resolveTSDFLogger(options.logger ?? true);
7870
8236
  let resolvedOfflineSession;
7871
8237
  if (options.offlineSession) {
7872
8238
  const createOfflineSessionOptions = {
7873
8239
  config: options.offlineSession,
7874
- getSessionKey: options.getSessionKey
8240
+ getSessionKey: options.getSessionKey,
8241
+ ...appVersion !== void 0 ? { appVersion } : void 0
7875
8242
  };
7876
8243
  if (debugLogger !== void 0) createOfflineSessionOptions.debugLogger = debugLogger;
7877
8244
  resolvedOfflineSession = createOfflineSession(createOfflineSessionOptions);
@@ -7901,6 +8268,7 @@ function createStoreManager(options) {
7901
8268
  useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
7902
8269
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
7903
8270
  const registry = {
8271
+ appVersion,
7904
8272
  browserTabsPresence: void 0,
7905
8273
  nextStoreRegistrationId: 0,
7906
8274
  stores: /* @__PURE__ */ new Map()
@@ -7961,10 +8329,14 @@ function registerStoreWithManager(storeManager, store) {
7961
8329
  }
7962
8330
  };
7963
8331
  }
8332
+ function getStoreManagerAppVersion(storeManager) {
8333
+ return getRegistryOrThrow(storeManager).appVersion;
8334
+ }
7964
8335
  function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
7965
8336
  const registry = getRegistryOrThrow(storeManager);
7966
8337
  const presence = registry.browserTabsPresence ??= createBrowserTabsPresencePriority({
7967
8338
  getSessionKey: storeManager.getSessionKey,
8339
+ ...registry.appVersion !== void 0 ? { appVersion: registry.appVersion } : void 0,
7968
8340
  getWindowIsFocused: options.getWindowIsFocused,
7969
8341
  onWindowFocusChange: options.onWindowFocusChange,
7970
8342
  transportFactory: options.transportFactory,
@@ -9206,7 +9578,7 @@ function createCollectionStore(storeOptions) {
9206
9578
  const browserTabsSync = createBrowserTabsCoordinator("collection", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
9207
9579
  lastCollectionSyncVersions.clear();
9208
9580
  clearOfflineOverlays();
9209
- }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
9581
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId, getStoreManagerAppVersion(storeManager));
9210
9582
  async function executeBatchFetch$1(requests, fetchCtx, batchKey) {
9211
9583
  const results = await executeBatchFetch(requests, fetchCtx, store, fetchFn, batchFetchFn, errorNormalizer, batchKey, offlineController);
9212
9584
  const successfulRequests = requests.filter(({ requestId }) => results.get(requestId) === true);
@@ -10079,7 +10451,7 @@ function createDocumentStore(storeOptions) {
10079
10451
  const browserTabsSync = createBrowserTabsCoordinator("document", id, getSessionKeyForRuntime, handleRemoteMessage, () => {
10080
10452
  lastDocumentSyncVersion = void 0;
10081
10453
  clearOfflineOverlay();
10082
- }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
10454
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId, getStoreManagerAppVersion(storeManager));
10083
10455
  async function executeFetch(fetchCtx) {
10084
10456
  const currentStatus = store.state.status;
10085
10457
  const wasLoadedBeforeFetch = currentStatus === "success";
@@ -10511,6 +10883,7 @@ function createDocumentStore(storeOptions) {
10511
10883
  //#region src/persistentStorage/listQueryStorePersistence.ts
10512
10884
  const DEFAULT_MAX_QUERY_SIZE = 100;
10513
10885
  const SAVE_DEBOUNCE_MS = 1e3;
10886
+ const MAINTENANCE_SCAN_CHUNK_SIZE = 25;
10514
10887
  function toItemState(persisted, dataSchema, shouldIgnoreItem) {
10515
10888
  const validated = parsePersistedStoreData(persisted.data, dataSchema);
10516
10889
  if (validated === null) return null;
@@ -10718,6 +11091,7 @@ function setupListQueryPersistence(config, options = {}) {
10718
11091
  let knownPersistedItemKeys = null;
10719
11092
  let knownPersistedQueryKeys = null;
10720
11093
  let maintenanceCallbackKey = null;
11094
+ const pendingLocalQueryReconciliationSessions = /* @__PURE__ */ new Set();
10721
11095
  function isOfflineNetworkActive() {
10722
11096
  return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig().network);
10723
11097
  }
@@ -10742,6 +11116,18 @@ function setupListQueryPersistence(config, options = {}) {
10742
11116
  if (prefix === false) return false;
10743
11117
  return `${prefix}${queryKey}`;
10744
11118
  }
11119
+ function getLocalStorageMaintenanceScope() {
11120
+ const sessionKey = config.getSessionKey();
11121
+ if (sessionKey === false) return null;
11122
+ return {
11123
+ sessionKey,
11124
+ itemPrefix: getStoragePrefixForStoreNamespace(sessionKey, config.storeName, "li"),
11125
+ queryPrefix: getStoragePrefixForStoreNamespace(sessionKey, config.storeName, "lq")
11126
+ };
11127
+ }
11128
+ function isLocalStorageMaintenanceScopeCurrent(scope) {
11129
+ return config.getSessionKey() === scope.sessionKey;
11130
+ }
10745
11131
  function getLocalStorageItemEntrySizeBytes(value) {
10746
11132
  return serializeJsonForStorage(createCompactLocalStorageEntry({
10747
11133
  d: value.data,
@@ -10749,14 +11135,15 @@ function setupListQueryPersistence(config, options = {}) {
10749
11135
  ...value.loadedFields !== void 0 ? { lf: value.loadedFields } : {}
10750
11136
  }, version)).sizeBytes;
10751
11137
  }
10752
- function readLocalStorageQueryEntry(queryKey) {
11138
+ function readLocalStorageQueryEntry(queryKey, knownStorageKey) {
10753
11139
  if (localStorageAdapter === null) return void 0;
10754
- const storageKey = getLocalStorageQueryStorageKey(queryKey);
11140
+ const storageKey = knownStorageKey ?? getLocalStorageQueryStorageKey(queryKey);
10755
11141
  if (storageKey === false) return void 0;
10756
11142
  const rawEntry = localStorageAdapter.readRaw(storageKey);
11143
+ if (rawEntry === null) return void 0;
10757
11144
  const entry = parseCompactListQueryLocalStorageEntry(rawEntry);
10758
11145
  if (entry === null || entry.version !== version) return;
10759
- const sizeBytes = rawEntry === null ? 0 : rememberQueryMetadataSize(queryKey, getSerializedStringSize(rawEntry));
11146
+ const sizeBytes = rememberQueryMetadataSize(queryKey, getSerializedStringSize(rawEntry));
10760
11147
  return {
10761
11148
  queryKey,
10762
11149
  payload: entry.payload,
@@ -10764,6 +11151,7 @@ function setupListQueryPersistence(config, options = {}) {
10764
11151
  hasMore: entry.hasMore,
10765
11152
  lastAccessAt: entry.lastAccessAt,
10766
11153
  offlineProtected: entry.offlineProtected,
11154
+ rawValue: rawEntry,
10767
11155
  sizeBytes
10768
11156
  };
10769
11157
  }
@@ -10772,22 +11160,58 @@ function setupListQueryPersistence(config, options = {}) {
10772
11160
  const queryPrefix = getQueryPrefix();
10773
11161
  if (queryPrefix === false) return null;
10774
11162
  const entriesByKey = /* @__PURE__ */ new Map();
10775
- const invalidQueryKeys = [];
11163
+ const invalidQueryEntries = [];
10776
11164
  for (const storageKey of localStorageAdapter.listRawKeys(queryPrefix)) {
10777
11165
  const queryKey = storageKey.slice(queryPrefix.length);
10778
11166
  const entry = readLocalStorageQueryEntry(queryKey);
10779
11167
  if (!entry) {
10780
- invalidQueryKeys.push(queryKey);
11168
+ invalidQueryEntries.push({
11169
+ queryKey,
11170
+ rawValue: localStorageAdapter.readRaw(storageKey)
11171
+ });
10781
11172
  continue;
10782
11173
  }
10783
11174
  entriesByKey.set(queryKey, entry);
10784
11175
  }
10785
11176
  return {
10786
11177
  entriesByKey,
10787
- invalidQueryKeys
11178
+ invalidQueryEntries
11179
+ };
11180
+ }
11181
+ async function scanLocalStorageQueryEntriesDuringMaintenance(idleContext, scope) {
11182
+ if (localStorageAdapter === null) return null;
11183
+ if (!isLocalStorageMaintenanceScopeCurrent(scope)) return null;
11184
+ const storageKeys = await localStorageAdapter.runMaintenanceLocked(idleContext, () => localStorageAdapter.listRawKeys(scope.queryPrefix));
11185
+ const entriesByKey = /* @__PURE__ */ new Map();
11186
+ const invalidQueryEntries = [];
11187
+ let storageKeyIndex = 0;
11188
+ while (storageKeyIndex < storageKeys.length) {
11189
+ if (!await idleContext.yieldIfNeeded()) return null;
11190
+ if (!isLocalStorageMaintenanceScopeCurrent(scope)) return null;
11191
+ await localStorageAdapter.runMaintenanceLocked(idleContext, () => {
11192
+ let processedCount = 0;
11193
+ while (storageKeyIndex < storageKeys.length) {
11194
+ if (processedCount > 0 && idleContext.shouldYield()) break;
11195
+ const storageKey = storageKeys[storageKeyIndex];
11196
+ storageKeyIndex++;
11197
+ processedCount++;
11198
+ if (storageKey === void 0) continue;
11199
+ const queryKey = storageKey.slice(scope.queryPrefix.length);
11200
+ const entry = readLocalStorageQueryEntry(queryKey, storageKey);
11201
+ if (entry === void 0) invalidQueryEntries.push({
11202
+ queryKey,
11203
+ rawValue: localStorageAdapter.readRaw(storageKey)
11204
+ });
11205
+ else entriesByKey.set(queryKey, entry);
11206
+ }
11207
+ });
11208
+ }
11209
+ return {
11210
+ entriesByKey,
11211
+ invalidQueryEntries
10788
11212
  };
10789
11213
  }
10790
- async function saveLocalStorageQueryEntry(queryKey, data) {
11214
+ async function saveLocalStorageQueryEntry(queryKey, data, idleContext) {
10791
11215
  if (localStorageAdapter === null) {
10792
11216
  await queryNamespace.save(queryKey, data);
10793
11217
  return;
@@ -10797,24 +11221,42 @@ function setupListQueryPersistence(config, options = {}) {
10797
11221
  if (sessionKey === false || storageKey === false) return;
10798
11222
  const timestamp = Date.now();
10799
11223
  try {
10800
- await localStorageAdapter.runLocked(() => {
10801
- const offlineProtected = mergeLocalStorageOfflineProtection(sessionKey, storageKey, parseCompactListQueryLocalStorageEntry(localStorageAdapter.readRaw(storageKey))?.offlineProtected === true);
10802
- const { sizeBytes } = localStorageAdapter.write(storageKey, createCompactListQueryLocalStorageEntry({
10803
- lastAccessAt: timestamp,
10804
- offlineProtected,
10805
- payload: data.payload,
10806
- items: data.items,
10807
- hasMore: data.hasMore,
10808
- version
10809
- }));
10810
- rememberQueryMetadataSize(queryKey, sizeBytes);
10811
- recordLocalStorageTouch(storageKey, timestamp);
11224
+ const saveEntry = () => writeLocalStorageQueryEntry(sessionKey, storageKey, queryKey, data, timestamp);
11225
+ await (idleContext === void 0 ? localStorageAdapter.runLocked(saveEntry) : localStorageAdapter.runMaintenanceLocked(idleContext, saveEntry));
11226
+ } catch (error) {
11227
+ config.onPersistentStorageError?.(error);
11228
+ }
11229
+ }
11230
+ function writeLocalStorageQueryEntry(sessionKey, storageKey, queryKey, data, timestamp) {
11231
+ if (localStorageAdapter === null) return;
11232
+ const offlineProtected = mergeLocalStorageOfflineProtection(sessionKey, storageKey, parseCompactListQueryLocalStorageEntry(localStorageAdapter.readRaw(storageKey))?.offlineProtected === true);
11233
+ const { sizeBytes } = localStorageAdapter.write(storageKey, createCompactListQueryLocalStorageEntry({
11234
+ lastAccessAt: timestamp,
11235
+ offlineProtected,
11236
+ payload: data.payload,
11237
+ items: data.items,
11238
+ hasMore: data.hasMore,
11239
+ version
11240
+ }));
11241
+ rememberQueryMetadataSize(queryKey, sizeBytes);
11242
+ recordLocalStorageTouch(storageKey, timestamp);
11243
+ }
11244
+ async function saveLocalStorageQueryEntryIfUnchanged(queryData, data, idleContext, scope) {
11245
+ if (localStorageAdapter === null || !isLocalStorageMaintenanceScopeCurrent(scope)) return false;
11246
+ const storageKey = `${scope.queryPrefix}${queryData.queryKey}`;
11247
+ try {
11248
+ return await localStorageAdapter.runMaintenanceLocked(idleContext, () => {
11249
+ if (!isLocalStorageMaintenanceScopeCurrent(scope)) return false;
11250
+ if (localStorageAdapter.readRaw(storageKey) !== queryData.rawValue) return false;
11251
+ writeLocalStorageQueryEntry(scope.sessionKey, storageKey, queryData.queryKey, data, Date.now());
11252
+ return true;
10812
11253
  });
10813
11254
  } catch (error) {
10814
11255
  config.onPersistentStorageError?.(error);
11256
+ return false;
10815
11257
  }
10816
11258
  }
10817
- async function removeLocalStorageQueryEntry(queryKey) {
11259
+ async function removeLocalStorageQueryEntry(queryKey, idleContext) {
10818
11260
  if (localStorageAdapter === null) {
10819
11261
  await queryNamespace.remove(queryKey);
10820
11262
  return;
@@ -10822,13 +11264,57 @@ function setupListQueryPersistence(config, options = {}) {
10822
11264
  const storageKey = getLocalStorageQueryStorageKey(queryKey);
10823
11265
  if (storageKey === false) return;
10824
11266
  try {
10825
- await localStorageAdapter.runLocked(() => {
10826
- localStorageAdapter.remove(storageKey);
10827
- });
11267
+ const removeEntry = () => localStorageAdapter.remove(storageKey);
11268
+ await (idleContext === void 0 ? localStorageAdapter.runLocked(removeEntry) : localStorageAdapter.runMaintenanceLocked(idleContext, removeEntry));
10828
11269
  } catch (error) {
10829
11270
  config.onPersistentStorageError?.(error);
10830
11271
  }
10831
11272
  }
11273
+ async function removeLocalStorageQueriesIfUnchanged(candidates, idleContext, scope) {
11274
+ const removedQueryKeys = /* @__PURE__ */ new Set();
11275
+ const staleQueryKeys = /* @__PURE__ */ new Set();
11276
+ if (localStorageAdapter === null) return {
11277
+ completed: false,
11278
+ removedQueryKeys,
11279
+ staleQueryKeys
11280
+ };
11281
+ let candidateIndex = 0;
11282
+ while (candidateIndex < candidates.length) {
11283
+ if (!await idleContext.yieldIfNeeded()) return {
11284
+ completed: false,
11285
+ removedQueryKeys,
11286
+ staleQueryKeys
11287
+ };
11288
+ if (!isLocalStorageMaintenanceScopeCurrent(scope)) return {
11289
+ completed: false,
11290
+ removedQueryKeys,
11291
+ staleQueryKeys
11292
+ };
11293
+ await localStorageAdapter.runMaintenanceLocked(idleContext, () => {
11294
+ let processedCount = 0;
11295
+ while (candidateIndex < candidates.length) {
11296
+ if (processedCount > 0 && idleContext.shouldYield()) break;
11297
+ const candidate = candidates[candidateIndex];
11298
+ candidateIndex++;
11299
+ processedCount++;
11300
+ if (candidate === void 0) continue;
11301
+ if (!isLocalStorageMaintenanceScopeCurrent(scope)) break;
11302
+ const storageKey = `${scope.queryPrefix}${candidate.queryKey}`;
11303
+ if (localStorageAdapter.readRaw(storageKey) !== candidate.rawValue) {
11304
+ staleQueryKeys.add(candidate.queryKey);
11305
+ continue;
11306
+ }
11307
+ localStorageAdapter.remove(storageKey);
11308
+ removedQueryKeys.add(candidate.queryKey);
11309
+ }
11310
+ });
11311
+ }
11312
+ return {
11313
+ completed: true,
11314
+ removedQueryKeys,
11315
+ staleQueryKeys
11316
+ };
11317
+ }
10832
11318
  async function clearLocalStorageQueries() {
10833
11319
  if (localStorageAdapter === null) {
10834
11320
  await queryNamespace.clear();
@@ -10863,9 +11349,17 @@ function setupListQueryPersistence(config, options = {}) {
10863
11349
  return true;
10864
11350
  });
10865
11351
  }
10866
- async function runMaintenance() {
10867
- const { keptQueryKeys, managedQueryEntriesByKey } = await evictStoredQueries();
10868
- await evictStoredItems(keptQueryKeys, managedQueryEntriesByKey);
11352
+ async function runMaintenance(idleContext) {
11353
+ const localMaintenanceScope = localStorageAdapter !== null && idleContext !== void 0 ? getLocalStorageMaintenanceScope() : void 0;
11354
+ if (localMaintenanceScope === null) return;
11355
+ const { completed, keptQueryKeys, managedQueryEntriesByKey } = await evictStoredQueries(idleContext, localMaintenanceScope);
11356
+ if (!completed || idleContext?.isCanceled()) return;
11357
+ if (localMaintenanceScope !== void 0 && !isLocalStorageMaintenanceScopeCurrent(localMaintenanceScope)) {
11358
+ knownPersistedItemKeys = null;
11359
+ knownPersistedQueryKeys = null;
11360
+ return;
11361
+ }
11362
+ await evictStoredItems(keptQueryKeys, managedQueryEntriesByKey, idleContext, localMaintenanceScope);
10869
11363
  }
10870
11364
  async function planAsyncStartupCleanup(args) {
10871
11365
  const discoveredItemScope = args.discoveredScopes.find(({ scope }) => scope.kind === "listQuery.item");
@@ -11439,32 +11933,38 @@ function setupListQueryPersistence(config, options = {}) {
11439
11933
  async function maybeHydrateQueries(queryKeys) {
11440
11934
  return Promise.all(queryKeys.map((queryKey) => preloadQuery(queryKey)));
11441
11935
  }
11442
- async function evictStoredQueries() {
11936
+ async function evictStoredQueries(idleContext, localMaintenanceScope) {
11443
11937
  syncMaintenanceRegistration();
11444
- const scannedQueryEntries = localStorageAdapter !== null ? scanLocalStorageQueryEntries() : null;
11938
+ const scannedQueryEntries = localStorageAdapter === null ? null : idleContext === void 0 ? await localStorageAdapter.runLocked(scanLocalStorageQueryEntries) : localMaintenanceScope === void 0 ? null : await scanLocalStorageQueryEntriesDuringMaintenance(idleContext, localMaintenanceScope);
11445
11939
  const managedQueryEntriesByKey = scannedQueryEntries?.entriesByKey ?? null;
11940
+ if (localStorageAdapter !== null && idleContext !== void 0 && scannedQueryEntries === null) {
11941
+ knownPersistedQueryKeys = null;
11942
+ return {
11943
+ completed: false,
11944
+ keptQueryKeys: /* @__PURE__ */ new Set(),
11945
+ managedQueryEntriesByKey
11946
+ };
11947
+ }
11446
11948
  if (localStorageAdapter !== null && scannedQueryEntries !== null) {
11447
11949
  const managedQueryEntries = scannedQueryEntries.entriesByKey;
11448
- const invalidQueryKeys = scannedQueryEntries.invalidQueryKeys;
11449
11950
  const skipOfflineExpirationMaintenance = isOfflineNetworkActive();
11450
- const expiredQueryKeys = filterAndMap([...managedQueryEntries.values()], ({ queryKey, lastAccessAt, offlineProtected }) => {
11951
+ const expiredQueryKeys = new Set(filterAndMap([...managedQueryEntries.values()], ({ queryKey, lastAccessAt, offlineProtected }) => {
11451
11952
  if (skipOfflineExpirationMaintenance) return false;
11452
11953
  if (offlineProtected) return false;
11453
- return Date.now() - lastAccessAt > getLocalStorageMaxAgeMs() ? { queryKey } : false;
11454
- });
11455
- if (invalidQueryKeys.length > 0) await Promise.all(invalidQueryKeys.map((queryKey) => removeLocalStorageQueryEntry(queryKey)));
11456
- if (expiredQueryKeys.length > 0) {
11457
- await Promise.all(expiredQueryKeys.map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11458
- for (const { queryKey } of expiredQueryKeys) managedQueryEntries.delete(queryKey);
11459
- }
11460
- const invalidPayloadQueryKeys = [];
11461
- const filteredEntries = filterAndMap([...managedQueryEntries.values()], (entry) => {
11954
+ return Date.now() - lastAccessAt > getLocalStorageMaxAgeMs() ? queryKey : false;
11955
+ }));
11956
+ const invalidPayloadQueryKeys = /* @__PURE__ */ new Set();
11957
+ const filteredEntries = [];
11958
+ for (const [entryIndex, entry] of [...managedQueryEntries.values()].entries()) {
11959
+ if (idleContext !== void 0 && entryIndex % MAINTENANCE_SCAN_CHUNK_SIZE === 0 && !await idleContext.yieldIfNeeded()) return {
11960
+ completed: false,
11961
+ keptQueryKeys: /* @__PURE__ */ new Set(),
11962
+ managedQueryEntriesByKey
11963
+ };
11964
+ if (expiredQueryKeys.has(entry.queryKey)) continue;
11462
11965
  const payload = validateWithSchema(config.queryPayloadSchema, entry.payload);
11463
- if (payload === null) {
11464
- invalidPayloadQueryKeys.push(entry.queryKey);
11465
- return false;
11466
- }
11467
- return {
11966
+ if (payload === null) invalidPayloadQueryKeys.add(entry.queryKey);
11967
+ else filteredEntries.push({
11468
11968
  queryKey: entry.queryKey,
11469
11969
  payload,
11470
11970
  items: entry.items,
@@ -11472,18 +11972,61 @@ function setupListQueryPersistence(config, options = {}) {
11472
11972
  lastAccessAt: entry.lastAccessAt,
11473
11973
  offlineProtected: entry.offlineProtected,
11474
11974
  sizeBytes: entry.sizeBytes
11975
+ });
11976
+ }
11977
+ const queryByteBudgetResult = idleContext === void 0 ? keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes) : await keepEntriesWithinByteBudgetDuringIdle(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes, idleContext);
11978
+ if (queryByteBudgetResult === null) return {
11979
+ completed: false,
11980
+ keptQueryKeys: /* @__PURE__ */ new Set(),
11981
+ managedQueryEntriesByKey
11982
+ };
11983
+ const { keptKeys: plannedKeptQueryKeys, unprotectedBytes } = queryByteBudgetResult;
11984
+ const plannedBudgetEvictedQueryKeys = new Set(filteredEntries.flatMap(({ queryKey }) => plannedKeptQueryKeys.has(queryKey) ? [] : [queryKey]));
11985
+ const plannedRemovalQueryKeys = new Set([
11986
+ ...expiredQueryKeys,
11987
+ ...invalidPayloadQueryKeys,
11988
+ ...plannedBudgetEvictedQueryKeys
11989
+ ]);
11990
+ const removalCandidates = [...scannedQueryEntries.invalidQueryEntries, ...[...managedQueryEntries.values()].flatMap((entry) => plannedRemovalQueryKeys.has(entry.queryKey) ? [{
11991
+ queryKey: entry.queryKey,
11992
+ rawValue: entry.rawValue
11993
+ }] : [])];
11994
+ const removalResult = idleContext === void 0 ? await (async () => {
11995
+ await Promise.all(removalCandidates.map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11996
+ return {
11997
+ completed: true,
11998
+ removedQueryKeys: new Set(removalCandidates.map(({ queryKey }) => queryKey)),
11999
+ staleQueryKeys: /* @__PURE__ */ new Set()
11475
12000
  };
11476
- });
11477
- if (invalidPayloadQueryKeys.length > 0) await Promise.all(invalidPayloadQueryKeys.map((queryKey) => removeLocalStorageQueryEntry(queryKey)));
11478
- const { keptKeys: keptQueryKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11479
- logQueryByteBudgetCleanup("maintenance", filteredEntries.length, keptQueryKeys, unprotectedBytes);
11480
- await Promise.all(filteredEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11481
- for (const { queryKey, lastAccessAt } of filteredEntries) if (!keptQueryKeys.has(queryKey)) {
12001
+ })() : localMaintenanceScope === void 0 ? {
12002
+ completed: false,
12003
+ removedQueryKeys: /* @__PURE__ */ new Set(),
12004
+ staleQueryKeys: /* @__PURE__ */ new Set()
12005
+ } : await removeLocalStorageQueriesIfUnchanged(removalCandidates, idleContext, localMaintenanceScope);
12006
+ for (const { queryKey, lastAccessAt } of filteredEntries) if (removalResult.removedQueryKeys.has(queryKey) && plannedBudgetEvictedQueryKeys.has(queryKey)) {
11482
12007
  rememberBudgetEvictedEntry(budgetEvictedQueryRecency, queryKey, lastAccessAt, querySnapshotByKey.get(queryKey), storeRef !== null && Object.hasOwn(storeRef.state.queries, queryKey));
11483
12008
  forgetPersistedQuery(queryKey);
11484
12009
  }
11485
- knownPersistedQueryKeys = keptQueryKeys;
12010
+ for (const queryKey of removalResult.removedQueryKeys) managedQueryEntries.delete(queryKey);
12011
+ if (!removalResult.completed) {
12012
+ knownPersistedQueryKeys = null;
12013
+ return {
12014
+ completed: false,
12015
+ keptQueryKeys: /* @__PURE__ */ new Set(),
12016
+ managedQueryEntriesByKey
12017
+ };
12018
+ }
12019
+ const keptQueryKeys = new Set(filteredEntries.flatMap(({ queryKey }) => removalResult.removedQueryKeys.has(queryKey) ? [] : [queryKey]));
12020
+ knownPersistedQueryKeys = removalResult.staleQueryKeys.size > 0 ? null : keptQueryKeys;
12021
+ if (removalResult.staleQueryKeys.size > 0 && maintenanceCallbackKey !== null) scheduleLocalStorageMaintenance([maintenanceCallbackKey]);
12022
+ if (removalResult.staleQueryKeys.size > 0) return {
12023
+ completed: false,
12024
+ keptQueryKeys,
12025
+ managedQueryEntriesByKey
12026
+ };
12027
+ if (removalResult.staleQueryKeys.size === 0) logQueryByteBudgetCleanup("maintenance", filteredEntries.length, keptQueryKeys, unprotectedBytes);
11486
12028
  return {
12029
+ completed: true,
11487
12030
  keptQueryKeys,
11488
12031
  managedQueryEntriesByKey
11489
12032
  };
@@ -11515,25 +12058,40 @@ function setupListQueryPersistence(config, options = {}) {
11515
12058
  }
11516
12059
  knownPersistedQueryKeys = keptQueryKeys;
11517
12060
  return {
12061
+ completed: true,
11518
12062
  keptQueryKeys,
11519
12063
  managedQueryEntriesByKey: null
11520
12064
  };
11521
12065
  }
11522
- async function evictStoredItems(keptQueryKeys, managedQueryEntriesByKey) {
12066
+ async function evictStoredItems(keptQueryKeys, managedQueryEntriesByKey, idleContext, localMaintenanceScope) {
11523
12067
  syncMaintenanceRegistration();
11524
- const sessionKey = config.getSessionKey();
11525
- const itemPrefix = sessionKey === false ? null : getStoragePrefixForStoreNamespace(sessionKey, config.storeName, "li");
12068
+ if (localMaintenanceScope !== void 0 && !isLocalStorageMaintenanceScopeCurrent(localMaintenanceScope)) {
12069
+ knownPersistedItemKeys = null;
12070
+ knownPersistedQueryKeys = null;
12071
+ return;
12072
+ }
12073
+ const sessionKey = localMaintenanceScope?.sessionKey ?? config.getSessionKey();
12074
+ const itemPrefix = localMaintenanceScope?.itemPrefix ?? (sessionKey === false ? null : getStoragePrefixForStoreNamespace(sessionKey, config.storeName, "li"));
11526
12075
  if (localStorageAdapter !== null && itemPrefix !== null) {
11527
- const metadataEntries = localStorageAdapter.listManifestEntries(itemPrefix);
11528
- const protectedItemKeys = new Set(metadataEntries.flatMap((entry) => isManagedLocalStorageEntryOfflineProtected(entry.meta) ? [entry.entryKey] : []));
11529
- const metadataEntriesWithPayload = metadataEntries.map((entry) => ({
11530
- itemKey: entry.entryKey,
11531
- lastAccessAt: entry.lastAccessAt,
11532
- sizeBytes: rememberItemMetadataSize(entry.entryKey, entry.sizeBytes),
11533
- payload: validateWithSchema(config.itemPayloadSchema, readManifestPayloadMeta(entry.meta))
11534
- }));
12076
+ const metadataEntries = await (idleContext === void 0 ? localStorageAdapter.runLocked(() => localStorageAdapter.listManifestEntries(itemPrefix)) : localStorageAdapter.runMaintenanceLocked(idleContext, () => localStorageAdapter.listManifestEntries(itemPrefix)));
12077
+ const protectedItemKeys = /* @__PURE__ */ new Set();
12078
+ const metadataEntriesWithPayload = [];
12079
+ for (const [entryIndex, entry] of metadataEntries.entries()) {
12080
+ if (idleContext !== void 0 && entryIndex % MAINTENANCE_SCAN_CHUNK_SIZE === 0 && !await idleContext.yieldIfNeeded()) return;
12081
+ if (localMaintenanceScope !== void 0 && !isLocalStorageMaintenanceScopeCurrent(localMaintenanceScope)) {
12082
+ knownPersistedItemKeys = null;
12083
+ knownPersistedQueryKeys = null;
12084
+ return;
12085
+ }
12086
+ if (isManagedLocalStorageEntryOfflineProtected(entry.meta)) protectedItemKeys.add(entry.entryKey);
12087
+ metadataEntriesWithPayload.push({
12088
+ itemKey: entry.entryKey,
12089
+ lastAccessAt: entry.lastAccessAt,
12090
+ sizeBytes: rememberItemMetadataSize(entry.entryKey, entry.sizeBytes),
12091
+ payload: validateWithSchema(config.itemPayloadSchema, readManifestPayloadMeta(entry.meta))
12092
+ });
12093
+ }
11535
12094
  const invalidItemEntries = filterAndMap(metadataEntriesWithPayload, ({ itemKey, payload }) => payload === null ? { itemKey } : false);
11536
- if (invalidItemEntries.length > 0) await Promise.all(invalidItemEntries.map(({ itemKey }) => itemNamespace.remove(itemKey)));
11537
12095
  const hydratedItemEntries = filterAndMap(metadataEntriesWithPayload, ({ itemKey, lastAccessAt, payload, sizeBytes }) => payload === null ? false : {
11538
12096
  itemKey,
11539
12097
  lastAccessAt,
@@ -11541,26 +12099,61 @@ function setupListQueryPersistence(config, options = {}) {
11541
12099
  sizeBytes
11542
12100
  });
11543
12101
  const ignoredItemEntries = hydratedItemEntries.filter(({ payload }) => shouldIgnoreItem(payload));
11544
- if (ignoredItemEntries.length > 0) {
11545
- await Promise.all(ignoredItemEntries.map(({ itemKey }) => itemNamespace.remove(itemKey)));
11546
- for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11547
- }
11548
12102
  const persistedItemEntries = hydratedItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11549
- 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);
11550
- logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11551
- const evictedItemKeys = /* @__PURE__ */ new Set();
11552
- await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11553
- evictedItemKeys.add(itemKey);
11554
- return itemNamespace.remove(itemKey);
11555
- }));
11556
- for (const { itemKey, lastAccessAt } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) {
12103
+ const itemByteBudgetResult = idleContext === void 0 ? keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes) : await keepEntriesWithinByteBudgetDuringIdle(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes, idleContext);
12104
+ if (itemByteBudgetResult === null) return;
12105
+ if (localMaintenanceScope !== void 0 && !isLocalStorageMaintenanceScopeCurrent(localMaintenanceScope)) {
12106
+ knownPersistedItemKeys = null;
12107
+ knownPersistedQueryKeys = null;
12108
+ return;
12109
+ }
12110
+ const { keptKeys: plannedKeptItemKeys, unprotectedBytes } = itemByteBudgetResult;
12111
+ const ignoredItemKeys = new Set(ignoredItemEntries.map(({ itemKey }) => itemKey));
12112
+ const plannedBudgetEvictedItemKeys = new Set(persistedItemEntries.flatMap(({ itemKey }) => plannedKeptItemKeys.has(itemKey) ? [] : [itemKey]));
12113
+ const removalItemKeys = new Set([
12114
+ ...invalidItemEntries.map(({ itemKey }) => itemKey),
12115
+ ...ignoredItemKeys,
12116
+ ...plannedBudgetEvictedItemKeys
12117
+ ]);
12118
+ const removalEntries = metadataEntriesWithPayload.flatMap((entry) => removalItemKeys.has(entry.itemKey) ? [{
12119
+ key: entry.itemKey,
12120
+ lastAccessAt: entry.lastAccessAt,
12121
+ offlineProtected: protectedItemKeys.has(entry.itemKey)
12122
+ }] : []);
12123
+ const removalResult = idleContext === void 0 ? await (async () => {
12124
+ await itemNamespace.commit({ removes: removalEntries.map(({ key }) => key) });
12125
+ return {
12126
+ completed: true,
12127
+ removedKeys: removalItemKeys,
12128
+ staleKeys: /* @__PURE__ */ new Set()
12129
+ };
12130
+ })() : await itemNamespace.removeLocalEntriesIfUnchanged(removalEntries, idleContext, localMaintenanceScope === void 0 ? void 0 : () => isLocalStorageMaintenanceScopeCurrent(localMaintenanceScope));
12131
+ for (const { itemKey, lastAccessAt } of persistedItemEntries) if (removalResult.removedKeys.has(itemKey) && plannedBudgetEvictedItemKeys.has(itemKey)) {
11557
12132
  rememberBudgetEvictedEntry(budgetEvictedItemRecency, itemKey, lastAccessAt, itemSnapshotByKey.get(itemKey), storeRef !== null && storeRef.state.items[itemKey] != null);
11558
12133
  forgetPersistedItem(itemKey);
11559
12134
  }
11560
- knownPersistedItemKeys = keptItemKeys;
11561
- if (evictedItemKeys.size === 0 || keptQueryKeys.size === 0) return;
12135
+ for (const itemKey of ignoredItemKeys) if (removalResult.removedKeys.has(itemKey)) forgetPersistedItem(itemKey);
12136
+ const evictedItemKeys = new Set([...plannedBudgetEvictedItemKeys].filter((itemKey) => removalResult.removedKeys.has(itemKey)));
12137
+ if (localMaintenanceScope !== void 0 && evictedItemKeys.size > 0) pendingLocalQueryReconciliationSessions.add(localMaintenanceScope.sessionKey);
12138
+ if (!removalResult.completed) {
12139
+ knownPersistedItemKeys = null;
12140
+ return;
12141
+ }
12142
+ if (localMaintenanceScope !== void 0 && !isLocalStorageMaintenanceScopeCurrent(localMaintenanceScope)) {
12143
+ knownPersistedItemKeys = null;
12144
+ knownPersistedQueryKeys = null;
12145
+ return;
12146
+ }
12147
+ const keptItemKeys = new Set(persistedItemEntries.flatMap(({ itemKey }) => removalResult.removedKeys.has(itemKey) ? [] : [itemKey]));
12148
+ knownPersistedItemKeys = removalResult.staleKeys.size > 0 ? null : keptItemKeys;
12149
+ if (removalResult.staleKeys.size > 0 && maintenanceCallbackKey !== null) scheduleLocalStorageMaintenance([maintenanceCallbackKey]);
12150
+ if (removalResult.staleKeys.size === 0) logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
12151
+ if (!(localMaintenanceScope === void 0 ? evictedItemKeys.size > 0 : pendingLocalQueryReconciliationSessions.has(localMaintenanceScope.sessionKey)) || keptQueryKeys.size === 0) {
12152
+ if (keptQueryKeys.size === 0 && localMaintenanceScope !== void 0) pendingLocalQueryReconciliationSessions.delete(localMaintenanceScope.sessionKey);
12153
+ return;
12154
+ }
11562
12155
  const queryEntries = managedQueryEntriesByKey ? [...managedQueryEntriesByKey.values()].filter(({ queryKey }) => keptQueryKeys.has(queryKey)) : filterAndMap([...keptQueryKeys], (queryKey) => {
11563
- const entry = readLocalStorageQueryEntry(queryKey);
12156
+ const entry = readLocalStorageQueryEntry(queryKey, localMaintenanceScope === void 0 ? void 0 : `${localMaintenanceScope.queryPrefix}${queryKey}`);
11564
12157
  if (!entry) {
11565
12158
  forgetPersistedQuery(queryKey);
11566
12159
  keptQueryKeys.delete(queryKey);
@@ -11568,15 +12161,30 @@ function setupListQueryPersistence(config, options = {}) {
11568
12161
  }
11569
12162
  return entry;
11570
12163
  });
11571
- await Promise.all(queryEntries.map(async (queryData) => {
12164
+ let staleQueryFound = false;
12165
+ for (const queryData of queryEntries) {
12166
+ if (idleContext !== void 0 && !await idleContext.yieldIfNeeded()) return;
12167
+ if (localMaintenanceScope !== void 0 && !isLocalStorageMaintenanceScopeCurrent(localMaintenanceScope)) {
12168
+ knownPersistedQueryKeys = null;
12169
+ return;
12170
+ }
11572
12171
  const limitedQuery = limitPersistedQueryItems(queryData.items.filter((itemKey) => keptItemKeys.has(itemKey)), queryData.hasMore, maxQuerySize);
11573
- if (limitedQuery.itemKeys.length === queryData.items.length && limitedQuery.hasMore === queryData.hasMore) return;
11574
- await saveLocalStorageQueryEntry(queryData.queryKey, {
12172
+ if (limitedQuery.itemKeys.length === queryData.items.length && limitedQuery.hasMore === queryData.hasMore) continue;
12173
+ const nextQueryData = {
11575
12174
  payload: queryData.payload,
11576
12175
  items: limitedQuery.itemKeys,
11577
12176
  hasMore: limitedQuery.hasMore
11578
- });
11579
- }));
12177
+ };
12178
+ let saved = true;
12179
+ if (idleContext === void 0) await saveLocalStorageQueryEntry(queryData.queryKey, nextQueryData);
12180
+ else if (localMaintenanceScope !== void 0) saved = await saveLocalStorageQueryEntryIfUnchanged(queryData, nextQueryData, idleContext, localMaintenanceScope);
12181
+ else saved = false;
12182
+ if (!saved) staleQueryFound = true;
12183
+ }
12184
+ if (staleQueryFound) {
12185
+ knownPersistedQueryKeys = null;
12186
+ if (maintenanceCallbackKey !== null) scheduleLocalStorageMaintenance([maintenanceCallbackKey]);
12187
+ } else if (localMaintenanceScope !== void 0) pendingLocalQueryReconciliationSessions.delete(localMaintenanceScope.sessionKey);
11580
12188
  return;
11581
12189
  }
11582
12190
  const itemMetadataEntries = await listAllPersistentStorageNamespaceMetadata(itemNamespace, { order: "lru-desc" });
@@ -15662,7 +16270,7 @@ function createListQueryStore(storeOptions) {
15662
16270
  lastQuerySyncVersions.clear();
15663
16271
  lastItemSyncVersions.clear();
15664
16272
  clearOfflineOverlays();
15665
- }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId);
16273
+ }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId, getStoreManagerAppVersion(storeManager));
15666
16274
  function getQueryTargetKey(queryKey) {
15667
16275
  return `query:${queryKey}`;
15668
16276
  }