tsdf 17.0.0-beta.0 → 17.0.0-beta.4

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
@@ -6939,8 +6939,8 @@ var RequestScheduler = class {
6939
6939
  phase: { type: "idle" },
6940
6940
  pending: {
6941
6941
  scheduledRequests: /* @__PURE__ */ new Map(),
6942
- rtuDelayed: null,
6943
- mediumPriorityDelayed: null,
6942
+ rtuDelayed: /* @__PURE__ */ new Map(),
6943
+ mediumPriorityDelayed: /* @__PURE__ */ new Map(),
6944
6944
  mutationsInProgress: /* @__PURE__ */ new Map()
6945
6945
  },
6946
6946
  timing: {
@@ -6959,7 +6959,7 @@ var RequestScheduler = class {
6959
6959
  }
6960
6960
  get hasPendingFetch() {
6961
6961
  const { phase, pending } = this.#state;
6962
- return phase.type !== "idle" || pending.scheduledRequests.size > 0 || pending.rtuDelayed !== null || pending.mediumPriorityDelayed !== null;
6962
+ return phase.type !== "idle" || pending.scheduledRequests.size > 0 || pending.rtuDelayed.size > 0 || pending.mediumPriorityDelayed.size > 0;
6963
6963
  }
6964
6964
  get fetchIsInProgress() {
6965
6965
  return this.#state.phase.type === "fetching";
@@ -7067,8 +7067,8 @@ var RequestScheduler = class {
7067
7067
  reset() {
7068
7068
  const { phase, pending, abort } = this.#state;
7069
7069
  if (phase.type === "coalescing") clearTimeout(phase.timeoutId);
7070
- if (pending.rtuDelayed) clearTimeout(pending.rtuDelayed.timeoutId);
7071
- if (pending.mediumPriorityDelayed) clearTimeout(pending.mediumPriorityDelayed.timeoutId);
7070
+ for (const rtu of pending.rtuDelayed.values()) clearTimeout(rtu.timeoutId);
7071
+ for (const delayed of pending.mediumPriorityDelayed.values()) clearTimeout(delayed.timeoutId);
7072
7072
  if (abort.controller) abort.controller.abort();
7073
7073
  this.#state = this.#createInitialState();
7074
7074
  }
@@ -7078,15 +7078,18 @@ var RequestScheduler = class {
7078
7078
  * regains focus so a refetch priced with the background throttle doesn't
7079
7079
  * keep the tab stale. Never extends the pending delay. */
7080
7080
  reevaluateDelayedRTU() {
7081
- const rtu = this.#state.pending.rtuDelayed;
7082
- if (!rtu || !this.#dynamicRealtimeThrottleMs) return;
7081
+ if (!this.#dynamicRealtimeThrottleMs) return;
7082
+ if (this.#state.pending.rtuDelayed.size === 0) return;
7083
7083
  const { timing } = this.#state;
7084
- if (timing.lastFetchStartTime + timing.lastFetchDuration + this.#dynamicRealtimeThrottleMs(timing.lastFetchDuration) >= rtu.fireAt) return;
7085
- clearTimeout(rtu.timeoutId);
7086
- this.#state.pending.rtuDelayed = null;
7087
- if (!this.#scheduleDelayedRTU(Date.now(), rtu.requestId, rtu.payload, rtu.remoteStartCancelable)) {
7088
- this.#onEvent?.("scheduled-rt-fetch-started");
7089
- this.#scheduleRequest(rtu.requestId, "highPriority", rtu.payload, void 0, rtu.remoteStartCancelable);
7084
+ const newFireAt = timing.lastFetchStartTime + timing.lastFetchDuration + this.#dynamicRealtimeThrottleMs(timing.lastFetchDuration);
7085
+ for (const rtu of Array.from(this.#state.pending.rtuDelayed.values())) {
7086
+ if (newFireAt >= rtu.fireAt) continue;
7087
+ clearTimeout(rtu.timeoutId);
7088
+ this.#state.pending.rtuDelayed.delete(rtu.requestId);
7089
+ if (!this.#scheduleDelayedRTU(Date.now(), rtu.requestId, rtu.payload, rtu.remoteStartCancelable)) {
7090
+ this.#onEvent?.("scheduled-rt-fetch-started");
7091
+ this.#scheduleRequest(rtu.requestId, "highPriority", rtu.payload, void 0, rtu.remoteStartCancelable);
7092
+ }
7090
7093
  }
7091
7094
  }
7092
7095
  cancelCoalescingRequests(requestIds) {
@@ -7102,20 +7105,24 @@ var RequestScheduler = class {
7102
7105
  this.#finalizePendingRequestCallbacks(scheduledRequest, false);
7103
7106
  wasCancelled = true;
7104
7107
  }
7105
- const rtuDelayed = this.#state.pending.rtuDelayed;
7106
- if (rtuDelayed && requestIds.includes(rtuDelayed.requestId) && matchesShouldCancel(shouldCancel, rtuDelayed.requestId, rtuDelayed)) {
7107
- this.#clearRtuDelayed();
7108
- wasCancelled = true;
7108
+ for (const requestId of requestIds) {
7109
+ const rtuDelayed = this.#state.pending.rtuDelayed.get(requestId);
7110
+ if (rtuDelayed && matchesShouldCancel(shouldCancel, requestId, rtuDelayed)) {
7111
+ this.#clearRtuDelayed(requestId);
7112
+ wasCancelled = true;
7113
+ }
7109
7114
  }
7110
- const mediumPriorityDelayed = this.#state.pending.mediumPriorityDelayed;
7111
- if (mediumPriorityDelayed && requestIds.includes(mediumPriorityDelayed.requestId) && matchesShouldCancel(shouldCancel, mediumPriorityDelayed.requestId, mediumPriorityDelayed)) {
7112
- this.#cancelMediumPriority();
7113
- wasCancelled = true;
7115
+ for (const requestId of requestIds) {
7116
+ const mediumDelayed = this.#state.pending.mediumPriorityDelayed.get(requestId);
7117
+ if (mediumDelayed && matchesShouldCancel(shouldCancel, requestId, mediumDelayed)) {
7118
+ this.#cancelMediumPriority(requestId);
7119
+ wasCancelled = true;
7120
+ }
7114
7121
  }
7115
- if (this.#state.phase.type === "fetching") {
7116
- const rtuAfterFetch = this.#state.phase.rtuAfterFetch;
7117
- if (rtuAfterFetch && requestIds.includes(rtuAfterFetch.requestId) && matchesShouldCancel(shouldCancel, rtuAfterFetch.requestId, rtuAfterFetch)) {
7118
- this.#state.phase.rtuAfterFetch = null;
7122
+ if (this.#state.phase.type === "fetching") for (const requestId of requestIds) {
7123
+ const rtuAfterFetch = this.#state.phase.rtuAfterFetch.get(requestId);
7124
+ if (rtuAfterFetch && matchesShouldCancel(shouldCancel, requestId, rtuAfterFetch)) {
7125
+ this.#state.phase.rtuAfterFetch.delete(requestId);
7119
7126
  wasCancelled = true;
7120
7127
  }
7121
7128
  }
@@ -7251,10 +7258,12 @@ var RequestScheduler = class {
7251
7258
  fetchId,
7252
7259
  startTime,
7253
7260
  fetchingRequests,
7254
- rtuAfterFetch: null
7261
+ rtuAfterFetch: /* @__PURE__ */ new Map()
7255
7262
  };
7256
- this.#clearRtuDelayed();
7257
- this.#cancelMediumPriority();
7263
+ for (const requestId of requests.keys()) {
7264
+ this.#clearRtuDelayed(requestId);
7265
+ this.#cancelMediumPriority(requestId);
7266
+ }
7258
7267
  const shouldAbort = this.#createShouldAbort(fetchId, requests, abortController);
7259
7268
  const batchRequests = Array.from(requests.entries()).map(([requestId, request]) => ({
7260
7269
  requestId,
@@ -7278,13 +7287,15 @@ var RequestScheduler = class {
7278
7287
  }
7279
7288
  if (Array.from(results.values()).some((value) => value)) this.#state.timing.lastFetchDuration = Date.now() - startTime;
7280
7289
  const { fetchingRequests: callbacks, rtuAfterFetch } = this.#state.phase;
7281
- this.#clearRtuDelayed();
7282
7290
  this.#state.phase = { type: "idle" };
7283
7291
  for (const [requestId, { awaitCallbacks }] of callbacks) {
7284
7292
  const wasAborted = this.#state.lastAbortedRequests.has(requestId);
7285
7293
  for (const callback of awaitCallbacks) callback(wasAborted);
7286
7294
  }
7287
- if (rtuAfterFetch) this.#scheduleDelayedRTU(Date.now(), rtuAfterFetch.requestId, rtuAfterFetch.payload, rtuAfterFetch.remoteStartCancelable);
7295
+ for (const rtu of rtuAfterFetch.values()) if (!this.#scheduleDelayedRTU(Date.now(), rtu.requestId, rtu.payload, rtu.remoteStartCancelable)) {
7296
+ this.#onEvent?.("scheduled-rt-fetch-started");
7297
+ this.#scheduleRequest(rtu.requestId, "highPriority", rtu.payload, void 0, rtu.remoteStartCancelable);
7298
+ }
7288
7299
  this.#flushScheduledRequests();
7289
7300
  return true;
7290
7301
  }
@@ -7368,30 +7379,35 @@ var RequestScheduler = class {
7368
7379
  }
7369
7380
  return false;
7370
7381
  }
7371
- #clearRtuDelayed() {
7372
- const rtu = this.#state.pending.rtuDelayed;
7382
+ #clearRtuDelayed(requestId) {
7383
+ const rtu = this.#state.pending.rtuDelayed.get(requestId);
7373
7384
  if (rtu) {
7374
7385
  clearTimeout(rtu.timeoutId);
7375
- this.#state.pending.rtuDelayed = null;
7386
+ this.#state.pending.rtuDelayed.delete(requestId);
7376
7387
  this.#onEvent?.("rt-fetch-cancelled");
7377
7388
  }
7378
7389
  }
7379
7390
  #handleRealtimeUpdate(startTime, requestId, payload, remoteStartCancelable) {
7380
7391
  const { timing, phase, pending } = this.#state;
7381
7392
  if (!timing.lastFetchDuration || !timing.lastFetchStartTime || !this.#dynamicRealtimeThrottleMs) return false;
7382
- if (pending.rtuDelayed && pending.rtuDelayed.requestId === requestId) {
7383
- pending.rtuDelayed.payload = this.#coalescePayload ? this.#coalescePayload(pending.rtuDelayed.payload, payload) : payload;
7384
- pending.rtuDelayed.remoteStartCancelable = pending.rtuDelayed.remoteStartCancelable && remoteStartCancelable;
7393
+ const existingDelayed = pending.rtuDelayed.get(requestId);
7394
+ if (existingDelayed) {
7395
+ existingDelayed.payload = this.#coalescePayload ? this.#coalescePayload(existingDelayed.payload, payload) : payload;
7396
+ existingDelayed.remoteStartCancelable = existingDelayed.remoteStartCancelable && remoteStartCancelable;
7385
7397
  return true;
7386
7398
  }
7387
7399
  if (phase.type === "fetching") {
7388
- phase.rtuAfterFetch = {
7400
+ const existing = phase.rtuAfterFetch.get(requestId);
7401
+ if (existing) {
7402
+ existing.payload = this.#coalescePayload ? this.#coalescePayload(existing.payload, payload) : payload;
7403
+ existing.remoteStartCancelable = existing.remoteStartCancelable && remoteStartCancelable;
7404
+ } else phase.rtuAfterFetch.set(requestId, {
7389
7405
  requestId,
7390
7406
  payload,
7391
7407
  priority: "realtimeUpdate",
7392
7408
  addedAt: startTime,
7393
7409
  remoteStartCancelable
7394
- };
7410
+ });
7395
7411
  return true;
7396
7412
  }
7397
7413
  if (pending.mutationsInProgress.has(requestId)) {
@@ -7407,11 +7423,11 @@ var RequestScheduler = class {
7407
7423
  const minimumRealtimeInterval = this.#dynamicRealtimeThrottleMs(timing.lastFetchDuration);
7408
7424
  if (timeSinceLastFetch >= minimumRealtimeInterval) return false;
7409
7425
  const delay = minimumRealtimeInterval - timeSinceLastFetch;
7410
- this.#state.pending.rtuDelayed = {
7426
+ const existing = this.#state.pending.rtuDelayed.get(requestId);
7427
+ if (existing) clearTimeout(existing.timeoutId);
7428
+ this.#state.pending.rtuDelayed.set(requestId, {
7411
7429
  timeoutId: setTimeout(() => {
7412
- this.#state.pending.rtuDelayed = null;
7413
- this.#onEvent?.("scheduled-rt-fetch-started");
7414
- this.#scheduleRequest(requestId, "highPriority", payload, void 0, remoteStartCancelable);
7430
+ this.#executeDelayedRTUFetch(requestId);
7415
7431
  }, delay),
7416
7432
  requestId,
7417
7433
  payload,
@@ -7419,44 +7435,61 @@ var RequestScheduler = class {
7419
7435
  addedAt: startTime,
7420
7436
  remoteStartCancelable,
7421
7437
  fireAt: startTime + delay
7422
- };
7438
+ });
7423
7439
  this.#onEvent?.("rt-fetch-scheduled", { delayMs: delay });
7424
7440
  return true;
7425
7441
  }
7442
+ /** Executes from the current delayed entry, not from the args captured when
7443
+ * the timeout was created — realtime updates arriving during the delay
7444
+ * coalesce their payloads into the entry. */
7445
+ #executeDelayedRTUFetch(requestId) {
7446
+ const delayedRequest = this.#state.pending.rtuDelayed.get(requestId);
7447
+ if (!delayedRequest) return;
7448
+ this.#state.pending.rtuDelayed.delete(requestId);
7449
+ this.#onEvent?.("scheduled-rt-fetch-started");
7450
+ this.#scheduleRequest(requestId, "highPriority", delayedRequest.payload, void 0, delayedRequest.remoteStartCancelable);
7451
+ }
7426
7452
  #handleMediumPriority(requestId, payload, startTime, customDelayMs, remoteStartCancelable) {
7427
7453
  const delayMs = customDelayMs ?? this.#mediumPriorityDelayMs;
7428
7454
  if (delayMs === void 0) throw new Error("[tsdf] mediumPriorityDelayMs must be configured to use mediumPriority fetch type");
7429
7455
  if (!this.#state.timing.lastFetchStartTime) return this.#scheduleRequest(requestId, "highPriority", payload, void 0, remoteStartCancelable);
7430
- if (this.#state.pending.mediumPriorityDelayed) clearTimeout(this.#state.pending.mediumPriorityDelayed.timeoutId);
7431
- this.#state.pending.mediumPriorityDelayed = {
7456
+ const existing = this.#state.pending.mediumPriorityDelayed.get(requestId);
7457
+ let mergedPayload = payload;
7458
+ let mergedRemoteStartCancelable = remoteStartCancelable;
7459
+ if (existing) {
7460
+ clearTimeout(existing.timeoutId);
7461
+ mergedPayload = this.#coalescePayload ? this.#coalescePayload(existing.payload, payload) : payload;
7462
+ mergedRemoteStartCancelable = existing.remoteStartCancelable && remoteStartCancelable;
7463
+ }
7464
+ this.#state.pending.mediumPriorityDelayed.set(requestId, {
7432
7465
  timeoutId: setTimeout(() => {
7433
7466
  this.#executeMediumPriorityFetch(requestId);
7434
7467
  }, delayMs),
7435
7468
  requestId,
7436
- payload,
7469
+ payload: mergedPayload,
7437
7470
  priority: "mediumPriority",
7438
7471
  addedAt: startTime,
7439
- remoteStartCancelable
7440
- };
7472
+ remoteStartCancelable: mergedRemoteStartCancelable
7473
+ });
7441
7474
  this.#onEvent?.("medium-priority-scheduled", { delayMs });
7442
7475
  return "medium-scheduled";
7443
7476
  }
7444
7477
  #executeMediumPriorityFetch(requestId) {
7445
- const delayedRequest = this.#state.pending.mediumPriorityDelayed;
7446
- if (!delayedRequest || delayedRequest.requestId !== requestId) return;
7447
- this.#state.pending.mediumPriorityDelayed = null;
7478
+ const delayedRequest = this.#state.pending.mediumPriorityDelayed.get(requestId);
7479
+ if (!delayedRequest) return;
7480
+ this.#state.pending.mediumPriorityDelayed.delete(requestId);
7448
7481
  this.#onEvent?.("medium-priority-fetch-started");
7449
- const { phase, pending } = this.#state;
7450
- if (phase.type !== "idle" || pending.mutationsInProgress.has(requestId)) {
7482
+ if (this.#state.phase.type === "fetching") {
7451
7483
  this.#addToScheduledRequests(requestId, delayedRequest.payload, "mediumPriority", Date.now(), delayedRequest.remoteStartCancelable);
7452
7484
  return;
7453
7485
  }
7454
7486
  this.#scheduleRequest(requestId, "highPriority", delayedRequest.payload, void 0, delayedRequest.remoteStartCancelable);
7455
7487
  }
7456
- #cancelMediumPriority() {
7457
- if (this.#state.pending.mediumPriorityDelayed) {
7458
- clearTimeout(this.#state.pending.mediumPriorityDelayed.timeoutId);
7459
- this.#state.pending.mediumPriorityDelayed = null;
7488
+ #cancelMediumPriority(requestId) {
7489
+ const delayed = this.#state.pending.mediumPriorityDelayed.get(requestId);
7490
+ if (delayed) {
7491
+ clearTimeout(delayed.timeoutId);
7492
+ this.#state.pending.mediumPriorityDelayed.delete(requestId);
7460
7493
  this.#onEvent?.("medium-priority-cancelled");
7461
7494
  }
7462
7495
  }
@@ -11941,6 +11974,24 @@ function getFallbackMissingRequestedFields(fallbackItemState, requestedFields, i
11941
11974
  return missingLoadedFields.filter((field) => !inferredFields.includes(field));
11942
11975
  }
11943
11976
  /**
11977
+ * Fields from `requestedFields` that are genuinely absent from the snapshot —
11978
+ * not tracked as loaded, not vouched by `inferFields`, and not merely stale
11979
+ * (awaiting an invalidation re-fetch). Stale fields were loaded when their
11980
+ * invalidation was recorded, so their stale data is still present and may stay
11981
+ * visible while the re-fetch runs; only genuinely absent fields have no data
11982
+ * to show. Staleness is proven either by the field being in the unresolved
11983
+ * pending invalidation list, or — for an item with data still present — by the
11984
+ * unresolved full ('*') invalidation marker, which means the snapshot was
11985
+ * complete when invalidated.
11986
+ */
11987
+ function getGenuinelyMissingRequestedFields(itemKey, fallbackItemState, requestedFields, inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields) {
11988
+ const fallbackMissingFields = getFallbackMissingRequestedFields(fallbackItemState, requestedFields, inferFields);
11989
+ if (fallbackMissingFields.length === 0) return fallbackMissingFields;
11990
+ if (itemsPendingFullInvalidation.has(itemKey) && fallbackItemState?.item) return [];
11991
+ if (unresolvedPendingInvalidationFields.length === 0) return fallbackMissingFields;
11992
+ return fallbackMissingFields.filter((field) => !unresolvedPendingInvalidationFields.includes(field));
11993
+ }
11994
+ /**
11944
11995
  * Returns the fields from `requestedFields` that are not yet present in
11945
11996
  * `loadedFields`. When either argument is `undefined` or empty, returns `[]`.
11946
11997
  */
@@ -13034,7 +13085,7 @@ const GET_ALL = () => true;
13034
13085
  //#endregion
13035
13086
  //#region src/listQueryStore/createMutationApi.ts
13036
13087
  /** @internal */
13037
- function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent, itemPendingInvalidationFields, itemsPendingFullInvalidation) {
13088
+ function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations) {
13038
13089
  const storeEvents = evtmitter();
13039
13090
  const deferredOptimisticQueryInvalidationsStack = [];
13040
13091
  const optimisticMutationQueryContextStack = [];
@@ -13094,6 +13145,25 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13094
13145
  const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
13095
13146
  const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
13096
13147
  const itemFieldInvalidationPriorities = /* @__PURE__ */ new Map();
13148
+ /**
13149
+ * The staleness baseline for invalidations: a field is invalidatable
13150
+ * exactly when it is displayable, and hooks display the UNION of the
13151
+ * tracked `itemLoadedFields` metadata and whatever `inferFields` currently
13152
+ * vouches for (e.g. fields a mutation wrote beyond the tracked metadata).
13153
+ * Collapses to '*' when either side is '*' — the displayable set is then
13154
+ * not enumerable.
13155
+ */
13156
+ function getInvalidationBaselineFields(itemKey) {
13157
+ const trackedLoadedFields = store.state.itemLoadedFields[itemKey];
13158
+ if (trackedLoadedFields === "*") return "*";
13159
+ if (!partialResources) return trackedLoadedFields;
13160
+ const itemState = store.state.items[itemKey];
13161
+ if (!itemState) return trackedLoadedFields;
13162
+ const inferredFields = partialResources.inferFields(itemState);
13163
+ if (inferredFields === "*") return "*";
13164
+ if (!trackedLoadedFields || trackedLoadedFields.length === 0) return inferredFields;
13165
+ return Array.from(new Set([...trackedLoadedFields, ...inferredFields]));
13166
+ }
13097
13167
  function invalidateQueryAndItems(args) {
13098
13168
  const itemPayload = args.all ? GET_ALL : args.itemPayload;
13099
13169
  const queryPayload = args.all ? GET_ALL : args.queryPayload;
@@ -13121,29 +13191,49 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13121
13191
  const itemsKey = getItemsKeyArray(itemPayload);
13122
13192
  const nextInvalidationPriorityByItemKey = /* @__PURE__ */ new Map();
13123
13193
  const nextPendingInvalidationFieldsByItemKey = /* @__PURE__ */ new Map();
13194
+ const staleInvalidateFieldsByItemKey = /* @__PURE__ */ new Map();
13124
13195
  for (const { itemKey } of itemsKey) {
13196
+ const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
13197
+ const staleInvalidateFields = effectiveLoadedFields === "*" ? invalidateFields : invalidateFields.filter((field) => effectiveLoadedFields?.includes(field) ?? false);
13198
+ if (staleInvalidateFields.length < invalidateFields.length) {
13199
+ let droppedForItem = itemDroppedFieldInvalidations.get(itemKey);
13200
+ for (const field of invalidateFields) {
13201
+ if (staleInvalidateFields.includes(field)) continue;
13202
+ if (!droppedForItem) {
13203
+ droppedForItem = /* @__PURE__ */ new Map();
13204
+ itemDroppedFieldInvalidations.set(itemKey, droppedForItem);
13205
+ }
13206
+ const existingDropped = droppedForItem.get(field);
13207
+ droppedForItem.set(field, {
13208
+ invalidatedAt: Date.now(),
13209
+ priority: existingDropped && fetchTypePriority[existingDropped.priority] > fetchTypePriority[priority] ? existingDropped.priority : priority
13210
+ });
13211
+ }
13212
+ }
13213
+ if (staleInvalidateFields.length === 0) continue;
13214
+ staleInvalidateFieldsByItemKey.set(itemKey, staleInvalidateFields);
13125
13215
  const existingPriority = itemFieldInvalidationPriorities.get(itemKey);
13126
13216
  const existingPendingFields = itemPendingInvalidationFields.get(itemKey) ?? [];
13127
- nextPendingInvalidationFieldsByItemKey.set(itemKey, Array.from(new Set([...existingPendingFields, ...invalidateFields])).sort());
13217
+ nextPendingInvalidationFieldsByItemKey.set(itemKey, Array.from(new Set([...existingPendingFields, ...staleInvalidateFields])).sort());
13128
13218
  nextInvalidationPriorityByItemKey.set(itemKey, existingPriority && fetchTypePriority[existingPriority] > fetchTypePriority[priority] ? existingPriority : priority);
13129
13219
  }
13130
13220
  for (const [itemKey, itemPriority] of nextInvalidationPriorityByItemKey) itemFieldInvalidationPriorities.set(itemKey, itemPriority);
13131
13221
  for (const [itemKey, invalidationFields] of nextPendingInvalidationFieldsByItemKey) itemPendingInvalidationFields.set(itemKey, invalidationFields);
13132
13222
  store.produceState((draft) => {
13133
- for (const { itemKey } of itemsKey) {
13223
+ for (const [itemKey, staleInvalidateFields] of staleInvalidateFieldsByItemKey) {
13134
13224
  const loadedFields = draft.itemLoadedFields[itemKey];
13135
13225
  if (!loadedFields) continue;
13136
- if (loadedFields !== "*") draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !invalidateFields.includes(f));
13226
+ if (loadedFields !== "*") draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !staleInvalidateFields.includes(f));
13137
13227
  const existingInvalidationFields = draft.itemFieldInvalidationFields[itemKey] ?? [];
13138
- draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...invalidateFields])).sort();
13228
+ draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...staleInvalidateFields])).sort();
13139
13229
  }
13140
13230
  }, { action: "invalidate-item-fields" });
13141
- for (const { itemKey } of itemsKey) {
13231
+ for (const [itemKey, staleInvalidateFields] of staleInvalidateFieldsByItemKey) {
13142
13232
  itemInvalidationWasTriggered.delete(itemKey);
13143
13233
  emitInvalidateItem({
13144
13234
  priority: nextInvalidationPriorityByItemKey.get(itemKey) ?? priority,
13145
13235
  itemKey,
13146
- invalidateFields
13236
+ invalidateFields: staleInvalidateFields
13147
13237
  });
13148
13238
  }
13149
13239
  } else invalidateItem(itemPayload, priority);
@@ -13154,11 +13244,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13154
13244
  for (const { itemKey, payload } of itemsKey) {
13155
13245
  const item = store.state.itemQueries[itemKey];
13156
13246
  if (!item) continue;
13157
- let effectiveLoadedFields = store.state.itemLoadedFields[itemKey];
13158
- if (partialResources && effectiveLoadedFields === void 0) {
13159
- const itemState = store.state.items[itemKey];
13160
- if (itemState) effectiveLoadedFields = partialResources.inferFields(itemState);
13161
- }
13247
+ const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
13162
13248
  const itemWasFullyLoaded = partialResources && effectiveLoadedFields === "*";
13163
13249
  const trackedInvalidationFields = partialResources && !itemWasFullyLoaded ? Array.from(new Set([...effectiveLoadedFields === "*" ? [] : effectiveLoadedFields ?? [], ...itemPendingInvalidationFields.get(itemKey) ?? []])).sort() : [];
13164
13250
  const trackedInvalidationPriority = trackedInvalidationFields.length > 0 || itemsPendingFullInvalidation.has(itemKey) ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
@@ -13199,6 +13285,55 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13199
13285
  }
13200
13286
  }
13201
13287
  }
13288
+ /**
13289
+ * Called when a fetch settles for `itemKeys` (item fetches and list fetches
13290
+ * that committed the items). Per-field invalidations of never-loaded fields
13291
+ * are dropped at invalidation time (see `invalidateQueryAndItems`) — but a
13292
+ * fetch that STARTED BEFORE such an invalidation commits a response
13293
+ * produced before it, so the just-loaded value may already be stale.
13294
+ * Re-announce those invalidations as a regular per-field invalidation (the
13295
+ * field now has a displayable value). Fields loaded by a fetch started
13296
+ * after the invalidation are fresh relative to it — their record is simply
13297
+ * discarded.
13298
+ */
13299
+ function reannounceInvalidationsDroppedDuringFetch(itemKeys, fetchStartedAt) {
13300
+ for (const itemKey of itemKeys) {
13301
+ const droppedForItem = itemDroppedFieldInvalidations.get(itemKey);
13302
+ if (!droppedForItem) continue;
13303
+ const loadedFields = store.state.itemLoadedFields[itemKey];
13304
+ let staleFields;
13305
+ let stalePriority;
13306
+ for (const [field, dropped] of droppedForItem) {
13307
+ if (!(loadedFields === "*" || (loadedFields?.includes(field) ?? false))) continue;
13308
+ droppedForItem.delete(field);
13309
+ if (dropped.invalidatedAt > fetchStartedAt) {
13310
+ (staleFields ??= []).push(field);
13311
+ if (!stalePriority || fetchTypePriority[dropped.priority] > fetchTypePriority[stalePriority]) stalePriority = dropped.priority;
13312
+ }
13313
+ }
13314
+ if (droppedForItem.size === 0) itemDroppedFieldInvalidations.delete(itemKey);
13315
+ if (!staleFields || !stalePriority) continue;
13316
+ const existingPriority = itemFieldInvalidationPriorities.get(itemKey);
13317
+ const mergedPriority = existingPriority && fetchTypePriority[existingPriority] > fetchTypePriority[stalePriority] ? existingPriority : stalePriority;
13318
+ const existingPendingFields = itemPendingInvalidationFields.get(itemKey) ?? [];
13319
+ itemPendingInvalidationFields.set(itemKey, Array.from(new Set([...existingPendingFields, ...staleFields])).sort());
13320
+ itemFieldInvalidationPriorities.set(itemKey, mergedPriority);
13321
+ const staleFieldsToApply = staleFields;
13322
+ store.produceState((draft) => {
13323
+ const draftLoadedFields = draft.itemLoadedFields[itemKey];
13324
+ if (!draftLoadedFields) return;
13325
+ if (draftLoadedFields !== "*") draft.itemLoadedFields[itemKey] = draftLoadedFields.filter((f) => !staleFieldsToApply.includes(f));
13326
+ const existingInvalidationFields = draft.itemFieldInvalidationFields[itemKey] ?? [];
13327
+ draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...staleFieldsToApply])).sort();
13328
+ }, { action: "invalidate-item-fields" });
13329
+ itemInvalidationWasTriggered.delete(itemKey);
13330
+ emitInvalidateItem({
13331
+ priority: mergedPriority,
13332
+ itemKey,
13333
+ invalidateFields: staleFields
13334
+ });
13335
+ }
13336
+ }
13202
13337
  function startItemMutation(itemId) {
13203
13338
  const itemsKey = getItemsKeyArray(itemId);
13204
13339
  const endMutations = [];
@@ -13403,6 +13538,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13403
13538
  itemFieldInvalidationPriorities.delete(itemKey);
13404
13539
  itemPendingInvalidationFields.delete(itemKey);
13405
13540
  itemsPendingFullInvalidation.delete(itemKey);
13541
+ itemDroppedFieldInvalidations.delete(itemKey);
13406
13542
  itemInvalidationWasTriggered.delete(itemKey);
13407
13543
  publishItemSnapshot(itemKey);
13408
13544
  }
@@ -13415,6 +13551,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13415
13551
  itemFieldInvalidationPriorities.clear();
13416
13552
  itemPendingInvalidationFields.clear();
13417
13553
  itemsPendingFullInvalidation.clear();
13554
+ itemDroppedFieldInvalidations.clear();
13418
13555
  }
13419
13556
  async function performMutation(payload, { optimisticUpdate, mutation, silentErrors, revalidateOnSuccess, onSuccess, onError, debounce, offline, upload }) {
13420
13557
  const payloadToUse = payload === null ? [] : payload;
@@ -13496,6 +13633,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13496
13633
  itemFieldInvalidationPriorities,
13497
13634
  invalidateQueryAndItems,
13498
13635
  invalidateItem,
13636
+ reannounceInvalidationsDroppedDuringFetch,
13499
13637
  startItemMutation,
13500
13638
  updateItemState,
13501
13639
  addItemToState,
@@ -13897,10 +14035,10 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13897
14035
  const fetchQueriesWithId = shouldDebounceFetchQueries ? debouncedFetchQueriesWithId : queriesWithId;
13898
14036
  const offlineEntitiesByKey = useMemo(() => createOfflineEntityLookup(offlineEntities), [offlineEntities]);
13899
14037
  const activeOfflineOverlays = useMemo(() => filterActiveOfflineOverlays(offlineEntitiesByKey, offlineOverlays), [offlineEntitiesByKey, offlineOverlays]);
13900
- const getUnresolvedPendingInvalidationFields = useCallback((itemKey) => {
13901
- const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
14038
+ const getUnresolvedPendingInvalidationFields = useCallback((itemKey, state) => {
14039
+ const stateInvalidationFields = (state ? state.itemFieldInvalidationFields : store.state.itemFieldInvalidationFields)[itemKey];
13902
14040
  if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
13903
- return excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
14041
+ return excludeLoadedFields((state ? state.itemLoadedFields : store.state.itemLoadedFields)[itemKey], itemPendingInvalidationFields.get(itemKey));
13904
14042
  }, [itemPendingInvalidationFields, store]);
13905
14043
  const resultSelector = useCallback((state) => {
13906
14044
  return queriesWithId.map(({ itemKey, payload, fields, returnIdleStatus, returnRefetchingStatus, showPartialAsRefetching, queryMetadata }) => {
@@ -13963,10 +14101,10 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13963
14101
  let status = itemQuery.status;
13964
14102
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
13965
14103
  if (partialResources && Array.isArray(fields) && fields.length > 0 && (status === "success" || status === "refetching")) {
13966
- if (getFallbackMissingRequestedFields({
14104
+ if (getGenuinelyMissingRequestedFields(itemKey, {
13967
14105
  item: rawItemState,
13968
14106
  loadedFields
13969
- }, fields, partialResources.inferFields).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
14107
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
13970
14108
  } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
13971
14109
  const isIncomplete = !snapshotIsFullyLoaded(loadedFields, rawItemState, partialResources.inferFields) && !(itemsPendingFullInvalidation.has(itemKey) && hasCachedDataInState);
13972
14110
  const isStale = !isIncomplete && !snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, rawItemState, partialResources.inferFields, itemsPendingFullInvalidation);
@@ -13975,7 +14113,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13975
14113
  }
13976
14114
  if (partialResources && showPartialAsRefetching) {
13977
14115
  if (Array.isArray(fields) && fields.length > 0) {
13978
- const pendingRequestedFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, rawItemState, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey));
14116
+ const pendingRequestedFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, rawItemState, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state));
13979
14117
  if (pendingRequestedFields.length > 0) loadingFields = pendingRequestedFields;
13980
14118
  } else if (fields === "*") {
13981
14119
  if (hasFullyLoadedFields(loadedFields) && itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) loadingFields = itemFieldInvalidationFields;
@@ -14010,7 +14148,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14010
14148
  return queriesWithId.map(({ itemKey, fields }) => {
14011
14149
  const itemQuery = state.itemQueries[itemKey];
14012
14150
  const loadedFields = state.itemLoadedFields[itemKey] ?? [];
14013
- const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).sort() : [];
14151
+ const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).sort() : [];
14014
14152
  const needsFullFetch = partialResources && fields === "*" ? !snapshotIsFullyLoaded(loadedFields, state.items[itemKey], partialResources.inferFields) || itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields) : false;
14015
14153
  return {
14016
14154
  status: itemQuery?.status ?? null,
@@ -14098,23 +14236,42 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14098
14236
  store,
14099
14237
  visibleStoreState
14100
14238
  ]);
14239
+ const ignoreItemsInRefetchOnMount = useConst(() => /* @__PURE__ */ new Set());
14101
14240
  useOnEvtmitterEvent(events, "invalidateItem", ({ payload: event }) => {
14102
14241
  if (loadFromStateOnly || !fetchItemFn) return;
14103
- const matchingQueries = fetchQueriesWithId.filter(({ itemKey, isOffScreen }) => !isOffScreen && itemKey === event.itemKey);
14242
+ const queriesForItem = fetchQueriesWithId.filter(({ itemKey }) => itemKey === event.itemKey);
14243
+ let fieldsToFetch;
14244
+ if (event.invalidateFields && event.invalidateFields.length > 0) fieldsToFetch = Array.from(new Set(event.invalidateFields)).sort();
14245
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(event.itemKey);
14246
+ const loadedFields = store.state.itemLoadedFields[event.itemKey];
14247
+ const owedStaleFields = new Set([...store.state.itemFieldInvalidationFields[event.itemKey] ?? [], ...excludeLoadedFields(loadedFields, itemPendingInvalidationFields.get(event.itemKey))]);
14248
+ const affectedQueries = fieldsToFetch ? queriesForItem.filter(({ fields }) => {
14249
+ if (fields === "*") return true;
14250
+ if (!fields || fields.length === 0) return true;
14251
+ if (fields.some((field) => event.invalidateFields?.includes(field))) return true;
14252
+ return hasUnresolvedFullInvalidation ? excludeLoadedFields(loadedFields, fields).length > 0 : fields.some((field) => owedStaleFields.has(field));
14253
+ }) : queriesForItem;
14254
+ if (affectedQueries.length === 0) return;
14255
+ ignoreItemsInRefetchOnMount.delete(event.itemKey);
14256
+ const matchingQueries = affectedQueries.filter(({ isOffScreen }) => !isOffScreen);
14104
14257
  if (matchingQueries.length === 0) return;
14105
- if (itemInvalidationWasTriggered.has(event.itemKey)) return;
14106
14258
  if (matchingQueries.every((q) => q.disableRefetches) && store.state.itemQueries[event.itemKey]?.wasLoaded) return;
14107
- let fieldsToFetch;
14108
- if (event.invalidateFields && event.invalidateFields.length > 0) {
14109
- fieldsToFetch = Array.from(new Set(event.invalidateFields)).sort();
14110
- if (!matchingQueries.some(({ fields }) => {
14111
- if (fields === "*") return true;
14112
- if (!fields || fields.length === 0) return true;
14113
- return fields.some((field) => event.invalidateFields?.includes(field));
14114
- })) return;
14115
- }
14116
14259
  const firstQuery = matchingQueries[0];
14117
14260
  if (!firstQuery) return;
14261
+ const hookFields = firstQuery.fields;
14262
+ const isUnboundedHook = !hookFields || hookFields === "*" || hookFields.length === 0;
14263
+ if (itemInvalidationWasTriggered.has(event.itemKey)) {
14264
+ if (!fieldsToFetch) return;
14265
+ const contributionFields = hasUnresolvedFullInvalidation ? isUnboundedHook ? void 0 : excludeLoadedFields(loadedFields, hookFields) : isUnboundedHook ? Array.from(owedStaleFields) : hookFields.filter((field) => owedStaleFields.has(field));
14266
+ if (contributionFields && contributionFields.length === 0) return;
14267
+ scheduleAutomaticItemFetch(event.priority, firstQuery.payload, { fields: contributionFields });
14268
+ return;
14269
+ }
14270
+ if (fieldsToFetch) if (hasUnresolvedFullInvalidation) fieldsToFetch = isUnboundedHook ? void 0 : Array.from(new Set([...fieldsToFetch, ...excludeLoadedFields(loadedFields, hookFields)])).sort();
14271
+ else {
14272
+ const rideAlongFields = isUnboundedHook ? Array.from(owedStaleFields) : hookFields.filter((field) => owedStaleFields.has(field));
14273
+ fieldsToFetch = Array.from(new Set([...fieldsToFetch, ...rideAlongFields])).sort();
14274
+ }
14118
14275
  store.produceState((draft) => {
14119
14276
  const query = draft.itemQueries[event.itemKey];
14120
14277
  if (!query?.refetchOnMount) return;
@@ -14123,7 +14280,6 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14123
14280
  scheduleAutomaticItemFetch(event.priority, firstQuery.payload, { fields: fieldsToFetch ?? firstQuery.fields });
14124
14281
  itemInvalidationWasTriggered.add(event.itemKey);
14125
14282
  });
14126
- const ignoreItemsInRefetchOnMount = useConst(() => /* @__PURE__ */ new Set());
14127
14283
  useLayoutEffect(() => {
14128
14284
  if (loadFromStateOnly || !preloadItemsBeforePaint || !preloadItems || fetchQueriesWithId.length < 1) return;
14129
14285
  preloadItems(fetchQueriesWithId.map(({ payload }) => payload));
@@ -14160,28 +14316,32 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14160
14316
  const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields);
14161
14317
  const invalidationPriority = unresolvedPendingInvalidationFields.length > 0 || hasUnresolvedFullInvalidation ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
14162
14318
  if (Array.isArray(fields) && fields.length > 0) {
14163
- const affectedInvalidationFields = fields.filter((field) => unresolvedPendingInvalidationFields.includes(field));
14164
14319
  const staleOrMissingFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, item, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields);
14165
- const missingFields = loadedFields === "*" ? [] : staleOrMissingFields.filter((field) => !loadedFields.includes(field));
14320
+ const missingFields = getGenuinelyMissingRequestedFields(itemKey, {
14321
+ item,
14322
+ loadedFields
14323
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields);
14324
+ const staleInvalidatedFields = staleOrMissingFields.filter((field) => !missingFields.includes(field));
14166
14325
  const hasMissingFields = missingFields.length > 0;
14167
- const hasAffectedFieldInvalidation = affectedInvalidationFields.length > 0;
14168
- const shouldFetchForInvalidation = hasAffectedFieldInvalidation && !ignoreItemsInRefetchOnMount.has(itemKey);
14326
+ const hasStaleInvalidatedFields = staleInvalidatedFields.length > 0;
14327
+ const shouldFetchForInvalidation = hasStaleInvalidatedFields && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
14169
14328
  if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive) {
14170
14329
  shouldFetch = true;
14171
14330
  requiredFetch = true;
14172
- fieldsToFetch = Array.from(new Set([...missingFields, ...affectedInvalidationFields]));
14173
- if (fetchType === "lowPriority") fetchType = "highPriority";
14331
+ fieldsToFetch = Array.from(new Set([...missingFields, ...staleInvalidatedFields]));
14332
+ if ((hasMissingFields || !invalidationPriority) && fetchType === "lowPriority") fetchType = "highPriority";
14174
14333
  }
14175
- if (hasAffectedFieldInvalidation && invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14334
+ if (hasStaleInvalidatedFields && !hasMissingFields && invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14176
14335
  } else if (fields === "*") {
14177
- const missingFullItem = !snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation;
14178
- const shouldFetchForInvalidation = !missingFullItem && unresolvedPendingInvalidationFields.length > 0 && !ignoreItemsInRefetchOnMount.has(itemKey);
14336
+ const hasStaleFullInvalidation = hasUnresolvedFullInvalidation && !!item;
14337
+ const missingFullItem = !hasStaleFullInvalidation && (!snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation);
14338
+ const shouldFetchForInvalidation = !missingFullItem && (unresolvedPendingInvalidationFields.length > 0 || hasStaleFullInvalidation) && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
14179
14339
  if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive) {
14180
14340
  shouldFetch = true;
14181
14341
  requiredFetch = true;
14182
- fieldsToFetch = missingFullItem ? "*" : unresolvedPendingInvalidationFields;
14183
- if (fetchType === "lowPriority") fetchType = "highPriority";
14184
- if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14342
+ fieldsToFetch = missingFullItem || hasStaleFullInvalidation ? "*" : unresolvedPendingInvalidationFields;
14343
+ if ((missingFullItem || !invalidationPriority) && fetchType === "lowPriority") fetchType = "highPriority";
14344
+ if (!missingFullItem && invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14185
14345
  }
14186
14346
  }
14187
14347
  }
@@ -14332,14 +14492,20 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14332
14492
  let highestPriority;
14333
14493
  for (const itemKey of itemKeys) {
14334
14494
  const unresolvedInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
14335
- if (unresolvedInvalidationFields.length === 0) continue;
14336
- if (requestedFields && !requestedFields.some((field) => unresolvedInvalidationFields.includes(field))) continue;
14495
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(store.state.itemLoadedFields[itemKey]);
14496
+ if (unresolvedInvalidationFields.length === 0 && !hasUnresolvedFullInvalidation) continue;
14497
+ if (!hasUnresolvedFullInvalidation && requestedFields && !requestedFields.some((field) => unresolvedInvalidationFields.includes(field))) continue;
14337
14498
  const itemPriority = itemFieldInvalidationPriorities.get(itemKey);
14338
14499
  if (!itemPriority) continue;
14339
14500
  if (!highestPriority || fetchTypePriority[itemPriority] > fetchTypePriority[highestPriority]) highestPriority = itemPriority;
14340
14501
  }
14341
14502
  return highestPriority;
14342
- }, [getUnresolvedPendingInvalidationFields, itemFieldInvalidationPriorities]);
14503
+ }, [
14504
+ getUnresolvedPendingInvalidationFields,
14505
+ itemFieldInvalidationPriorities,
14506
+ itemsPendingFullInvalidation,
14507
+ store
14508
+ ]);
14343
14509
  const getVisibleQueryItemKeys = useCallback((queryKey, itemKeys) => {
14344
14510
  const missingOverlayItems = overlayItemsByQueryKey.get(queryKey);
14345
14511
  const hasDeletions = deletedOverlayItemKeys.size > 0;
@@ -14488,10 +14654,10 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14488
14654
  }
14489
14655
  }
14490
14656
  if (partialResources && Array.isArray(fields) && statusCanBeOverridden && staleOrMissingRequestedFields && staleOrMissingRequestedFields.size > 0) {
14491
- const someItemMissingFieldDataInState = effectiveQuery.query.items.some((itemKey) => getFallbackMissingRequestedFields({
14657
+ const someItemMissingFieldDataInState = effectiveQuery.query.items.some((itemKey) => getGenuinelyMissingRequestedFields(itemKey, {
14492
14658
  item: state.items[itemKey],
14493
14659
  loadedFields: state.itemLoadedFields[itemKey]
14494
- }, fields, partialResources.inferFields).length > 0);
14660
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0);
14495
14661
  if (!hasCachedItemsInState) status = "loading";
14496
14662
  else if (someItemMissingFieldDataInState) status = showPartialAsRefetching ? "refetching" : "loading";
14497
14663
  else status = "refetching";
@@ -14661,9 +14827,9 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14661
14827
  store,
14662
14828
  visibleStoreState
14663
14829
  ]);
14830
+ const pendingOffScreenQueryInvalidations = useConst(() => /* @__PURE__ */ new Map());
14664
14831
  useOnEvtmitterEvent(events, "invalidateQuery", ({ payload: event }) => {
14665
14832
  for (const { key, payload, fields, loadSize, isOffScreen, disableRefetches } of fetchQueriesWithId) {
14666
- if (isOffScreen) continue;
14667
14833
  if (key !== event.queryKey) continue;
14668
14834
  const resolvedQuery = resolveEffectiveQuery(store.state, {
14669
14835
  key,
@@ -14671,6 +14837,11 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14671
14837
  fields
14672
14838
  });
14673
14839
  if (disableRefetches && resolvedQuery?.query.wasLoaded) continue;
14840
+ if (isOffScreen) {
14841
+ const existingPriority = pendingOffScreenQueryInvalidations.get(key);
14842
+ if (!existingPriority || fetchTypePriority[event.priority] > fetchTypePriority[existingPriority]) pendingOffScreenQueryInvalidations.set(key, event.priority);
14843
+ continue;
14844
+ }
14674
14845
  if (!queryInvalidationWasTriggered.has(key)) {
14675
14846
  stickyDerivedQueryKeys.delete(key);
14676
14847
  store.produceState((draft) => {
@@ -14678,9 +14849,9 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14678
14849
  if (!query?.refetchOnMount) return;
14679
14850
  query.refetchOnMount = false;
14680
14851
  });
14681
- scheduleAutomaticListQueryFetch(event.priority, payload, loadSize, { fields });
14682
14852
  queryInvalidationWasTriggered.add(key);
14683
14853
  }
14854
+ scheduleAutomaticListQueryFetch(event.priority, payload, loadSize, { fields });
14684
14855
  }
14685
14856
  });
14686
14857
  const ignoreQueriesInRefetchOnMount = useConst(() => /* @__PURE__ */ new Set());
@@ -14729,35 +14900,59 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14729
14900
  if (partialResources && !shouldFetch && effectiveQueryState) {
14730
14901
  const isQueryFetchInFlight = effectiveQueryState.status === "loading" || effectiveQueryState.status === "refetching" || effectiveQueryState.status === "loadingMore";
14731
14902
  if (Array.isArray(fields) && fields.length > 0) {
14732
- if (effectiveQueryState.items.some((itemKey) => getStaleOrMissingRequestedFields(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).length > 0) && !isQueryFetchInFlight) {
14733
- shouldFetch = true;
14734
- requiredFetch = true;
14735
- fieldsToFetch = fields;
14736
- if (fetchType === "lowPriority") fetchType = "highPriority";
14903
+ let hasStaleOrMissingRequestedFields = false;
14904
+ let hasGenuinelyMissingFields = false;
14905
+ for (const itemKey of effectiveQueryState.items) {
14906
+ const unresolvedInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
14907
+ if (getStaleOrMissingRequestedFields(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedInvalidationFields).length === 0) continue;
14908
+ hasStaleOrMissingRequestedFields = true;
14909
+ if (getGenuinelyMissingRequestedFields(itemKey, {
14910
+ item: store.state.items[itemKey],
14911
+ loadedFields: store.state.itemLoadedFields[itemKey]
14912
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedInvalidationFields).length > 0) {
14913
+ hasGenuinelyMissingFields = true;
14914
+ break;
14915
+ }
14737
14916
  }
14738
- if (effectiveQueryState.items.some((itemKey) => {
14739
- const itemFieldInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
14740
- return itemFieldInvalidationFields.length > 0 && fields.some((f) => itemFieldInvalidationFields.includes(f));
14741
- }) && !isQueryFetchInFlight) {
14917
+ if (hasStaleOrMissingRequestedFields && !isQueryFetchInFlight) {
14742
14918
  shouldFetch = true;
14743
14919
  requiredFetch = true;
14744
14920
  fieldsToFetch = fields;
14745
- const invalidationPriority = getHighestPendingInvalidationPriority(effectiveQueryState.items, fields);
14746
- if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14921
+ const invalidationPriority = hasGenuinelyMissingFields ? void 0 : getHighestPendingInvalidationPriority(effectiveQueryState.items, fields);
14922
+ if (!invalidationPriority) {
14923
+ if (fetchType === "lowPriority") fetchType = "highPriority";
14924
+ } else if (fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14747
14925
  }
14748
14926
  } else if (fields === "*") {
14749
- const hasAnyPartialItem = effectiveQueryState.items.some((itemKey) => !snapshotIsFullyLoadedAndFresh(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], partialResources.inferFields, itemsPendingFullInvalidation));
14750
- const hasAnyFieldInvalidation = effectiveQueryState.items.some((itemKey) => {
14751
- return getUnresolvedPendingInvalidationFields(itemKey).length > 0;
14752
- });
14753
- if ((hasAnyPartialItem || hasAnyFieldInvalidation) && !isQueryFetchInFlight) {
14927
+ let hasStaleItemData = false;
14928
+ let hasGenuinelyMissingItemData = false;
14929
+ for (const itemKey of effectiveQueryState.items) {
14930
+ const item = store.state.items[itemKey];
14931
+ const loadedFields = store.state.itemLoadedFields[itemKey];
14932
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields);
14933
+ const hasStaleFullInvalidation = hasUnresolvedFullInvalidation && !!item;
14934
+ if (!hasStaleFullInvalidation && (!snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation)) {
14935
+ hasGenuinelyMissingItemData = true;
14936
+ break;
14937
+ }
14938
+ if (hasStaleFullInvalidation || getUnresolvedPendingInvalidationFields(itemKey).length > 0) hasStaleItemData = true;
14939
+ }
14940
+ if ((hasGenuinelyMissingItemData || hasStaleItemData) && !isQueryFetchInFlight) {
14754
14941
  shouldFetch = true;
14755
14942
  requiredFetch = true;
14756
- const invalidationPriority = getHighestPendingInvalidationPriority(effectiveQueryState.items, void 0);
14757
- if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14943
+ const invalidationPriority = hasGenuinelyMissingItemData ? void 0 : getHighestPendingInvalidationPriority(effectiveQueryState.items, void 0);
14944
+ if (!invalidationPriority) {
14945
+ if (fetchType === "lowPriority") fetchType = "highPriority";
14946
+ } else if (fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14758
14947
  }
14759
14948
  }
14760
14949
  }
14950
+ const offScreenInvalidationPriority = pendingOffScreenQueryInvalidations.get(queryId);
14951
+ if (offScreenInvalidationPriority !== void 0) {
14952
+ pendingOffScreenQueryInvalidations.delete(queryId);
14953
+ shouldFetch = true;
14954
+ if (fetchTypePriority[offScreenInvalidationPriority] > fetchTypePriority[fetchType]) fetchType = offScreenInvalidationPriority;
14955
+ }
14761
14956
  if (!shouldFetch && ignoreQueriesInRefetchOnMount.has(queryId)) continue;
14762
14957
  ignoreQueriesInRefetchOnMount.add(queryId);
14763
14958
  if (shouldScheduleAutomaticFetch(effectiveQueryState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
@@ -14774,6 +14969,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14774
14969
  getQueryState,
14775
14970
  getDerivedPreloadPayloads,
14776
14971
  ignoreQueriesInRefetchOnMount,
14972
+ pendingOffScreenQueryInvalidations,
14777
14973
  preloadDerivedQueryItems,
14778
14974
  preloadQueries,
14779
14975
  preloadQueriesBeforePaint,
@@ -15196,6 +15392,7 @@ function createListQueryStore(storeOptions) {
15196
15392
  }
15197
15393
  const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
15198
15394
  const itemsPendingFullInvalidation = /* @__PURE__ */ new Set();
15395
+ const itemDroppedFieldInvalidations = /* @__PURE__ */ new Map();
15199
15396
  const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers, reevaluateDelayedRTUs } = createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, wrappedDynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, !!persistence && !persistence.hasAsyncPreload, persistence ? (queryKeys) => persistence.preloadQueries(queryKeys) : void 0, persistence ? (itemKeys) => persistence.preloadItems(itemKeys) : void 0, persistence, testOptions?.initialLastFetchStartTime, (requests, startedAt) => {
15200
15397
  const queryKey = requests[0]?.requestId;
15201
15398
  if (!queryKey) return;
@@ -15209,8 +15406,10 @@ function createListQueryStore(storeOptions) {
15209
15406
  pruneItemInvalidationTracking();
15210
15407
  const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
15211
15408
  if (successfulQueryKeys.length > 0) {
15409
+ const committedItemKeys = successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []);
15212
15410
  touchQueries(successfulQueryKeys);
15213
- touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
15411
+ touchItems(committedItemKeys);
15412
+ reannounceInvalidationsDroppedDuringFetch(committedItemKeys, startedAt);
15214
15413
  if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15215
15414
  }
15216
15415
  const firstQueryKey = successfulQueryKeys[0];
@@ -15240,7 +15439,9 @@ function createListQueryStore(storeOptions) {
15240
15439
  pruneItemInvalidationTracking();
15241
15440
  const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
15242
15441
  if (successfulItems.length > 0) {
15243
- touchItems(successfulItems.map(({ itemKey }) => itemKey));
15442
+ const committedItemKeys = successfulItems.map(({ itemKey }) => itemKey);
15443
+ touchItems(committedItemKeys);
15444
+ reannounceInvalidationsDroppedDuringFetch(committedItemKeys, startedAt);
15244
15445
  if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15245
15446
  }
15246
15447
  const firstSuccessfulItem = successfulItems[0];
@@ -15258,11 +15459,11 @@ function createListQueryStore(storeOptions) {
15258
15459
  for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
15259
15460
  }
15260
15461
  }, offlineFetchController, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15261
- const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, invalidateQueryAndItems, invalidateItem, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, resolvedOnMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, (event) => {
15462
+ const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, invalidateQueryAndItems, invalidateItem, reannounceInvalidationsDroppedDuringFetch, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, resolvedOnMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, (event) => {
15262
15463
  events.emit("invalidateQuery", event);
15263
15464
  }, (event) => {
15264
15465
  events.emit("invalidateItem", event);
15265
- }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15466
+ }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations);
15266
15467
  if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
15267
15468
  normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
15268
15469
  const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
@@ -15345,6 +15546,37 @@ function createListQueryStore(storeOptions) {
15345
15546
  if (remainingFields.length > 0) draft.itemFieldInvalidationFields[itemKey] = remainingFields;
15346
15547
  else delete draft.itemFieldInvalidationFields[itemKey];
15347
15548
  }
15549
+ /**
15550
+ * A confirmed remote snapshot cancels the pending local fetches it
15551
+ * satisfies, but the sender may have refetched only a subset of the
15552
+ * invalidated fields (it fetches only its own hooks' fields). Any fields
15553
+ * still owed after applying the snapshot are re-announced so mounted hooks
15554
+ * re-schedule refetches of their own remaining stale fields — without
15555
+ * this, the cancelled local refetch would leave them stale forever.
15556
+ *
15557
+ * Only called when the snapshot actually cancelled a pending local fetch:
15558
+ * that cancellation is the refetch obligation being destroyed, and gating
15559
+ * on it also guarantees the cross-tab re-announce ping-pong terminates —
15560
+ * a repeat cycle requires a new pending fetch at snapshot arrival.
15561
+ */
15562
+ function emitRemainingInvalidationFieldsAfterSnapshot(itemKey) {
15563
+ const priority = itemFieldInvalidationPriorities.get(itemKey) ?? "highPriority";
15564
+ if (itemsPendingFullInvalidation.has(itemKey)) {
15565
+ events.emit("invalidateItem", {
15566
+ priority,
15567
+ itemKey
15568
+ });
15569
+ return;
15570
+ }
15571
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
15572
+ const remainingFields = stateInvalidationFields && stateInvalidationFields.length > 0 ? stateInvalidationFields : excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
15573
+ if (remainingFields.length === 0) return;
15574
+ events.emit("invalidateItem", {
15575
+ priority,
15576
+ itemKey,
15577
+ invalidateFields: remainingFields
15578
+ });
15579
+ }
15348
15580
  function pruneItemInvalidationTracking() {
15349
15581
  for (const [itemKey, pendingFields] of itemPendingInvalidationFields) {
15350
15582
  const remainingFields = excludeLoadedFields(store.state.itemLoadedFields[itemKey], pendingFields);
@@ -15369,6 +15601,7 @@ function createListQueryStore(storeOptions) {
15369
15601
  itemFieldInvalidationPriorities.delete(itemKey);
15370
15602
  itemPendingInvalidationFields.delete(itemKey);
15371
15603
  itemsPendingFullInvalidation.delete(itemKey);
15604
+ itemDroppedFieldInvalidations.delete(itemKey);
15372
15605
  itemInvalidationWasTriggered.delete(itemKey);
15373
15606
  itemCacheRuntime.clear(itemKey);
15374
15607
  }
@@ -15465,10 +15698,12 @@ function createListQueryStore(storeOptions) {
15465
15698
  }
15466
15699
  }, { action: "browser-tabs-list-item-snapshot" });
15467
15700
  });
15468
- if (message.consistency === "confirmed") itemScheduler?.cancelPendingRequests([message.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(message.item, message.loadedFields, payload.fields));
15701
+ let cancelledPendingItemFetch = false;
15702
+ if (message.consistency === "confirmed" && itemScheduler) cancelledPendingItemFetch = itemScheduler.cancelPendingRequests([message.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(message.item, message.loadedFields, payload.fields));
15469
15703
  itemInvalidationWasTriggered.delete(message.itemKey);
15470
15704
  if (message.item === null && message.itemQuery === null) cleanupItemStateMetadata(message.itemKey);
15471
15705
  pruneItemInvalidationTracking();
15706
+ if (cancelledPendingItemFetch) emitRemainingInvalidationFieldsAfterSnapshot(message.itemKey);
15472
15707
  if (message.item === null && message.itemQuery === null) {
15473
15708
  if (payloadToCleanup) deleteItemFetchResources([{
15474
15709
  itemKey: message.itemKey,
@@ -15480,10 +15715,12 @@ function createListQueryStore(storeOptions) {
15480
15715
  }
15481
15716
  }
15482
15717
  function applyRemoteQuerySnapshot(message) {
15718
+ let cancelledPendingQueryFetch = false;
15719
+ const itemKeysWithCancelledFetch = /* @__PURE__ */ new Set();
15483
15720
  if (message.consistency === "confirmed") {
15484
15721
  const snapshotItemsByKey = new Map(message.items.map((item) => [item.itemKey, item]));
15485
- getOrCreateQueryScheduler(message.queryKey).cancelPendingRequests([message.queryKey], (request) => querySnapshotSatisfiesPendingQueryFetch(message, snapshotItemsByKey, request));
15486
- for (const item of message.items) getKnownItemScheduler(item.itemKey)?.cancelPendingRequests([item.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(item.item, item.loadedFields, payload.fields));
15722
+ cancelledPendingQueryFetch = getOrCreateQueryScheduler(message.queryKey).cancelPendingRequests([message.queryKey], (request) => querySnapshotSatisfiesPendingQueryFetch(message, snapshotItemsByKey, request));
15723
+ for (const item of message.items) if (getKnownItemScheduler(item.itemKey)?.cancelPendingRequests([item.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(item.item, item.loadedFields, payload.fields))) itemKeysWithCancelledFetch.add(item.itemKey);
15487
15724
  }
15488
15725
  runWithoutBroadcast(() => {
15489
15726
  store.produceState((draft) => {
@@ -15511,6 +15748,7 @@ function createListQueryStore(storeOptions) {
15511
15748
  for (const item of message.items) {
15512
15749
  itemInvalidationWasTriggered.delete(item.itemKey);
15513
15750
  lastItemSyncVersions.set(item.itemKey, toBrowserTabsSyncVersion(message, message.consistency));
15751
+ if (cancelledPendingQueryFetch || itemKeysWithCancelledFetch.has(item.itemKey)) emitRemainingInvalidationFieldsAfterSnapshot(item.itemKey);
15514
15752
  }
15515
15753
  touchQueries([message.queryKey]);
15516
15754
  touchItems(message.items.map(({ itemKey }) => itemKey));
@@ -6,12 +6,12 @@ TSDF uses a `RequestScheduler` to intelligently manage when and how fetches are
6
6
 
7
7
  Every fetch request has a priority that determines its behavior:
8
8
 
9
- | Priority | When used | Behavior |
10
- | ---------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11
- | `lowPriority` | Hook mount (default), window focus revalidation | Throttled — skipped if a fetch happened recently (within `lowPriorityThrottleMs`) |
12
- | `mediumPriority` | Background refetches | Delayed by `mediumPriorityDelayMs`, then executed. Cancelled if another fetch starts. If the store has never been fetched, automatically promotes to `highPriority` |
13
- | `realtimeUpdate` | Real-time data pushes | Uses `dynamicRealtimeThrottleMs` for adaptive throttling based on last fetch duration |
14
- | `highPriority` | Explicit invalidation, `ensureIsLoaded` | Executes immediately (after coalescing window). Never throttled |
9
+ | Priority | When used | Behavior |
10
+ | ---------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
11
+ | `lowPriority` | Hook mount (default), window focus revalidation | Throttled — skipped if a fetch happened recently (within `lowPriorityThrottleMs`) |
12
+ | `mediumPriority` | Background refetches | Delayed by `mediumPriorityDelayMs`, then executed. Cancelled if another fetch including the same request starts. If the store has never been fetched, automatically promotes to `highPriority` |
13
+ | `realtimeUpdate` | Real-time data pushes | Uses `dynamicRealtimeThrottleMs` for adaptive throttling based on last fetch duration |
14
+ | `highPriority` | Explicit invalidation, `ensureIsLoaded` | Executes immediately (after coalescing window). Never throttled |
15
15
 
16
16
  ## Throttling
17
17
 
@@ -62,11 +62,13 @@ This prevents race conditions where a fetch could overwrite optimistic updates.
62
62
  Medium-priority fetches have special behavior:
63
63
 
64
64
  1. The fetch is delayed by `mediumPriorityDelayMs`
65
- 2. If another fetch (of any priority) starts during the delay, the medium-priority fetch is cancelled
65
+ 2. If another fetch (of any priority) for the same data starts during the delay, the medium-priority fetch is cancelled
66
66
  3. If the store has never been fetched (`wasLoaded === false`), the fetch is promoted to `highPriority` immediately
67
67
 
68
68
  This is useful for background refetches that should yield to user-initiated actions.
69
69
 
70
+ Delayed medium-priority fetches are tracked per request: on schedulers shared by multiple items (batch fetching via `getItemsBatchKey`), each item keeps its own delay timer, and a fetch of one item does not cancel another item's pending medium-priority refetch. Re-invalidating the same item during the delay resets its timer.
71
+
70
72
  ## Configuration Reference
71
73
 
72
74
  | Option | Required | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "17.0.0-beta.0",
3
+ "version": "17.0.0-beta.4",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",