tsdf 18.3.0 → 18.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -2909,7 +2909,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2909
2909
  }
2910
2910
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2911
2911
  async function clearAllSessionStorage(sessionKey) {
2912
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Daewq7dv.js");
2912
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-BFn-BuAl.js");
2913
2913
  await Promise.all([
2914
2914
  clearSessionStorage(sessionKey, "local-sync"),
2915
2915
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -3774,6 +3774,34 @@ function isOfflineResolutionRecordForStore(resolution, operations) {
3774
3774
  return resolution.operation in operations;
3775
3775
  }
3776
3776
  //#endregion
3777
+ //#region src/persistentStorage/offline/offlineStoreError.typeGuards.ts
3778
+ /**
3779
+ * Whether `error` is the error TSDF reports for a fetch that could not
3780
+ * complete because the offline session is in offline mode (the request is not
3781
+ * sent while offline).
3782
+ *
3783
+ * TSDF only exposes it on reads that have nothing cached to return
3784
+ * (`status: 'error'`): a document, item or query that is returning cached data
3785
+ * stays `success` with `error: null` while offline, so this is the state the
3786
+ * app has to explain to the user ("not available offline").
3787
+ *
3788
+ * Accepts the `error` of hooks and state getters and the `StoreFetchError` of
3789
+ * the `awaitFetch` methods. The error is matched by its whole shape, not only
3790
+ * by `id`, so an app error whose `errorNormalizer` happens to use the
3791
+ * `'offline'` id is not mistaken for it.
3792
+ *
3793
+ * @example
3794
+ * ```tsx
3795
+ * const { data, error } = store.useDocument();
3796
+ *
3797
+ * if (isOfflineStoreError(error)) return <NotAvailableOffline />;
3798
+ * if (error) return <ErrorMessage error={error} />;
3799
+ * ```
3800
+ */
3801
+ function isOfflineStoreError(error) {
3802
+ return !!error && error.id === "offline" && error.code === 0 && error.message === "Offline";
3803
+ }
3804
+ //#endregion
3777
3805
  //#region src/persistentStorage/offline/overlayStoreLifecycle.ts
3778
3806
  function rebindOfflineOverlayEntries(overlayStore, itemKeyRewrites, createReboundOverlay) {
3779
3807
  if (itemKeyRewrites.length === 0) return;
@@ -3986,7 +4014,11 @@ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWin
3986
4014
  }
3987
4015
  //#endregion
3988
4016
  //#region src/utils/browserTabsSync.ts
3989
- const PROTOCOL_VERSION = 1;
4017
+ /**
4018
+ * Bump when a message shape changes: tabs running another tsdf release then
4019
+ * ignore each other instead of misreading messages.
4020
+ */
4021
+ const PROTOCOL_VERSION = 2;
3990
4022
  const CHANNEL_PREFIX = "tsdf";
3991
4023
  function createBrowserTabsChannelName(storeType, storeKey, appVersion) {
3992
4024
  return `${CHANNEL_PREFIX}${appVersion === void 0 ? "" : `:app:${encodeURIComponent(appVersion)}`}:${storeType}:${storeKey}`;
@@ -4257,10 +4289,10 @@ function parseSyncMessage(message, storeType) {
4257
4289
  //#endregion
4258
4290
  //#region src/persistentStorage/offlineUploadsShared.ts
4259
4291
  function stripStoredUploadFile(record) {
4260
- const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, ...upload } = record;
4292
+ const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, storeName: _storeName, ...upload } = record;
4261
4293
  return upload;
4262
4294
  }
4263
- function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt, metadata) {
4295
+ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt, metadata, storeName) {
4264
4296
  const file = normalizeUploadFile(fileInput, id);
4265
4297
  const now = Date.now();
4266
4298
  const createdAt = createdAtInput ?? now;
@@ -4281,7 +4313,8 @@ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, crea
4281
4313
  ...lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt } : {},
4282
4314
  ...metadata !== void 0 ? { metadata } : {},
4283
4315
  file,
4284
- lastModified: file.lastModified
4316
+ lastModified: file.lastModified,
4317
+ ...storeName !== void 0 ? { storeName } : {}
4285
4318
  };
4286
4319
  }
4287
4320
  function normalizeUploadFile(file, fallbackName) {
@@ -4292,6 +4325,67 @@ function normalizeUploadFile(file, fallbackName) {
4292
4325
  });
4293
4326
  }
4294
4327
  //#endregion
4328
+ //#region src/persistentStorage/offline/entityMetadata.ts
4329
+ function createOfflineEntityLookup(entities) {
4330
+ const entitiesByKey = /* @__PURE__ */ new Map();
4331
+ for (const entity of entities) entitiesByKey.set(entity.entityKey, entity);
4332
+ return entitiesByKey;
4333
+ }
4334
+ const storeEntityLookupsBySessionEntities = /* @__PURE__ */ new WeakMap();
4335
+ const emptyEntityLookup = /* @__PURE__ */ new Map();
4336
+ /**
4337
+ * Entities of one store keyed by entity key, for a snapshot of the session's
4338
+ * entities (all stores). The lookups are built once per snapshot and shared by
4339
+ * every reader, so per-item readers (one per rendered row) do a keyed read
4340
+ * instead of each scanning the whole session on every change.
4341
+ */
4342
+ function getOfflineStoreEntityLookup(sessionEntities, storeName) {
4343
+ let lookupsByStoreName = storeEntityLookupsBySessionEntities.get(sessionEntities);
4344
+ if (!lookupsByStoreName) {
4345
+ lookupsByStoreName = /* @__PURE__ */ new Map();
4346
+ for (const entity of sessionEntities) {
4347
+ let lookup = lookupsByStoreName.get(entity.storeName);
4348
+ if (!lookup) {
4349
+ lookup = /* @__PURE__ */ new Map();
4350
+ lookupsByStoreName.set(entity.storeName, lookup);
4351
+ }
4352
+ lookup.set(entity.entityKey, entity);
4353
+ }
4354
+ storeEntityLookupsBySessionEntities.set(sessionEntities, lookupsByStoreName);
4355
+ }
4356
+ return lookupsByStoreName.get(storeName) ?? emptyEntityLookup;
4357
+ }
4358
+ function toItemOfflineState(entity) {
4359
+ if (entity?.entityKind !== "item") return null;
4360
+ return {
4361
+ syncState: entity.syncState,
4362
+ pendingMutations: entity.pendingMutations,
4363
+ requiresResolution: entity.requiresResolution,
4364
+ isUnsentCreation: entity.tempId !== void 0
4365
+ };
4366
+ }
4367
+ function getIsPendingOfflineSync(entity) {
4368
+ return !!entity && !entity.requiresResolution;
4369
+ }
4370
+ function hasPendingOfflineSync(entitiesByKey, entityKeys) {
4371
+ for (const entityKey of entityKeys) if (getIsPendingOfflineSync(entitiesByKey.get(entityKey))) return true;
4372
+ return false;
4373
+ }
4374
+ function shouldApplyOfflineOverlay(entity, overlay) {
4375
+ return !!entity && (!entity.requiresResolution || entity.blockedResolutionCount > 0 || entity.childResolutionCount > 0 || typeof overlay === "object" && overlay !== null && "keepVisibleWhileResolutionRequired" in overlay && overlay.keepVisibleWhileResolutionRequired === true);
4376
+ }
4377
+ /**
4378
+ * Batch-filters offline overlays to only include entries with a pending sync
4379
+ * (entity exists and does not require resolution). Use this instead of calling
4380
+ * {@link getActiveOfflineOverlay} per item when all active overlays are needed
4381
+ * at once.
4382
+ */
4383
+ function filterActiveOfflineOverlays(entitiesByKey, overlays) {
4384
+ const result = {};
4385
+ for (const [entityKey, overlay] of Object.entries(overlays)) if (shouldApplyOfflineOverlay(entitiesByKey.get(entityKey), overlay)) result[entityKey] = overlay;
4386
+ return result;
4387
+ }
4388
+ //#endregion
4295
4389
  //#region src/persistentStorage/offline/sessionCoordinator.ts
4296
4390
  function stripInternalEntityPayload(entity) {
4297
4391
  if (!("payload" in entity)) return entity;
@@ -4576,15 +4670,46 @@ var SessionOfflineCoordinator = class {
4576
4670
  store;
4577
4671
  #registrations = /* @__PURE__ */ new Map();
4578
4672
  #storeContributions = /* @__PURE__ */ new Map();
4673
+ /**
4674
+ * Latest entities and resolutions other tabs reported for their stores. Only
4675
+ * used for stores this tab has not attached, e.g. a store only another tab
4676
+ * created.
4677
+ */
4678
+ #remoteStoreItems = /* @__PURE__ */ new Map();
4579
4679
  #adapters = /* @__PURE__ */ new Set();
4580
4680
  #sessionHandle;
4581
4681
  #browserTabs;
4582
4682
  #onPersistentStorageError;
4583
4683
  #uploadsConfig;
4584
4684
  #uploads = /* @__PURE__ */ new Map();
4685
+ #storedUploadsRestore = null;
4686
+ /**
4687
+ * Ids other tabs deleted while this tab's stored uploads were being listed,
4688
+ * so the list result can't bring them back. `null` outside the listing.
4689
+ */
4690
+ #uploadsRemovedWhileListing = null;
4585
4691
  #referencedUploadIds = /* @__PURE__ */ new Set();
4586
4692
  #uploadQueue;
4587
4693
  #uploadPromisesById = /* @__PURE__ */ new Map();
4694
+ /**
4695
+ * Uploads released by work that left the queue but not deleted yet: a store
4696
+ * had not reported its references, or the upload was still being sent.
4697
+ */
4698
+ #pendingUploadReleases = /* @__PURE__ */ new Set();
4699
+ /**
4700
+ * Files attached to a mutation that is still being queued: saved before the
4701
+ * queue entry that references them, so unused-mutation-upload cleanup must
4702
+ * skip them until a store reports that reference.
4703
+ */
4704
+ #stagedMutationUploadIds = /* @__PURE__ */ new Set();
4705
+ /**
4706
+ * Refs of uploads that were uploaded and then released, so data still
4707
+ * holding their ids (optimistic or draft state) resolves to the same ref
4708
+ * for the rest of the session instead of failing.
4709
+ */
4710
+ #releasedUploadRefs = /* @__PURE__ */ new Map();
4711
+ /** Adapter removals in flight, awaited before the same id is read or saved. */
4712
+ #uploadRemovals = /* @__PURE__ */ new Map();
4588
4713
  #uploadCleanupTimer = null;
4589
4714
  #uploadOnlineSessionStartedAt = null;
4590
4715
  #uploadOnlineSessionStabilizationTimer = null;
@@ -4601,6 +4726,8 @@ var SessionOfflineCoordinator = class {
4601
4726
  #scheduledRecoveryMode = null;
4602
4727
  #recoveryAttempt = 0;
4603
4728
  #classifiedNetworkActive = false;
4729
+ /** Tabs of this session that sent anything on the session channel. */
4730
+ #otherTabIds = /* @__PURE__ */ new Set();
4604
4731
  #networkEnabledOverride;
4605
4732
  #outageEnabledOverride;
4606
4733
  #mutationQueueingOverrides;
@@ -4656,13 +4783,55 @@ var SessionOfflineCoordinator = class {
4656
4783
  for (const listener of offlineRecoveryListeners) listener(sessionKey, (storeName) => !awaitingStores.has(storeName) && (prevAwaitingStores === null || prevAwaitingStores.has(storeName)));
4657
4784
  });
4658
4785
  this.#browserTabs = createBrowserTabsCoordinatorWithPriority("offline", `session:${sessionKey}`, () => this.sessionKey, (message) => {
4786
+ const isNewTab = !this.#otherTabIds.has(message.tabId);
4787
+ this.#otherTabIds.add(message.tabId);
4659
4788
  if (message.kind === "tab-status") {
4660
4789
  this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
4790
+ if (isNewTab) {
4791
+ this.#browserTabs.priority.publishLocalStatus();
4792
+ this.#publishSnapshot();
4793
+ }
4661
4794
  this.#refreshLeadership();
4662
4795
  return;
4663
4796
  }
4797
+ if (message.kind === "offline-queue-entry") {
4798
+ this.#registrations.get(message.storeName)?.onRemoteQueueEntryChange?.(message.entryId, message.entry);
4799
+ return;
4800
+ }
4801
+ if (message.kind === "offline-resolution") {
4802
+ this.#registrations.get(message.storeName)?.onRemoteResolutionChange?.(message.resolutionId, message.resolution);
4803
+ return;
4804
+ }
4805
+ if (message.kind === "offline-temp-reconciled") {
4806
+ this.#registrations.get(message.storeName)?.onRemoteTempReconciled?.(message.tempId, message.finalPayload);
4807
+ return;
4808
+ }
4809
+ if (message.kind === "offline-work-discarded") {
4810
+ this.#registrations.get(message.storeName)?.onRemoteWorkDiscarded?.(message.discardedWork, message.removedTempEntityKeys);
4811
+ return;
4812
+ }
4813
+ if (message.kind === "offline-uploads-removed") {
4814
+ this.#applyRemoteUploadsRemoved(message.ids, message.releasedRefs);
4815
+ return;
4816
+ }
4664
4817
  this.#applyRemoteSnapshot(message);
4665
- }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, void 0, void 0, void 0, options.appVersion);
4818
+ }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, (noteFocusChange) => {
4819
+ if (!isWindowAvailable()) return () => {};
4820
+ const onChange = () => {
4821
+ noteFocusChange();
4822
+ this.#refreshLeadership();
4823
+ };
4824
+ window.addEventListener("focus", onChange);
4825
+ window.addEventListener("blur", onChange);
4826
+ window.addEventListener("pagehide", onChange);
4827
+ document.addEventListener("visibilitychange", onChange);
4828
+ return () => {
4829
+ window.removeEventListener("focus", onChange);
4830
+ window.removeEventListener("blur", onChange);
4831
+ window.removeEventListener("pagehide", onChange);
4832
+ document.removeEventListener("visibilitychange", onChange);
4833
+ };
4834
+ }, void 0, void 0, options.appVersion);
4666
4835
  this.#refreshLeadership();
4667
4836
  if (shouldBootstrapFromStorage) this.hydrate();
4668
4837
  if (this.#hasCanonicalConfig) this.#refreshNetworkConfig();
@@ -4702,16 +4871,12 @@ var SessionOfflineCoordinator = class {
4702
4871
  }
4703
4872
  this.#protectedKeys = [...protectedKeys].sort();
4704
4873
  setSessionProtectedKeysSnapshot(this.sessionKey, this.#protectedKeys);
4705
- if (this.#uploadsConfig) try {
4706
- const uploads = await this.#uploadsConfig.adapter.list(this.sessionKey);
4874
+ if (this.#uploadsConfig) {
4875
+ await this.#restoreStoredUploads();
4707
4876
  if (hydrationToken === this.#hydrationToken) {
4708
- this.#uploads = new Map([...uploads.map((upload) => [upload.id, upload]), ...this.#uploads]);
4709
- this.#syncUploadsState();
4710
4877
  this.#scheduleUploadOnlineSessionStabilization();
4711
4878
  this.#refreshUploadRetention();
4712
4879
  }
4713
- } catch (error) {
4714
- this.#onPersistentStorageError?.(error);
4715
4880
  }
4716
4881
  this.#persistSessionSnapshot();
4717
4882
  }
@@ -4762,18 +4927,66 @@ var SessionOfflineCoordinator = class {
4762
4927
  return () => {
4763
4928
  this.#registrations.delete(registration.storeName);
4764
4929
  this.#storeContributions.delete(registration.storeName);
4930
+ this.#remoteStoreItems.delete(registration.storeName);
4765
4931
  this.#refreshAggregates();
4766
4932
  this.#notifyGreenCycle();
4767
4933
  if (this.#registrations.size === 0) this.#stopRecoveryProbe();
4768
4934
  };
4769
4935
  }
4770
- syncStoreData(storeName, contribution) {
4936
+ syncStoreData(storeName, contribution, isRemoteChange = false) {
4771
4937
  if (this.#disposed) return;
4772
4938
  const replayHeadChanged = !replayHeadsEqual(this.#storeContributions.get(storeName)?.replayHead, contribution.replayHead);
4773
4939
  this.#storeContributions.set(storeName, contribution);
4774
- this.#refreshAggregates();
4940
+ this.#refreshAggregates(!isRemoteChange);
4775
4941
  if (replayHeadChanged) this.#notifyGreenCycle();
4776
4942
  }
4943
+ /** Tells the other tabs that this tab saved or removed (`null`) a queue entry. */
4944
+ publishQueueEntryChange(storeName, entryId, entry) {
4945
+ if (this.#disposed) return;
4946
+ this.#browserTabs.coordinator.publish({
4947
+ kind: "offline-queue-entry",
4948
+ storeName,
4949
+ entryId,
4950
+ entry
4951
+ });
4952
+ }
4953
+ /** Tells the other tabs that this tab saved or removed (`null`) a resolution. */
4954
+ publishResolutionChange(storeName, resolutionId, resolution) {
4955
+ if (this.#disposed) return;
4956
+ this.#browserTabs.coordinator.publish({
4957
+ kind: "offline-resolution",
4958
+ storeName,
4959
+ resolutionId,
4960
+ resolution
4961
+ });
4962
+ }
4963
+ /** Tells the other tabs that this tab reconciled a temp entity. */
4964
+ publishTempReconciled(storeName, tempId, finalPayload) {
4965
+ if (this.#disposed) return;
4966
+ this.#browserTabs.coordinator.publish({
4967
+ kind: "offline-temp-reconciled",
4968
+ storeName,
4969
+ tempId,
4970
+ finalPayload
4971
+ });
4972
+ }
4973
+ /** Tells the other tabs that this tab discarded queued work of a store. */
4974
+ publishWorkDiscarded(storeName, discardedWork, removedEntityKeys) {
4975
+ if (this.#disposed) return;
4976
+ this.#browserTabs.coordinator.publish({
4977
+ kind: "offline-work-discarded",
4978
+ storeName,
4979
+ discardedWork,
4980
+ removedTempEntityKeys: removedEntityKeys
4981
+ });
4982
+ }
4983
+ /**
4984
+ * Whether another tab of this session was seen. While `false`, this tab is
4985
+ * the only one changing the queue, so it can skip the cross-tab safeguards.
4986
+ */
4987
+ hasOtherTabs() {
4988
+ return this.#otherTabIds.size > 0;
4989
+ }
4777
4990
  canReplayEntry(args) {
4778
4991
  const nextReplayHead = [...this.#storeContributions.values()].map((contribution) => contribution.replayHead).filter((head) => head !== null).sort(compareReplayHeads)[0];
4779
4992
  if (!nextReplayHead) return true;
@@ -4823,9 +5036,14 @@ var SessionOfflineCoordinator = class {
4823
5036
  }
4824
5037
  async saveUpload(args) {
4825
5038
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
5039
+ await this.#restoreStoredUploads();
5040
+ await this.#waitForUploadRemoval(args.id);
4826
5041
  if (this.#uploadPromisesById.has(args.id)) throw new Error(`Cannot change upload "${args.id}" while it is queued or uploading`);
5042
+ this.#pendingUploadReleases.delete(args.id);
5043
+ this.#releasedUploadRefs.delete(args.id);
5044
+ if (args.source === "mutation") this.#stagedMutationUploadIds.add(args.id);
4827
5045
  const existing = this.#uploads.get(args.id);
4828
- const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt(), args.metadata);
5046
+ const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt(), args.metadata, args.storeName);
4829
5047
  await this.#saveUploadRecord(nextRecord);
4830
5048
  }
4831
5049
  async replaceUpload(args) {
@@ -4834,20 +5052,74 @@ var SessionOfflineCoordinator = class {
4834
5052
  id: args.id,
4835
5053
  file: args.file,
4836
5054
  source: existing?.source ?? "manual",
4837
- metadata: args.metadata ?? existing?.metadata
5055
+ metadata: args.metadata ?? existing?.metadata,
5056
+ storeName: existing?.storeName
4838
5057
  });
4839
5058
  }
4840
5059
  async loadUpload(id) {
4841
5060
  return (await this.#getUploadRecord(id))?.file ?? null;
4842
5061
  }
4843
5062
  async deleteUpload(id) {
5063
+ await this.#restoreStoredUploads();
4844
5064
  if (this.#referencedUploadIds.has(id)) throw new Error(`Cannot delete upload "${id}" while it is still referenced`);
4845
5065
  if (this.#uploadPromisesById.has(id)) throw new Error(`Cannot delete upload "${id}" while it is uploading`);
4846
- if (!this.#uploadsConfig) return;
4847
- this.#uploads.delete(id);
4848
- await this.#uploadsConfig.adapter.remove(this.sessionKey, id);
4849
- this.#syncUploadsState();
4850
- this.#refreshUploadRetention();
5066
+ this.#stagedMutationUploadIds.delete(id);
5067
+ this.#releasedUploadRefs.delete(id);
5068
+ await this.#removeUploads([id]);
5069
+ }
5070
+ /**
5071
+ * Deletes the given staged uploads unless queued work still needs them.
5072
+ *
5073
+ * Store controllers call this after a queue entry or resolution record left
5074
+ * the queue for good (replayed, discarded, superseded, cancelled), passing
5075
+ * the uploads that work depended on. It must run after the store synced its
5076
+ * remaining references: they are aggregated session-wide, so an upload is
5077
+ * kept while a queue entry or resolution record of any store references it.
5078
+ *
5079
+ * Uploads no queued work referenced are never passed here: the app stages a
5080
+ * file before it queues the mutation, so being unreferenced alone must not
5081
+ * delete an upload. Those are left to `deleteUpload` and to the retention
5082
+ * window.
5083
+ */
5084
+ async deleteUnreferencedUploads(uploadIds) {
5085
+ if (this.#disposed) return;
5086
+ for (const id of uploadIds) this.#pendingUploadReleases.add(id);
5087
+ await this.#releasePendingUploads();
5088
+ }
5089
+ /**
5090
+ * Deletes the released uploads nothing references anymore. Runs again when
5091
+ * the last store reports its references and when a released upload that was
5092
+ * still being sent settles.
5093
+ */
5094
+ async #releasePendingUploads() {
5095
+ if (this.#pendingUploadReleases.size === 0) return;
5096
+ await this.#restoreStoredUploads();
5097
+ const cannotRelease = () => this.#disposed || this.#pendingUploadReleases.size === 0 || this.#storeContributions.size !== this.#registrations.size;
5098
+ if (cannotRelease()) return;
5099
+ const missingIds = [...this.#pendingUploadReleases].filter((id) => !this.#uploads.has(id) && !this.#uploadPromisesById.has(id));
5100
+ if (missingIds.length > 0) {
5101
+ try {
5102
+ await Promise.all(missingIds.map((id) => this.#getUploadRecord(id)));
5103
+ } catch (error) {
5104
+ this.#onPersistentStorageError?.(error);
5105
+ }
5106
+ if (cannotRelease()) return;
5107
+ }
5108
+ const removableIds = [];
5109
+ for (const id of this.#pendingUploadReleases) {
5110
+ if (this.#uploadPromisesById.has(id)) continue;
5111
+ this.#pendingUploadReleases.delete(id);
5112
+ const upload = this.#uploads.get(id);
5113
+ if (upload && !this.#referencedUploadIds.has(id)) {
5114
+ if (upload.state === "uploaded" && upload.resolvedRef !== void 0) this.#releasedUploadRefs.set(id, upload.resolvedRef);
5115
+ removableIds.push(id);
5116
+ }
5117
+ }
5118
+ try {
5119
+ await this.#removeUploads(removableIds);
5120
+ } catch (error) {
5121
+ this.#onPersistentStorageError?.(error);
5122
+ }
4851
5123
  }
4852
5124
  async resolveUploadIds(uploadIds) {
4853
5125
  const entries = await Promise.all(uploadIds.map(async (id) => {
@@ -4855,6 +5127,57 @@ var SessionOfflineCoordinator = class {
4855
5127
  }));
4856
5128
  return Object.fromEntries(entries);
4857
5129
  }
5130
+ /**
5131
+ * Resolves the dependency uploads of a replaying operation. A failure is
5132
+ * returned with the id of the upload that caused it instead of thrown, and
5133
+ * leaves that upload `pending`: replay classifies the failure first and
5134
+ * calls `markUploadFailed` only when it gives up on the operation.
5135
+ */
5136
+ async resolveReplayUploadIds(uploadIds) {
5137
+ const failures = [];
5138
+ const entries = await Promise.all(uploadIds.map(async (id) => {
5139
+ try {
5140
+ return [id, await this.#ensureUploadResolved(id, true)];
5141
+ } catch (error) {
5142
+ failures.push({
5143
+ failedUploadId: id,
5144
+ error
5145
+ });
5146
+ throw error;
5147
+ }
5148
+ })).catch(() => null);
5149
+ return failures[0] ?? { refs: Object.fromEntries(entries ?? []) };
5150
+ }
5151
+ /**
5152
+ * Marks the dependency uploads of an operation as `failed` after replay
5153
+ * moved it to manual resolution. Uploads still being sent are marked if
5154
+ * they fail too. Uploads that are not waiting on a failure (restarted or
5155
+ * uploaded meanwhile) are left untouched.
5156
+ *
5157
+ * Never rejects: the state only drives the upload UI, so a storage error is
5158
+ * reported instead of interrupting the replay.
5159
+ */
5160
+ async markUploadsFailed(ids) {
5161
+ const reportError = (error) => this.#onPersistentStorageError?.(error);
5162
+ const settledIds = [];
5163
+ for (const id of ids) {
5164
+ const inFlight = this.#uploadPromisesById.get(id);
5165
+ if (!inFlight) {
5166
+ settledIds.push(id);
5167
+ continue;
5168
+ }
5169
+ inFlight.catch(() => this.#markUploadFailed(id)).catch(reportError);
5170
+ }
5171
+ await Promise.all(settledIds.map((id) => this.#markUploadFailed(id).catch(reportError)));
5172
+ }
5173
+ async #markUploadFailed(id) {
5174
+ const record = this.#uploads.get(id);
5175
+ if (record?.state !== "pending" || !record.lastError) return;
5176
+ await this.#updateUploadState({
5177
+ id,
5178
+ state: "failed"
5179
+ });
5180
+ }
4858
5181
  isLeader() {
4859
5182
  return this.#browserTabs.priority.getPriorityRank() <= 1;
4860
5183
  }
@@ -5013,6 +5336,11 @@ var SessionOfflineCoordinator = class {
5013
5336
  const nextEnabled = this.#isNetworkEnabled();
5014
5337
  const nextActive = active;
5015
5338
  this.#classifiedNetworkActive = nextActive ? options.classified ?? this.#classifiedNetworkActive : false;
5339
+ const currentStatus = this.store.state.status;
5340
+ if (currentStatus.network.enabled === nextEnabled && currentStatus.network.active === nextActive && !(nextActive && options.recordFailureAt) && (options.recoveryCheckAt === void 0 || options.recoveryCheckAt === currentStatus.lastRecoveryCheckAt)) {
5341
+ this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5342
+ return;
5343
+ }
5016
5344
  this.#updateStatus((current) => ({
5017
5345
  ...current,
5018
5346
  network: {
@@ -5105,10 +5433,38 @@ var SessionOfflineCoordinator = class {
5105
5433
  const initial = this.#getCurrentOfflineState();
5106
5434
  if (typeof initial === "boolean") this.setNetworkActive(initial, { classified: false });
5107
5435
  }
5436
+ /**
5437
+ * Lists the stored uploads into memory, once per coordinator. Every upload
5438
+ * operation that reads or changes a record waits for it first: the in-memory
5439
+ * map is only authoritative after the stored records are in it, and a list
5440
+ * result applied over newer changes would drop saved uploads and bring
5441
+ * deleted ones back.
5442
+ */
5443
+ #restoreStoredUploads() {
5444
+ if (!this.#uploadsConfig) return void 0;
5445
+ return this.#storedUploadsRestore ??= this.#listStoredUploads(this.#uploadsConfig);
5446
+ }
5447
+ async #listStoredUploads(uploadsConfig) {
5448
+ const removedWhileListing = /* @__PURE__ */ new Set();
5449
+ this.#uploadsRemovedWhileListing = removedWhileListing;
5450
+ try {
5451
+ const uploads = await uploadsConfig.adapter.list(this.sessionKey);
5452
+ this.#uploads = new Map([...uploads.filter((upload) => !removedWhileListing.has(upload.id)).map((upload) => [upload.id, upload]), ...this.#uploads]);
5453
+ this.#syncUploadsState();
5454
+ } catch (error) {
5455
+ this.#onPersistentStorageError?.(error);
5456
+ } finally {
5457
+ this.#uploadsRemovedWhileListing = null;
5458
+ }
5459
+ }
5108
5460
  async #getUploadRecord(id) {
5109
5461
  const existing = this.#uploads.get(id);
5110
5462
  if (existing) return existing;
5111
5463
  if (!this.#uploadsConfig) return null;
5464
+ await this.#restoreStoredUploads();
5465
+ const restored = this.#uploads.get(id);
5466
+ if (restored) return restored;
5467
+ await this.#waitForUploadRemoval(id);
5112
5468
  const loaded = await this.#uploadsConfig.adapter.load(this.sessionKey, id);
5113
5469
  const current = this.#uploads.get(id);
5114
5470
  if (current) return current;
@@ -5118,8 +5474,17 @@ var SessionOfflineCoordinator = class {
5118
5474
  }
5119
5475
  return loaded;
5120
5476
  }
5477
+ async #waitForUploadRemoval(id) {
5478
+ let removal = this.#uploadRemovals.get(id);
5479
+ while (removal) {
5480
+ await removal;
5481
+ removal = this.#uploadRemovals.get(id);
5482
+ }
5483
+ }
5121
5484
  async #saveUploadRecord(record) {
5122
5485
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
5486
+ const removal = this.#uploadRemovals.get(record.id);
5487
+ if (removal) await removal;
5123
5488
  this.#uploads.set(record.id, record);
5124
5489
  await this.#uploadsConfig.adapter.save(this.sessionKey, record.id, record);
5125
5490
  this.#syncUploadsState();
@@ -5195,7 +5560,11 @@ var SessionOfflineCoordinator = class {
5195
5560
  const expiredIdSet = new Set(expiredIds);
5196
5561
  if (expiredIdSet.size > 0) {
5197
5562
  for (const id of expiredIdSet) this.#uploads.delete(id);
5198
- await Promise.all(expiredIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
5563
+ try {
5564
+ await Promise.all(expiredIds.map((id) => this.#removeStoredUpload(uploadsConfig, id)));
5565
+ } finally {
5566
+ this.#publishUploadsRemoved(expiredIds);
5567
+ }
5199
5568
  didChange = true;
5200
5569
  }
5201
5570
  if (token !== this.#uploadRetentionToken || this.#disposed) return;
@@ -5216,7 +5585,7 @@ var SessionOfflineCoordinator = class {
5216
5585
  this.#publishSnapshot();
5217
5586
  }
5218
5587
  #buildNextUploadRecord(current, args) {
5219
- return {
5588
+ const nextRecord = {
5220
5589
  ...current,
5221
5590
  state: args.state,
5222
5591
  updatedAt: Date.now(),
@@ -5224,6 +5593,8 @@ var SessionOfflineCoordinator = class {
5224
5593
  ...args.progress !== void 0 ? { progress: args.progress } : {},
5225
5594
  ...args.lastError !== void 0 ? { lastError: args.lastError } : {}
5226
5595
  };
5596
+ if (args.state === "uploaded") delete nextRecord.lastError;
5597
+ return nextRecord;
5227
5598
  }
5228
5599
  async #updateUploadState(args) {
5229
5600
  const current = await this.#getUploadRecord(args.id);
@@ -5235,9 +5606,13 @@ var SessionOfflineCoordinator = class {
5235
5606
  } else await this.#saveUploadRecord(nextRecord);
5236
5607
  return nextRecord;
5237
5608
  }
5238
- async #ensureUploadResolved(id) {
5609
+ async #ensureUploadResolved(id, forReplay = false) {
5239
5610
  const existingRecord = await this.#getUploadRecord(id);
5240
- if (!existingRecord) throw new Error(`Unknown offline upload "${id}"`);
5611
+ if (!existingRecord) {
5612
+ const releasedRef = this.#releasedUploadRefs.get(id);
5613
+ if (releasedRef !== void 0) return releasedRef;
5614
+ throw new Error(`Unknown offline upload "${id}"`);
5615
+ }
5241
5616
  if (existingRecord.state === "uploaded" && existingRecord.resolvedRef !== void 0) return existingRecord.resolvedRef;
5242
5617
  const existingPromise = this.#uploadPromisesById.get(id);
5243
5618
  if (existingPromise) return existingPromise;
@@ -5245,7 +5620,11 @@ var SessionOfflineCoordinator = class {
5245
5620
  const uploadsConfig = this.#uploadsConfig;
5246
5621
  const uploadPromise = this.#uploadQueue.resultifyAdd(async () => {
5247
5622
  const queuedRecord = await this.#getUploadRecord(id);
5248
- if (!queuedRecord) throw new Error(`Unknown offline upload "${id}"`);
5623
+ if (!queuedRecord) {
5624
+ const releasedRef = this.#releasedUploadRefs.get(id);
5625
+ if (releasedRef !== void 0) return releasedRef;
5626
+ throw new Error(`Unknown offline upload "${id}"`);
5627
+ }
5249
5628
  if (queuedRecord.state === "uploaded" && queuedRecord.resolvedRef !== void 0) return queuedRecord.resolvedRef;
5250
5629
  const file = queuedRecord.file;
5251
5630
  await this.#updateUploadState({
@@ -5286,7 +5665,7 @@ var SessionOfflineCoordinator = class {
5286
5665
  } catch (error) {
5287
5666
  await this.#updateUploadState({
5288
5667
  id,
5289
- state: "failed",
5668
+ state: forReplay ? "pending" : "failed",
5290
5669
  lastError: { message: error instanceof Error ? error.message : "Upload failed" }
5291
5670
  });
5292
5671
  throw error;
@@ -5296,40 +5675,105 @@ var SessionOfflineCoordinator = class {
5296
5675
  return result.value;
5297
5676
  }).finally(() => {
5298
5677
  this.#uploadPromisesById.delete(id);
5678
+ if (this.#pendingUploadReleases.has(id)) this.#releasePendingUploads();
5299
5679
  });
5300
5680
  this.#uploadPromisesById.set(id, uploadPromise);
5301
5681
  return uploadPromise;
5302
5682
  }
5303
5683
  async #cleanupUnusedMutationUploads() {
5684
+ await this.#removeUploads([...this.#uploads.values()].filter((upload) => upload.source === "mutation" && (upload.storeName !== void 0 ? this.#registrations.has(upload.storeName) : [...this.#registrations.keys()].some((storeName) => upload.id.startsWith(`${storeName}:`)))).map((upload) => upload.id).filter((id) => !this.#referencedUploadIds.has(id) && !this.#uploadPromisesById.has(id) && !this.#stagedMutationUploadIds.has(id)));
5685
+ }
5686
+ async #removeUploads(ids) {
5304
5687
  const uploadsConfig = this.#uploadsConfig;
5305
- if (!uploadsConfig) return;
5306
- const removableIds = [...this.#uploads.values()].filter((upload) => upload.source === "mutation").map((upload) => upload.id).filter((id) => !this.#referencedUploadIds.has(id) && !this.#uploadPromisesById.has(id));
5307
- if (removableIds.length === 0) return;
5308
- for (const id of removableIds) this.#uploads.delete(id);
5309
- await Promise.all(removableIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
5688
+ if (!uploadsConfig || ids.length === 0) return;
5689
+ try {
5690
+ await Promise.all(ids.map((id) => {
5691
+ this.#uploads.delete(id);
5692
+ return this.#removeStoredUpload(uploadsConfig, id);
5693
+ }));
5694
+ } finally {
5695
+ this.#publishUploadsRemoved(ids);
5696
+ }
5310
5697
  this.#syncUploadsState();
5311
5698
  this.#refreshUploadRetention();
5312
5699
  }
5313
- #refreshAggregates() {
5700
+ /** Tells the other tabs that this tab deleted these stored uploads. */
5701
+ #publishUploadsRemoved(ids) {
5702
+ if (this.#disposed || ids.length === 0 || !this.hasOtherTabs()) return;
5703
+ const releasedRefs = [];
5704
+ for (const id of ids) {
5705
+ const ref = this.#releasedUploadRefs.get(id);
5706
+ if (ref !== void 0) releasedRefs.push([id, ref]);
5707
+ }
5708
+ this.#browserTabs.coordinator.publish({
5709
+ kind: "offline-uploads-removed",
5710
+ ids: [...ids],
5711
+ releasedRefs
5712
+ });
5713
+ }
5714
+ #applyRemoteUploadsRemoved(ids, releasedRefs) {
5715
+ const removedIds = new Set(ids);
5716
+ for (const id of removedIds) {
5717
+ this.#releasedUploadRefs.delete(id);
5718
+ this.#pendingUploadReleases.delete(id);
5719
+ this.#uploads.delete(id);
5720
+ this.#uploadsRemovedWhileListing?.add(id);
5721
+ }
5722
+ for (const [id, ref] of releasedRefs) this.#releasedUploadRefs.set(id, ref);
5723
+ const { uploads } = this.store.state;
5724
+ if (uploads.some((upload) => removedIds.has(upload.id))) this.store.setPartialState({ uploads: uploads.filter((upload) => !removedIds.has(upload.id)) }, { action: "offline-session-uploads" });
5725
+ }
5726
+ /**
5727
+ * Removes an upload from the adapter, tracking the removal so a save or
5728
+ * load of the same id waits for it.
5729
+ */
5730
+ #removeStoredUpload(uploadsConfig, id) {
5731
+ const removal = uploadsConfig.adapter.remove(this.sessionKey, id);
5732
+ const settled = removal.then(() => {}, () => {});
5733
+ this.#uploadRemovals.set(id, settled);
5734
+ settled.then(() => {
5735
+ if (this.#uploadRemovals.get(id) === settled) this.#uploadRemovals.delete(id);
5736
+ });
5737
+ return removal;
5738
+ }
5739
+ /**
5740
+ * The session-wide lists: this tab's own stores, plus what other tabs
5741
+ * reported for the stores this tab has not attached.
5742
+ */
5743
+ #buildItemLists() {
5314
5744
  const allEntities = [];
5315
5745
  const allResolutions = [];
5316
- const referencedUploadIds = /* @__PURE__ */ new Set();
5317
- const nextProtectedKeysByAdapter = /* @__PURE__ */ new Map();
5318
5746
  let hasQueuedMutations = false;
5319
5747
  for (const contribution of this.#storeContributions.values()) {
5320
5748
  if (contribution.replayHead !== null) hasQueuedMutations = true;
5321
5749
  allEntities.push(...contribution.entities);
5322
5750
  allResolutions.push(...contribution.resolutions);
5751
+ }
5752
+ for (const [storeName, items] of this.#remoteStoreItems) {
5753
+ if (this.#storeContributions.has(storeName)) continue;
5754
+ if (items.hasQueuedMutations) hasQueuedMutations = true;
5755
+ allEntities.push(...items.entities);
5756
+ allResolutions.push(...items.resolutions);
5757
+ }
5758
+ return {
5759
+ entities: dedupeById(allEntities),
5760
+ resolutions: dedupeById(allResolutions),
5761
+ hasQueuedMutations
5762
+ };
5763
+ }
5764
+ #refreshAggregates(publish = true) {
5765
+ const referencedUploadIds = /* @__PURE__ */ new Set();
5766
+ const nextProtectedKeysByAdapter = /* @__PURE__ */ new Map();
5767
+ for (const contribution of this.#storeContributions.values()) {
5323
5768
  for (const uploadId of contribution.referencedUploadIds) referencedUploadIds.add(uploadId);
5324
5769
  const existing = nextProtectedKeysByAdapter.get(contribution.adapter) ?? [];
5325
5770
  existing.push(...contribution.protectedKeys);
5326
5771
  nextProtectedKeysByAdapter.set(contribution.adapter, existing);
5327
5772
  }
5328
- const entities = dedupeById(allEntities);
5329
- const resolutions = dedupeById(allResolutions);
5773
+ const { entities, resolutions, hasQueuedMutations } = this.#buildItemLists();
5330
5774
  for (const [adapter, keys] of nextProtectedKeysByAdapter) nextProtectedKeysByAdapter.set(adapter, [...new Set(keys)].sort());
5331
5775
  const nextProtectedKeys = [...new Set([...nextProtectedKeysByAdapter.values()].flat())].sort();
5332
- const adaptersToSync = new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]);
5776
+ const adaptersToSync = publish ? new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]) : /* @__PURE__ */ new Set();
5333
5777
  const debugLogger = this.#debugLogger;
5334
5778
  const sessionKey = this.sessionKey;
5335
5779
  const emitSyncProtectedKeysLog = (adapterKind, status, count, startTime, error) => {
@@ -5372,8 +5816,9 @@ var SessionOfflineCoordinator = class {
5372
5816
  });
5373
5817
  }
5374
5818
  }
5375
- this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
5819
+ if (publish) this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
5376
5820
  this.#referencedUploadIds = referencedUploadIds;
5821
+ for (const id of this.#stagedMutationUploadIds) if (referencedUploadIds.has(id)) this.#stagedMutationUploadIds.delete(id);
5377
5822
  if (!arraysEqual(this.#protectedKeys, nextProtectedKeys)) {
5378
5823
  this.#protectedKeys = nextProtectedKeys;
5379
5824
  setSessionProtectedKeysSnapshot(this.sessionKey, nextProtectedKeys);
@@ -5384,8 +5829,11 @@ var SessionOfflineCoordinator = class {
5384
5829
  hasQueuedMutations
5385
5830
  }, { action: "offline-session-aggregate" });
5386
5831
  this.#persistSessionSnapshot();
5387
- this.#publishSnapshot();
5388
- if (this.#uploadsConfig && this.#uploads.size > 0 && this.#storeContributions.size === this.#registrations.size) this.#cleanupUnusedMutationUploads();
5832
+ if (publish) this.#publishSnapshot();
5833
+ if (publish && this.#uploadsConfig && this.#storeContributions.size === this.#registrations.size) {
5834
+ if (this.#uploads.size > 0) this.#cleanupUnusedMutationUploads();
5835
+ this.#releasePendingUploads();
5836
+ }
5389
5837
  }
5390
5838
  #stampLocalStatus(status) {
5391
5839
  return {
@@ -5416,31 +5864,50 @@ var SessionOfflineCoordinator = class {
5416
5864
  #publishSnapshot() {
5417
5865
  if (this.#disposed) return;
5418
5866
  const status = this.store.state.status;
5867
+ const contributions = [...this.#storeContributions.values()];
5419
5868
  this.#browserTabs.coordinator.publish({
5420
5869
  kind: "offline-session-snapshot",
5421
5870
  status,
5422
- entities: this.store.state.entities,
5423
- resolutions: this.store.state.resolutions,
5871
+ storeNames: [...this.#storeContributions.keys()],
5872
+ entities: contributions.flatMap((contribution) => contribution.entities),
5873
+ resolutions: contributions.flatMap((contribution) => contribution.resolutions),
5424
5874
  uploads: this.store.state.uploads,
5425
- hasQueuedMutations: this.store.state.hasQueuedMutations
5875
+ queuedStoreNames: [...this.#storeContributions].filter(([, contribution]) => contribution.replayHead !== null).map(([storeName]) => storeName)
5426
5876
  });
5427
5877
  }
5428
5878
  #applyRemoteSnapshot(message) {
5429
- if (message.sentAt < this.#lastRemoteSnapshotAt) return;
5879
+ for (const storeName of message.storeNames) this.#remoteStoreItems.set(storeName, {
5880
+ entities: message.entities.filter((entity) => entity.storeName === storeName),
5881
+ resolutions: message.resolutions.filter((resolution) => resolution.storeName === storeName),
5882
+ hasQueuedMutations: message.queuedStoreNames.includes(storeName)
5883
+ });
5884
+ if (message.sentAt < this.#lastRemoteSnapshotAt) {
5885
+ this.store.setPartialState(this.#buildItemLists(), { action: "offline-session-remote" });
5886
+ this.#persistSessionSnapshot();
5887
+ return;
5888
+ }
5430
5889
  this.#lastRemoteSnapshotAt = message.sentAt;
5890
+ const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5891
+ const wasReplayBlocked = this.isReplayBlocked();
5892
+ const isDetectedOffline = this.#isNetworkEnabled() && (this.store.state.status.network.active && !this.#classifiedNetworkActive || !this.#browserReportsOnline());
5431
5893
  this.store.setState({
5432
- status: this.#restampHydratedStatus(message.status, {
5894
+ status: this.#restampHydratedStatus(isDetectedOffline ? {
5895
+ ...message.status,
5896
+ network: {
5897
+ ...message.status.network,
5898
+ active: true
5899
+ }
5900
+ } : message.status, {
5433
5901
  isLeader: this.isLeader(),
5434
5902
  updatedAt: Date.now()
5435
5903
  }),
5436
- entities: message.entities,
5437
- resolutions: message.resolutions,
5438
- uploads: message.uploads,
5439
- hasQueuedMutations: message.hasQueuedMutations
5904
+ ...this.#buildItemLists(),
5905
+ uploads: message.uploads
5440
5906
  }, { action: "offline-session-remote" });
5441
- this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5907
+ if (!isDetectedOffline) this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5442
5908
  this.#persistSessionSnapshot();
5443
5909
  this.#refreshLeadership();
5910
+ this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5444
5911
  }
5445
5912
  #shouldPersistSessionSnapshot() {
5446
5913
  return this.store.state.status.isOfflineMode || this.store.state.entities.length > 0 || this.store.state.resolutions.length > 0 || this.#protectedKeys.length > 0;
@@ -5798,12 +6265,26 @@ function useOfflineStoreEntities(args) {
5798
6265
  return useMemo(() => entities.map(stripInternalEntityPayload), [entities]);
5799
6266
  }
5800
6267
  /**
5801
- * React hook returning offline status for a session or inactive scope.
6268
+ * React hook returning the offline state of one item of a store, or `null`
6269
+ * when the item has no offline work. It reads the item through the keyed
6270
+ * lookup shared by all readers and keeps the previous result while the state
6271
+ * is unchanged, so a component re-renders only when its own item changes.
5802
6272
  */
5803
- function useOfflineStoreStatus(args) {
5804
- const coordinator = useSessionOfflineCoordinator(resolveOfflineSessionScope(args.sessionKey, args.inactiveScope), false);
5805
- const statusSelector = useCallback((state) => state.status, []);
5806
- return coordinator.store.useSelector(statusSelector);
6273
+ function useOfflineStoreItemState(sessionKey, inactiveScope, storeName, itemKey) {
6274
+ const coordinator = useSessionOfflineCoordinator(resolveOfflineSessionScope(sessionKey, inactiveScope), false);
6275
+ const itemStateSelector = useCallback((state) => storeName === void 0 || itemKey === null ? null : toItemOfflineState(getOfflineStoreEntityLookup(state.entities, storeName).get(itemKey)), [itemKey, storeName]);
6276
+ return coordinator.store.useSelector(itemStateSelector, { equalityFn: deepEqual });
6277
+ }
6278
+ /**
6279
+ * React hook returning whether a session or inactive scope is in offline mode.
6280
+ * Only this flag is selected, so the other status changes (e.g. `updatedAt`)
6281
+ * don't re-render the store hooks using it.
6282
+ */
6283
+ function useOfflineStoreIsOfflineMode(args) {
6284
+ return useSessionOfflineCoordinator(resolveOfflineSessionScope(args.sessionKey, args.inactiveScope), false).store.useSelector(selectIsOfflineMode);
6285
+ }
6286
+ function selectIsOfflineMode(state) {
6287
+ return state.status.isOfflineMode;
5807
6288
  }
5808
6289
  /**
5809
6290
  * React hook returning offline conflict/retry resolutions for a specific store in a session.
@@ -5820,6 +6301,12 @@ function useOfflineStoreResolutions(args) {
5820
6301
  //#region src/persistentStorage/offline/storeController.ts
5821
6302
  const DEFAULT_REPLAY_RETRY_MAX_FAILURES = 3;
5822
6303
  const DEFAULT_REPLAY_RETRY_INTERVAL_MS = 5e3;
6304
+ /**
6305
+ * Time given to a tab to learn about the queue changes of the tab that just
6306
+ * replayed, before it may replay itself.
6307
+ */
6308
+ const REPLAY_HANDOFF_SETTLE_MS = 500;
6309
+ const REPLAY_LOCK_UNAVAILABLE_WARNING = "[TSDF] navigator.locks is unavailable; with several tabs open, a queued offline mutation can be sent more than once.";
5823
6310
  const BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE = "Blocked by unresolved dependency";
5824
6311
  const compactOfflineEntitySchema = rc_object({
5825
6312
  k: rc_string,
@@ -5882,6 +6369,16 @@ function deserializeCompactOfflineEntityRef(value) {
5882
6369
  entityKind: fromCompactOfflineEntityKind(compactKind)
5883
6370
  };
5884
6371
  }
6372
+ /**
6373
+ * An entity with several queued mutations reports the most urgent state among
6374
+ * them, so it shows `syncing` while any of its mutations is being sent.
6375
+ */
6376
+ const entitySyncStatePriority = {
6377
+ pending: 0,
6378
+ syncing: 1,
6379
+ "needs-confirmation": 2,
6380
+ "resolution-required": 3
6381
+ };
5885
6382
  function toCompactOfflineEntitySyncState(state) {
5886
6383
  switch (state) {
5887
6384
  case "pending": return "p";
@@ -6009,12 +6506,16 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6009
6506
  let replayRetryTimer = null;
6010
6507
  let hydratedSessionKey = null;
6011
6508
  let hydratedPromise = null;
6509
+ let releaseReplayLock = null;
6510
+ let heldReplayLockName = null;
6511
+ let replayLockReleaseTimer = null;
6012
6512
  let nextQueueOrder = 0;
6013
6513
  const replayRetryMaxFailures = sessionConfig.replayRetry?.maxFailures ?? DEFAULT_REPLAY_RETRY_MAX_FAILURES;
6014
6514
  const replayRetryIntervalMs = sessionConfig.replayRetry?.intervalMs ?? DEFAULT_REPLAY_RETRY_INTERVAL_MS;
6015
6515
  const queueEntries = /* @__PURE__ */ new Map();
6016
6516
  const resolutions = /* @__PURE__ */ new Map();
6017
6517
  const countedReplayFailures = /* @__PURE__ */ new Map();
6518
+ const entryIdsFromAnotherTab = /* @__PURE__ */ new Set();
6018
6519
  const resolvedEntityRefBySerializedRef = /* @__PURE__ */ new Map();
6019
6520
  function getActiveMutationQueueingCause(current) {
6020
6521
  const status = current.session.getStatus();
@@ -6121,8 +6622,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6121
6622
  activeSession?.unregister?.();
6122
6623
  activeSession = null;
6123
6624
  resetReplayRetryState();
6625
+ if (!replayScheduled) releaseHeldReplayLock();
6124
6626
  resolvedEntityRefBySerializedRef.clear();
6125
6627
  queueEntries.clear();
6628
+ entryIdsFromAnotherTab.clear();
6126
6629
  resolutions.clear();
6127
6630
  nextQueueOrder = 0;
6128
6631
  hydratedSessionKey = null;
@@ -6280,6 +6783,36 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6280
6783
  },
6281
6784
  onOfflineCycle: () => {
6282
6785
  resetReplayRetryState();
6786
+ },
6787
+ onRemoteQueueEntryChange: (entryId, entry) => {
6788
+ applyRecordChangeFromAnotherTab(() => {
6789
+ if (entry) {
6790
+ nextQueueOrder = Math.max(nextQueueOrder, getQueueOrder(entry) + 1);
6791
+ if (!operations[entry.operation]) return;
6792
+ queueEntries.set(entryId, entry);
6793
+ entryIdsFromAnotherTab.add(entryId);
6794
+ return;
6795
+ }
6796
+ queueEntries.delete(entryId);
6797
+ entryIdsFromAnotherTab.delete(entryId);
6798
+ countedReplayFailures.delete(entryId);
6799
+ if (queueEntries.size === 0) clearReplayRetryTimer();
6800
+ });
6801
+ },
6802
+ onRemoteResolutionChange: (resolutionId, resolution) => {
6803
+ applyRecordChangeFromAnotherTab(() => {
6804
+ if (resolution && rc_parse(resolution, offlineResolutionRecordSchema).ok && operations[resolution.operation]) resolutions.set(resolutionId, resolution);
6805
+ else resolutions.delete(resolutionId);
6806
+ });
6807
+ },
6808
+ onRemoteWorkDiscarded: (discardedWork, removedEntityKeys) => {
6809
+ applyRecordChangeFromAnotherTab(() => {
6810
+ revalidateDiscardedWork(discardedWork, new Set(removedEntityKeys));
6811
+ });
6812
+ },
6813
+ onRemoteTempReconciled: (tempId, finalPayload) => {
6814
+ rememberResolvedEntityRef(tempId, finalPayload);
6815
+ storeAdapter.applyTempReconciliationFromAnotherTab?.(tempId, finalPayload);
6283
6816
  }
6284
6817
  }),
6285
6818
  queueNamespace,
@@ -6298,8 +6831,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6298
6831
  const [loadedQueueEntries, loadedResolutionEntries] = await Promise.all([loadNamespaceRecords(current.queueNamespace), loadNamespaceRecords(current.resolutionNamespace)]);
6299
6832
  if (!isActiveSessionState(current)) return;
6300
6833
  queueEntries.clear();
6834
+ entryIdsFromAnotherTab.clear();
6301
6835
  resolutions.clear();
6302
6836
  for (const entry of loadedQueueEntries.values()) queueEntries.set(entry.id, entry);
6837
+ const droppedResolutions = [];
6303
6838
  for (const resolution of loadedResolutionEntries.values()) {
6304
6839
  if (!rc_parse(resolution, offlineResolutionRecordSchema).ok) {
6305
6840
  current.resolutionNamespace.remove(resolution.id);
@@ -6307,6 +6842,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6307
6842
  }
6308
6843
  if (!operations[resolution.operation]) {
6309
6844
  current.resolutionNamespace.remove(resolution.id);
6845
+ droppedResolutions.push(resolution);
6310
6846
  continue;
6311
6847
  }
6312
6848
  resolutions.set(resolution.id, resolution);
@@ -6314,11 +6850,31 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6314
6850
  nextQueueOrder = getNextQueueOrder(loadedQueueEntries.values());
6315
6851
  hydratedSessionKey = current.sessionKey;
6316
6852
  refreshDerivedState(current);
6853
+ deleteOrphanedDependencyUploads(current, droppedResolutions);
6317
6854
  })().finally(() => {
6318
6855
  hydratedPromise = null;
6319
6856
  });
6320
6857
  return hydratedPromise;
6321
6858
  }
6859
+ /**
6860
+ * Applies to this tab's in-memory queue a record change made by another tab,
6861
+ * so the leader replays entries queued by any tab and every tab stops
6862
+ * showing (and can never replay) an entry another tab already replayed.
6863
+ */
6864
+ function applyRecordChangeFromAnotherTab(applyChange, changeSession = activeSession) {
6865
+ const current = activeSession;
6866
+ if (!current || current !== changeSession) return;
6867
+ if (hydratedPromise) {
6868
+ const applyAfterHydration = () => {
6869
+ applyRecordChangeFromAnotherTab(applyChange, current);
6870
+ };
6871
+ hydratedPromise.then(applyAfterHydration, applyAfterHydration);
6872
+ return;
6873
+ }
6874
+ if (hydratedSessionKey !== current.sessionKey) return;
6875
+ applyChange();
6876
+ refreshDerivedState(current, true);
6877
+ }
6322
6878
  function parseConflictPayloadForOperation(operationName, conflict) {
6323
6879
  const operation = operations[operationName];
6324
6880
  if (!operation) return Result.err(new OfflineResolutionConflictParseError({
@@ -6447,7 +7003,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6447
7003
  };
6448
7004
  }).sort(compareResolutionRecords));
6449
7005
  }
6450
- function refreshDerivedState(current) {
7006
+ function refreshDerivedState(current, isRemoteChange) {
6451
7007
  const session = current ?? ensureActiveSession();
6452
7008
  if (!session || !isActiveSessionState(session)) return;
6453
7009
  const sessionState = session;
@@ -6473,7 +7029,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6473
7029
  ...createEntityBase(ref),
6474
7030
  kind: reduceOfflineEntityKind(existing?.kind, operationKind),
6475
7031
  pendingMutations: (existing?.pendingMutations ?? 0) + 1,
6476
- syncState: existing?.syncState === "needs-confirmation" ? existing.syncState : entry.syncState,
7032
+ syncState: existing && entitySyncStatePriority[existing.syncState] > entitySyncStatePriority[entry.syncState] ? existing.syncState : entry.syncState,
6477
7033
  requiresResolution: existing?.requiresResolution ?? false,
6478
7034
  blockedByResolutionIds,
6479
7035
  childResolutionIds,
@@ -6549,8 +7105,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6549
7105
  queueOrder: getQueueOrder(nextReplayEntry),
6550
7106
  createdAt: nextReplayEntry.createdAt
6551
7107
  }
6552
- });
6553
- syncEntityNamespace(sessionState, entities);
7108
+ }, isRemoteChange);
7109
+ if (!isRemoteChange) syncEntityNamespace(sessionState, entities);
6554
7110
  }
6555
7111
  async function syncEntityNamespace(current, entities) {
6556
7112
  await current.entityNamespace.replaceAll(entities.map((entity) => ({
@@ -6612,6 +7168,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6612
7168
  if (entry.operation !== args.operationName) continue;
6613
7169
  if (entry.syncState !== "pending") continue;
6614
7170
  if (entry.attempts > 0) continue;
7171
+ if (entryIdsFromAnotherTab.has(entry.id)) continue;
6615
7172
  if (entry.tempIds && entry.tempIds.length > 0) continue;
6616
7173
  if (normalizeEntityRefs(entry.entityRefs) !== normalizedEntityRefs) continue;
6617
7174
  if (!candidate || compareQueueEntries(entry, candidate) < 0) candidate = entry;
@@ -6754,11 +7311,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6754
7311
  };
6755
7312
  }
6756
7313
  async function buildOperationExecuteContext(args) {
6757
- const [fileEntries, resolvedRefsById] = await Promise.all([Promise.all(Object.entries(args.entry.attachedUploadIds ?? {}).map(async ([uploadId, storedUploadId]) => {
7314
+ const fileEntries = await Promise.all(Object.entries(args.entry.attachedUploadIds ?? {}).map(async ([uploadId, storedUploadId]) => {
6758
7315
  const file = await args.current.session.loadUpload(storedUploadId);
6759
7316
  if (!file) throw new Error(`Missing offline upload "${storedUploadId}"`);
6760
7317
  return [uploadId, file];
6761
- })), args.current.session.resolveUploadIds(args.entry.dependencyUploadIds ?? [])]);
7318
+ }));
6762
7319
  const filesById = Object.fromEntries(fileEntries);
6763
7320
  return {
6764
7321
  ...buildOperationBaseContext({
@@ -6768,7 +7325,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6768
7325
  }),
6769
7326
  uploads: {
6770
7327
  filesById,
6771
- resolvedRefsById
7328
+ resolvedRefsById: args.resolvedRefsById
6772
7329
  }
6773
7330
  };
6774
7331
  }
@@ -6812,6 +7369,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6812
7369
  };
6813
7370
  resolutions.set(rewrittenResolution.id, rewrittenResolution);
6814
7371
  await args.current.resolutionNamespace.save(rewrittenResolution.id, rewrittenResolution);
7372
+ args.current.session.publishResolutionChange(storeName, rewrittenResolution.id, rewrittenResolution);
6815
7373
  entityRefRewrites.push({
6816
7374
  previousEntityRefs: resolution.entityRefs,
6817
7375
  nextEntityRefs: rewrittenResolution.entityRefs
@@ -6850,6 +7408,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6850
7408
  const tempId = args.tempIds[0];
6851
7409
  if (tempId === void 0) return;
6852
7410
  const reconciliation = tempEntity.reconcileServerEntity(args.result, tempId);
7411
+ args.current.session.publishTempReconciled(storeName, tempId, reconciliation.finalPayload);
6853
7412
  storeAdapter.reconcileTempEntity({
6854
7413
  operationName: args.operationName,
6855
7414
  input: args.input,
@@ -6877,6 +7436,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6877
7436
  }))
6878
7437
  });
6879
7438
  for (const reconciliation of reconciliations) {
7439
+ args.current.session.publishTempReconciled(storeName, reconciliation.tempId, reconciliation.finalPayload);
6880
7440
  storeAdapter.reconcileTempEntity({
6881
7441
  operationName: args.operationName,
6882
7442
  input: args.input,
@@ -6897,6 +7457,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6897
7457
  if (!session) return;
6898
7458
  if (isActiveSessionState(session)) queueEntries.set(entry.id, entry);
6899
7459
  await session.queueNamespace.save(entry.id, entry);
7460
+ session.session.publishQueueEntryChange(storeName, entry.id, entry);
6900
7461
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6901
7462
  }
6902
7463
  function runSuccessfulExecuteSync(args) {
@@ -6914,9 +7475,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6914
7475
  if (!session) return;
6915
7476
  if (isActiveSessionState(session)) {
6916
7477
  queueEntries.delete(entryId);
7478
+ entryIdsFromAnotherTab.delete(entryId);
6917
7479
  countedReplayFailures.delete(entryId);
6918
7480
  if (queueEntries.size === 0) clearReplayRetryTimer();
6919
7481
  }
7482
+ session.session.publishQueueEntryChange(storeName, entryId, null);
6920
7483
  await session.queueNamespace.remove(entryId);
6921
7484
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6922
7485
  }
@@ -6925,6 +7488,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6925
7488
  if (!session) return;
6926
7489
  if (isActiveSessionState(session)) resolutions.set(resolution.id, resolution);
6927
7490
  await session.resolutionNamespace.save(resolution.id, resolution);
7491
+ session.session.publishResolutionChange(storeName, resolution.id, resolution);
6928
7492
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6929
7493
  }
6930
7494
  async function removeResolution(resolutionId, current, skipRefresh) {
@@ -6932,8 +7496,24 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6932
7496
  if (!session) return;
6933
7497
  if (isActiveSessionState(session)) resolutions.delete(resolutionId);
6934
7498
  await session.resolutionNamespace.remove(resolutionId);
7499
+ session.session.publishResolutionChange(storeName, resolutionId, null);
6935
7500
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
6936
7501
  }
7502
+ /**
7503
+ * Deletes the staged uploads that work items depended on, after those items
7504
+ * left the queue for good (replayed, discarded, superseded, cancelled).
7505
+ *
7506
+ * Call it after `refreshDerivedState`, which reports the references that
7507
+ * remain: the session keeps every upload a queue entry or resolution record
7508
+ * of any store still needs. Attached uploads need no call, the session drops
7509
+ * them as soon as nothing references them.
7510
+ */
7511
+ async function deleteOrphanedDependencyUploads(current, removedWorkItems) {
7512
+ if (!isActiveSessionState(current)) return;
7513
+ const uploadIds = removedWorkItems.flatMap((workItem) => workItem.dependencyUploadIds ?? []);
7514
+ if (uploadIds.length === 0) return;
7515
+ await current.session.deleteUnreferencedUploads(uploadIds);
7516
+ }
6937
7517
  function collectTempCreateDescendants(args) {
6938
7518
  const sourcesByEntityKey = new Map([[args.parentEntityKey, {
6939
7519
  entityKey: args.parentEntityKey,
@@ -7000,6 +7580,33 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7000
7580
  pendingEntity: void 0
7001
7581
  });
7002
7582
  }
7583
+ /**
7584
+ * Removes the items a discarded `create` without temp entity (the app
7585
+ * generated the id on the client) added to the store, like the rollback of a
7586
+ * temp create, and adds their keys to `removedEntityKeys`. Like removed temp
7587
+ * entities, they are not refetched: the server most likely never got them.
7588
+ * If an earlier replay attempt did create one, the store's list
7589
+ * revalidation brings it back.
7590
+ */
7591
+ function rollbackClientIdCreatedItems(workItem, removedEntityKeys) {
7592
+ if (getOperationLifecycleKind(workItem.operation) !== "create" || isTempCreateOperation(workItem.operation)) return;
7593
+ for (const ref of workItem.entityRefs) {
7594
+ if (ref.entityKind !== "item") continue;
7595
+ const payload = getPayloadForEntityRef({
7596
+ operationName: workItem.operation,
7597
+ input: workItem.input,
7598
+ entityKey: ref.entityKey
7599
+ });
7600
+ if (payload === void 0) continue;
7601
+ storeAdapter.rollbackPendingEntity?.({
7602
+ operationName: workItem.operation,
7603
+ input: workItem.input,
7604
+ tempId: payload,
7605
+ pendingEntity: void 0
7606
+ });
7607
+ removedEntityKeys.add(ref.entityKey);
7608
+ }
7609
+ }
7003
7610
  async function promoteBlockedTempCreateDescendants(args) {
7004
7611
  const descendantQueueEntries = /* @__PURE__ */ new Map();
7005
7612
  for (const entityKey of getTempLifecycleEntityKeys(args.parentEntry)) {
@@ -7010,13 +7617,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7010
7617
  for (const entry of descendants.queueEntries) descendantQueueEntries.set(entry.id, entry);
7011
7618
  }
7012
7619
  for (const dependentEntry of descendantQueueEntries.values()) {
7013
- await removeEntry(dependentEntry.id, args.current, true);
7014
7620
  await persistResolution(buildRetryExhaustedResolutionRecord(args.current, dependentEntry, { message: BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE }), args.current, true);
7621
+ await removeEntry(dependentEntry.id, args.current, true);
7015
7622
  }
7016
7623
  }
7017
7624
  async function persistManualResolutionChain(args) {
7018
- await removeEntry(args.parentEntry.id, args.current, true);
7625
+ await args.current.session.markUploadsFailed(args.parentEntry.dependencyUploadIds ?? []);
7019
7626
  await persistResolution(args.parentResolution, args.current, true);
7627
+ await removeEntry(args.parentEntry.id, args.current, true);
7020
7628
  await promoteBlockedTempCreateDescendants({
7021
7629
  current: args.current,
7022
7630
  parentEntry: args.parentEntry,
@@ -7031,8 +7639,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7031
7639
  await removeResolution(args.resolution.id, args.current, true);
7032
7640
  const parentEntityKeys = getTempLifecycleEntityKeys(args.resolution);
7033
7641
  if (parentEntityKeys.length === 0) {
7642
+ const removedEntityKeys = /* @__PURE__ */ new Set();
7643
+ rollbackClientIdCreatedItems(args.resolution, removedEntityKeys);
7034
7644
  refreshDerivedState(args.current);
7035
- revalidateDiscardedWork([args.resolution], /* @__PURE__ */ new Set());
7645
+ revalidateDiscardedWorkInEveryTab(args.current, [args.resolution], removedEntityKeys);
7646
+ await deleteOrphanedDependencyUploads(args.current, [args.resolution]);
7036
7647
  return;
7037
7648
  }
7038
7649
  const descendantQueueEntries = /* @__PURE__ */ new Map();
@@ -7047,25 +7658,42 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7047
7658
  }
7048
7659
  for (const queueEntry of descendantQueueEntries.values()) await removeEntry(queueEntry.id, args.current, true);
7049
7660
  for (const resolution of descendantResolutions.values()) await removeResolution(resolution.id, args.current, true);
7050
- for (const queueEntry of descendantQueueEntries.values()) rollbackTempCreatePendingEntity(queueEntry);
7051
- for (const resolution of descendantResolutions.values()) rollbackTempCreatePendingEntity(resolution);
7661
+ const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7662
+ const removedEntityKeys = new Set(parentEntityKeys);
7663
+ for (const workItem of discardedWork) {
7664
+ rollbackTempCreatePendingEntity(workItem);
7665
+ rollbackClientIdCreatedItems(workItem, removedEntityKeys);
7666
+ for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedEntityKeys.add(entityKey);
7667
+ }
7052
7668
  rollbackTempCreatePendingEntity(args.resolution);
7053
7669
  refreshDerivedState(args.current);
7054
- const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7055
- const removedTempEntityKeys = new Set(parentEntityKeys);
7056
- for (const workItem of discardedWork) for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedTempEntityKeys.add(entityKey);
7057
- revalidateDiscardedWork(discardedWork, removedTempEntityKeys);
7670
+ revalidateDiscardedWorkInEveryTab(args.current, discardedWork, removedEntityKeys);
7671
+ await deleteOrphanedDependencyUploads(args.current, [args.resolution, ...discardedWork]);
7672
+ }
7673
+ /**
7674
+ * {@link revalidateDiscardedWork} in this tab and in the other tabs with the
7675
+ * store: each one may show the discarded optimistic changes.
7676
+ */
7677
+ function revalidateDiscardedWorkInEveryTab(current, discardedWork, removedEntityKeys) {
7678
+ revalidateDiscardedWork(discardedWork, removedEntityKeys);
7679
+ if (!discardedWork.some((workItem) => workItem.entityRefs.length > 0)) return;
7680
+ current.session.publishWorkDiscarded(storeName, discardedWork.map(({ operation, input, entityRefs }) => ({
7681
+ operation,
7682
+ input,
7683
+ entityRefs
7684
+ })), [...removedEntityKeys]);
7058
7685
  }
7059
7686
  /**
7060
7687
  * Refetches the entities discarded queued work referenced (its optimistic
7061
- * changes cannot be rolled back locally), except the removed temp entities
7062
- * and the entities other changes still wait for a decision on: a refetch
7688
+ * changes cannot be rolled back locally), except the entities the discard
7689
+ * removed (temp entities and items of discarded creations) and the
7690
+ * entities other changes still wait for a decision on: a refetch
7063
7691
  * would replace those changes. The recovery revalidation refetches them
7064
7692
  * once the last one is handled.
7065
7693
  */
7066
- function revalidateDiscardedWork(discardedWork, removedTempEntityKeys) {
7694
+ function revalidateDiscardedWork(discardedWork, removedEntityKeys) {
7067
7695
  const entities = [];
7068
- const skippedEntityKeys = new Set(removedTempEntityKeys);
7696
+ const skippedEntityKeys = new Set(removedEntityKeys);
7069
7697
  for (const resolution of resolutions.values()) for (const ref of resolution.entityRefs) skippedEntityKeys.add(ref.entityKey);
7070
7698
  for (const workItem of discardedWork) for (const ref of workItem.entityRefs) {
7071
7699
  if (skippedEntityKeys.has(ref.entityKey)) continue;
@@ -7139,6 +7767,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7139
7767
  input: validatedInput
7140
7768
  }),
7141
7769
  upload: args.upload,
7770
+ attachedUploadIds: args.attachedUploadIds,
7142
7771
  tempIds: args.tempIds,
7143
7772
  entityRefs: args.entityRefs
7144
7773
  };
@@ -7162,14 +7791,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7162
7791
  return result;
7163
7792
  }
7164
7793
  async function planPreparedMutation(args) {
7165
- const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue } = args;
7794
+ const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, attachedUploadIds, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue, replacedResolutionId } = args;
7166
7795
  const tempEntity = operation.tempEntity;
7167
7796
  const tempEntities = operation.tempEntities;
7168
7797
  if (operation.accumulation && operation.supersedes) throw new Error(`Offline operation "${operationName}" cannot configure accumulation and supersedes together`);
7169
7798
  if (tempEntity && tempEntities) throw new Error(`Offline operation "${operationName}" cannot configure tempEntity and tempEntities together`);
7170
7799
  if (storeType === "document" && (tempEntity || tempEntities)) throw new Error(`Document offline operation "${operationName}" does not support tempEntity or tempEntities`);
7171
7800
  if ((tempEntity || tempEntities) && "onSuccessExecute" in operation) throw new Error(`Offline operation "${operationName}" cannot configure onSuccessExecute when tempEntity or tempEntities is present`);
7172
- if (operation.accumulation && upload !== void 0) throw new Error(`Offline operation "${operationName}" cannot configure direct uploads together with accumulation`);
7801
+ if (operation.accumulation && (upload !== void 0 || attachedUploadIds !== void 0)) throw new Error(`Offline operation "${operationName}" cannot configure direct uploads together with accumulation`);
7173
7802
  const rawEntityRefs = getOperationRawEntityRefs(operation, operationName, validatedInput);
7174
7803
  const resolvedEntityRefs = resolveNormalizedRefs(rawEntityRefs);
7175
7804
  const hasTempLifecycle = tempEntity !== void 0 || tempEntities !== void 0;
@@ -7190,7 +7819,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7190
7819
  entityRefs,
7191
7820
  tempIds,
7192
7821
  entries: workingQueue.values(),
7193
- resolutionEntries: resolutions.values()
7822
+ resolutionEntries: replacedResolutionId ? [...resolutions.values()].filter((resolution) => resolution.id !== replacedResolutionId) : resolutions.values()
7194
7823
  });
7195
7824
  if (duplicateTempEntityKey !== null) throw new Error(`Offline operation "${operationName}" cannot queue temp entity "${duplicateTempEntityKey}" more than once while it is still pending`);
7196
7825
  }
@@ -7265,6 +7894,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7265
7894
  queueOrder,
7266
7895
  entityRefs,
7267
7896
  attachedUploads: upload,
7897
+ attachedUploadIds,
7268
7898
  dependencyUploadIds: dependencyUploadIds.length > 0 ? dependencyUploadIds : void 0,
7269
7899
  tempIds
7270
7900
  });
@@ -7278,7 +7908,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7278
7908
  removedEntries: supersededEntries
7279
7909
  };
7280
7910
  }
7281
- async function queuePreparedMutations(preparedMutation) {
7911
+ async function queuePreparedMutations(preparedMutation, replacedResolutionId) {
7282
7912
  const current = ensureActiveSession();
7283
7913
  if (!current || current.sessionKey !== preparedMutation.currentSessionKey) throw new OfflineSessionUnavailableError();
7284
7914
  const { queueOrders, nextQueueOrderValue } = previewQueueOrders(1);
@@ -7290,7 +7920,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7290
7920
  current,
7291
7921
  preparedMutation,
7292
7922
  queueOrder,
7293
- workingQueue: new Map(queueEntries)
7923
+ workingQueue: new Map(queueEntries),
7924
+ replacedResolutionId
7294
7925
  });
7295
7926
  while (plannedMutation.accumulatedEntry && queueEntries.get(plannedMutation.accumulatedEntry.id) !== plannedMutation.accumulatedEntry);
7296
7927
  const persistedMutations = [];
@@ -7314,7 +7945,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7314
7945
  return current.session.saveUpload({
7315
7946
  id: storedUploadId,
7316
7947
  file,
7317
- source: "mutation"
7948
+ source: "mutation",
7949
+ storeName
7318
7950
  });
7319
7951
  }));
7320
7952
  }
@@ -7367,6 +7999,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7367
7999
  throw error;
7368
8000
  }
7369
8001
  refreshDerivedState(current);
8002
+ if (plannedMutation.removedEntries.length > 0) await deleteOrphanedDependencyUploads(current, plannedMutation.removedEntries);
7370
8003
  await ensureReplayScheduled();
7371
8004
  }
7372
8005
  async function ensureReplayScheduled() {
@@ -7379,19 +8012,84 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7379
8012
  }
7380
8013
  if (replayScheduled || replayRetryTimer !== null || current.session.getStatus().isOfflineMode || current.session.isReplayBlocked() || !current.session.isLeader() || queueEntries.size === 0) return;
7381
8014
  replayScheduled = true;
8015
+ const replaySession = current;
7382
8016
  replayQueue.resultifyAdd(async () => {
7383
8017
  try {
7384
- await drainReplay();
8018
+ await acquireReplayLock(replaySession);
8019
+ try {
8020
+ await drainReplay(replaySession);
8021
+ } finally {
8022
+ if (replaySession.session.hasOtherTabs()) replayLockReleaseTimer = setTimeout(releaseHeldReplayLock, REPLAY_HANDOFF_SETTLE_MS);
8023
+ else releaseHeldReplayLock();
8024
+ }
7385
8025
  } finally {
7386
8026
  replayScheduled = false;
7387
8027
  if (getSortedEntries()[0]?.syncState === "needs-confirmation") scheduleReplayRetry();
8028
+ if (!isActiveSessionState(replaySession)) ensureReplayScheduled();
7388
8029
  }
7389
8030
  });
7390
8031
  }
7391
- async function drainReplay() {
8032
+ /**
8033
+ * Leadership is decided from tab presence messages, so for a moment two tabs
8034
+ * can both consider themselves the leader (e.g. while it moves to the tab
8035
+ * that just got focus). This cross-tab lock makes sure only one of them
8036
+ * replays this store's queue at a time.
8037
+ */
8038
+ async function acquireReplayLock(current) {
8039
+ const lockManager = getNavigatorLockManager();
8040
+ if (lockManager === null) {
8041
+ if (current.session.hasOtherTabs()) warnIfNavigatorLockUnavailable(REPLAY_LOCK_UNAVAILABLE_WARNING);
8042
+ return;
8043
+ }
8044
+ if (replayLockReleaseTimer !== null) {
8045
+ clearTimeout(replayLockReleaseTimer);
8046
+ replayLockReleaseTimer = null;
8047
+ }
8048
+ const lockName = `tsdf:offline-replay:${current.sessionKey}:${storeName}`;
8049
+ if (heldReplayLockName === lockName) return;
8050
+ releaseHeldReplayLock();
8051
+ if (await requestReplayLock(lockManager, lockName, true)) return;
8052
+ await requestReplayLock(lockManager, lockName, false);
8053
+ await new Promise((resolve) => {
8054
+ setTimeout(resolve, REPLAY_HANDOFF_SETTLE_MS);
8055
+ });
8056
+ }
8057
+ /**
8058
+ * Resolves `true` once this tab holds the lock (until
8059
+ * `releaseHeldReplayLock`), or `false` when `ifAvailable` is set and another
8060
+ * tab holds it.
8061
+ */
8062
+ function requestReplayLock(lockManager, lockName, ifAvailable) {
8063
+ return new Promise((onSettled) => {
8064
+ lockManager.request(lockName, { ifAvailable }, (lock) => {
8065
+ if (lock === null) {
8066
+ onSettled(false);
8067
+ return;
8068
+ }
8069
+ return new Promise((release) => {
8070
+ heldReplayLockName = lockName;
8071
+ releaseReplayLock = release;
8072
+ onSettled(true);
8073
+ });
8074
+ }).catch(() => {
8075
+ onSettled(true);
8076
+ });
8077
+ });
8078
+ }
8079
+ function releaseHeldReplayLock() {
8080
+ if (replayLockReleaseTimer !== null) {
8081
+ clearTimeout(replayLockReleaseTimer);
8082
+ replayLockReleaseTimer = null;
8083
+ }
8084
+ releaseReplayLock?.();
8085
+ releaseReplayLock = null;
8086
+ heldReplayLockName = null;
8087
+ }
8088
+ async function drainReplay(replaySession) {
7392
8089
  while (true) {
7393
8090
  const current = ensureActiveSession();
7394
8091
  if (!current) return;
8092
+ if (current.sessionKey !== replaySession.sessionKey) return;
7395
8093
  if (current.session.getStatus().isOfflineMode || current.session.isReplayBlocked() || !current.session.isLeader()) return;
7396
8094
  const nextEntry = getSortedEntries()[0];
7397
8095
  if (!nextEntry) return;
@@ -7404,6 +8102,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7404
8102
  const operation = operations[nextEntry.operation];
7405
8103
  if (!operation) {
7406
8104
  await removeEntry(nextEntry.id, current);
8105
+ deleteOrphanedDependencyUploads(current, [nextEntry]);
7407
8106
  continue;
7408
8107
  }
7409
8108
  const shouldCheckSkipBeforeRetry = nextEntry.syncState === "needs-confirmation";
@@ -7420,6 +8119,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7420
8119
  lastAttemptAt: Date.now()
7421
8120
  };
7422
8121
  await persistEntry(entryToUse, current);
8122
+ let failedUploadId;
7423
8123
  try {
7424
8124
  const replayCheckCtx = Boolean(shouldCheckSkipBeforeRetry && operation.shouldSkipSync || conflictHandling) ? {
7425
8125
  ...replayCheckBaseCtx,
@@ -7429,6 +8129,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7429
8129
  if (!replayCheckCtx) throw new Error("Replay check context was not prepared");
7430
8130
  if (await operation.shouldSkipSync(replayCheckCtx)) {
7431
8131
  await removeEntry(entryToUse.id, current);
8132
+ deleteOrphanedDependencyUploads(current, [entryToUse]);
7432
8133
  continue;
7433
8134
  }
7434
8135
  }
@@ -7454,9 +8155,15 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7454
8155
  });
7455
8156
  continue;
7456
8157
  }
8158
+ const dependencyUploads = await current.session.resolveReplayUploadIds(entryToUse.dependencyUploadIds ?? []);
8159
+ if (dependencyUploads.failedUploadId !== void 0) {
8160
+ failedUploadId = dependencyUploads.failedUploadId;
8161
+ throw dependencyUploads.error;
8162
+ }
7457
8163
  const executeContext = __LEGIT_CAST__(await buildOperationExecuteContext({
7458
8164
  current,
7459
- entry: entryToUse
8165
+ entry: entryToUse,
8166
+ resolvedRefsById: dependencyUploads.refs
7460
8167
  }));
7461
8168
  const result = await operation.execute(executeContext);
7462
8169
  if (entryToUse.tempIds) await reconcileTempEntitiesFromResult({
@@ -7475,20 +8182,18 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7475
8182
  });
7476
8183
  if (isPromise(successfulExecuteSync)) await successfulExecuteSync;
7477
8184
  refreshDerivedState(current);
8185
+ deleteOrphanedDependencyUploads(current, [entryToUse]);
7478
8186
  } catch (error) {
7479
8187
  const lastError = { message: unknownToError(error).message };
7480
- const classification = await current.session.classifyFailure(error, {
7481
- phase: "sync",
7482
- storeType,
7483
- operationName: entryToUse.operation,
7484
- sessionKey: current.sessionKey
7485
- });
7486
- const allowReplayRetry = classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, {
8188
+ const failureCtx = {
7487
8189
  phase: "sync",
7488
8190
  storeType,
7489
8191
  operationName: entryToUse.operation,
7490
8192
  sessionKey: current.sessionKey
7491
- }) : false;
8193
+ };
8194
+ if (failedUploadId !== void 0) failureCtx.uploadId = failedUploadId;
8195
+ const classification = await current.session.classifyFailure(error, failureCtx);
8196
+ const allowReplayRetry = classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, failureCtx) : false;
7492
8197
  if (classification !== "ignore" || current.session.getStatus().isOfflineMode) {
7493
8198
  entryToUse = {
7494
8199
  ...entryToUse,
@@ -7514,7 +8219,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7514
8219
  lastError,
7515
8220
  allowReplayRetry
7516
8221
  };
7517
- if (allowReplayRetry && nextFailures >= replayRetryMaxFailures) {
8222
+ if (allowReplayRetry && nextFailures >= replayRetryMaxFailures || failedUploadId !== void 0 && !allowReplayRetry) {
7518
8223
  await persistManualResolutionChain({
7519
8224
  current,
7520
8225
  parentEntry: entryToUse,
@@ -7573,6 +8278,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7573
8278
  if (!current) return [];
7574
8279
  return current.session.getEntities().filter((entity) => entity.storeName === storeName);
7575
8280
  }
8281
+ function getItemOfflineState(itemKey) {
8282
+ const current = ensureActiveSession();
8283
+ if (!current) return null;
8284
+ return toItemOfflineState(getOfflineStoreEntityLookup(current.session.store.state.entities, storeName).get(itemKey));
8285
+ }
7576
8286
  function getOfflineResolutions() {
7577
8287
  return buildDerivedResolutionRecords();
7578
8288
  }
@@ -7586,6 +8296,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7586
8296
  const operation = operations[operationName];
7587
8297
  if (!operation) {
7588
8298
  await removeResolution(resolutionId, current);
8299
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
7589
8300
  return;
7590
8301
  }
7591
8302
  if (isPersistedResolutionBlocked(resolutionRecord)) throw new Error("Cannot resolve a blocked offline resolution before its blocking dependencies are cleared");
@@ -7623,11 +8334,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7623
8334
  }) : null
7624
8335
  };
7625
8336
  });
7626
- for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
7627
8337
  for (const nextEntry of nextEntries) {
7628
8338
  if (!nextEntry.entry) continue;
7629
8339
  await persistEntry(nextEntry.entry, current, true);
7630
8340
  }
8341
+ for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
7631
8342
  storeAdapter.captureQueuedMutationOverlays?.({
7632
8343
  sessionKey: current.sessionKey,
7633
8344
  entityRefs: nextEntries.flatMap((nextEntry) => {
@@ -7635,6 +8346,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7635
8346
  })
7636
8347
  });
7637
8348
  refreshDerivedState(current);
8349
+ await deleteOrphanedDependencyUploads(current, nextEntries.flatMap((nextEntry) => nextEntry.entry ? [] : [nextEntry.resolution]));
7638
8350
  await ensureReplayScheduled();
7639
8351
  return;
7640
8352
  }
@@ -7648,14 +8360,15 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7648
8360
  return;
7649
8361
  }
7650
8362
  if (action === "requeue") {
7651
- const preparedMutation = prepareMutationWithSession(current, {
8363
+ await queuePreparedMutations(prepareMutationWithSession(current, {
7652
8364
  operation: operationName,
7653
8365
  input: resolutionAction?.input,
8366
+ attachedUploadIds: resolutionRecord.attachedUploadIds,
7654
8367
  tempIds: resolutionRecord.tempIds,
7655
8368
  entityRefs: resolutionRecord.entityRefs
7656
- });
7657
- await removeResolution(resolutionId, current, true);
7658
- await queuePreparedMutations(preparedMutation);
8369
+ }), resolutionId);
8370
+ await removeResolution(resolutionId, current);
8371
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
7659
8372
  return;
7660
8373
  }
7661
8374
  if (action === "commit") {
@@ -7669,6 +8382,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7669
8382
  result: committedResult
7670
8383
  });
7671
8384
  await removeResolution(resolutionId, current);
8385
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
7672
8386
  return;
7673
8387
  }
7674
8388
  throw new Error("Invalid offline resolution action");
@@ -7720,6 +8434,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7720
8434
  prepareForMutation,
7721
8435
  queueMutation,
7722
8436
  getOfflineEntities,
8437
+ getItemOfflineState,
7723
8438
  getOfflineResolutions,
7724
8439
  parseOfflineResolutionConflict: parseConflictPayloadForResolution,
7725
8440
  resolveOfflineResolution,
@@ -9579,34 +10294,6 @@ function useRegisterActiveKeys(keys, registerActiveKeys, touchKeys) {
9579
10294
  * ```
9580
10295
  */
9581
10296
  const IsOffScreenContext = createContext(false);
9582
- //#endregion
9583
- //#region src/persistentStorage/offline/entityMetadata.ts
9584
- function createOfflineEntityLookup(entities) {
9585
- const entitiesByKey = /* @__PURE__ */ new Map();
9586
- for (const entity of entities) entitiesByKey.set(entity.entityKey, entity);
9587
- return entitiesByKey;
9588
- }
9589
- function getIsPendingOfflineSync(entity) {
9590
- return !!entity && !entity.requiresResolution;
9591
- }
9592
- function hasPendingOfflineSync(entitiesByKey, entityKeys) {
9593
- for (const entityKey of entityKeys) if (getIsPendingOfflineSync(entitiesByKey.get(entityKey))) return true;
9594
- return false;
9595
- }
9596
- function shouldApplyOfflineOverlay(entity, overlay) {
9597
- return !!entity && (!entity.requiresResolution || entity.blockedResolutionCount > 0 || entity.childResolutionCount > 0 || typeof overlay === "object" && overlay !== null && "keepVisibleWhileResolutionRequired" in overlay && overlay.keepVisibleWhileResolutionRequired === true);
9598
- }
9599
- /**
9600
- * Batch-filters offline overlays to only include entries with a pending sync
9601
- * (entity exists and does not require resolution). Use this instead of calling
9602
- * {@link getActiveOfflineOverlay} per item when all active overlays are needed
9603
- * at once.
9604
- */
9605
- function filterActiveOfflineOverlays(entitiesByKey, overlays) {
9606
- const result = {};
9607
- for (const [entityKey, overlay] of Object.entries(overlays)) if (shouldApplyOfflineOverlay(entitiesByKey.get(entityKey), overlay)) result[entityKey] = overlay;
9608
- return result;
9609
- }
9610
10297
  function observeAutomaticFetchStatus(state, signature, currentStatus) {
9611
10298
  if (currentStatus === "success") {
9612
10299
  state.delete(signature);
@@ -9976,6 +10663,12 @@ function createCollectionStore(storeOptions) {
9976
10663
  finalPayload
9977
10664
  });
9978
10665
  },
10666
+ applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
10667
+ storeEvents.emit("tempEntityReconciled", {
10668
+ tempId: __LEGIT_CAST__(tempId),
10669
+ finalPayload: __LEGIT_CAST__(finalPayload)
10670
+ });
10671
+ },
9979
10672
  captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
9980
10673
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
9981
10674
  captureOfflineOverlays(entityRefs.flatMap((ref) => {
@@ -10346,7 +11039,7 @@ function createCollectionStore(storeOptions) {
10346
11039
  error: new AbortedStoreError()
10347
11040
  };
10348
11041
  let item = getItemFromStateOrPersistence(itemId, { materializeSyncState: true });
10349
- if (item?.error?.id === "offline") {
11042
+ if (isOfflineStoreError(item?.error)) {
10350
11043
  const hydratedItem = persistence?.readHydratedItem(itemId);
10351
11044
  if (hydratedItem?.data) {
10352
11045
  item = hydratedItem;
@@ -10834,6 +11527,8 @@ function createCollectionStore(storeOptions) {
10834
11527
  inactiveScope: id,
10835
11528
  storeName: resolvedPersistentStorageConfig ? id : void 0
10836
11529
  }),
11530
+ useItemOfflineState: (itemPayload) => useOfflineStoreItemState(getSessionKeyForRuntime(), id, resolvedPersistentStorageConfig ? id : void 0, itemPayload === false || itemPayload == null ? null : getItemKey(itemPayload)),
11531
+ getItemOfflineState: (itemPayload) => offlineController?.getItemOfflineState(getItemKey(itemPayload)) ?? null,
10837
11532
  useOfflineResolutions: () => useOfflineStoreResolutions({
10838
11533
  sessionKey: getSessionKeyForRuntime(),
10839
11534
  inactiveScope: id,
@@ -11239,7 +11934,6 @@ function createDocumentStore(storeOptions) {
11239
11934
  }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId, getStoreManagerAppVersion(storeManager));
11240
11935
  async function executeFetch(fetchCtx) {
11241
11936
  const currentStatus = store.state.status;
11242
- const wasLoadedBeforeFetch = currentStatus === "success";
11243
11937
  store.setPartialState({
11244
11938
  status: currentStatus === "success" ? "refetching" : "loading",
11245
11939
  error: null,
@@ -11249,7 +11943,7 @@ function createDocumentStore(storeOptions) {
11249
11943
  const result = await runOfflineAwareFetch(offlineController, () => fetchFn(fetchCtx.signal));
11250
11944
  if (!result.ok) {
11251
11945
  if (result.offline) {
11252
- store.setPartialState(wasLoadedBeforeFetch ? {
11946
+ store.setPartialState(store.state.data !== null ? {
11253
11947
  error: null,
11254
11948
  status: "success"
11255
11949
  } : {
@@ -14067,6 +14761,7 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14067
14761
  const { payload, limit, fields } = fetchPayload;
14068
14762
  const offset = !!offsetPagination && fetchPayload.type === "loadMore" && fetchPayload.offset > 0 ? Math.min(fetchPayload.offset, store.state.queries[queryKey]?.items.length ?? fetchPayload.offset) : fetchPayload.offset;
14069
14763
  const appendToExisting = !!offsetPagination && fetchPayload.type === "loadMore" && offset > 0;
14764
+ let failure = null;
14070
14765
  try {
14071
14766
  const useChunkedInvalidation = offsetPagination && !appendToExisting && limit > offsetPagination.maxInvalidationLimit;
14072
14767
  let allItems;
@@ -14087,7 +14782,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14087
14782
  signal: fetchCtx.signal,
14088
14783
  fields
14089
14784
  })).then((result) => {
14090
- if (!result.ok) throw result.offline ? offlineConnectivityError : result.error;
14785
+ if (!result.ok) {
14786
+ failure ??= result;
14787
+ throw result.offline ? offlineConnectivityError : result.error;
14788
+ }
14091
14789
  return result.data;
14092
14790
  })));
14093
14791
  const successResults = (await Promise.all(chunkResultPromises)).map((r) => r.unwrap());
@@ -14099,7 +14797,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14099
14797
  signal: fetchCtx.signal,
14100
14798
  fields
14101
14799
  }));
14102
- if (!fetchResult.ok) throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
14800
+ if (!fetchResult.ok) {
14801
+ failure = fetchResult;
14802
+ throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
14803
+ }
14103
14804
  const result = fetchResult.data;
14104
14805
  allItems = result.items;
14105
14806
  hasMore = result.hasMore;
@@ -14118,11 +14819,12 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14118
14819
  results.set(queryKey, false);
14119
14820
  return;
14120
14821
  }
14121
- const error = exception && typeof exception === "object" && "id" in exception && exception.id === "offline" ? offlineConnectivityError : normalizeStoreError(exception, errorNormalizer);
14822
+ const failedOffline = failure?.offline === true;
14823
+ const error = failedOffline ? offlineConnectivityError : normalizeStoreError(failure && !failure.offline ? failure.error : exception, errorNormalizer);
14122
14824
  store.produceState((draft) => {
14123
14825
  const query = draft.queries[queryKey];
14124
14826
  if (!query) return;
14125
- if (error === offlineConnectivityError && query.wasLoaded) {
14827
+ if (failedOffline && query.wasLoaded) {
14126
14828
  query.status = "success";
14127
14829
  query.error = null;
14128
14830
  } else {
@@ -14626,7 +15328,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
14626
15328
  hasMore: false
14627
15329
  };
14628
15330
  let query = getQueryStateByKey(queryKey);
14629
- if (query?.error?.id === "offline") {
15331
+ if (isOfflineStoreError(query?.error)) {
14630
15332
  const hydratedQuery = persistence?.readHydratedQuery(queryKey);
14631
15333
  if (hydratedQuery) {
14632
15334
  query = hydratedQuery;
@@ -14735,7 +15437,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
14735
15437
  error: new AbortedStoreError()
14736
15438
  };
14737
15439
  let itemState = readItemState(itemKey);
14738
- if (itemState?.itemQuery?.error?.id === "offline") {
15440
+ if (isOfflineStoreError(itemState?.itemQuery?.error)) {
14739
15441
  const hydratedItem = persistence?.readHydratedItem(itemKey);
14740
15442
  if (hydratedItem) {
14741
15443
  itemState = hydratedItem;
@@ -15972,7 +16674,7 @@ const cacheMissError = {
15972
16674
  id: "cache-miss",
15973
16675
  message: "Cache miss"
15974
16676
  };
15975
- function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, debouncePayload }, store, events, getItemKey, registerActiveItems, touchItems, scheduleAutomaticItemFetch, preloadItems, preloadItemsBeforePaint, readFallbackItemState, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays) {
16677
+ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, debouncePayload }, store, events, getItemKey, registerActiveItems, touchItems, scheduleAutomaticItemFetch, preloadItems, preloadItemsBeforePaint, readFallbackItemState, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays, isOfflineMode) {
15976
16678
  const isOffScreenFromContext = useContext(IsOffScreenContext);
15977
16679
  const queriesWithId = useMemo(() => {
15978
16680
  return items.map((itemProps) => {
@@ -16077,17 +16779,24 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16077
16779
  };
16078
16780
  }
16079
16781
  let status = itemQuery.status;
16782
+ let error = itemQuery.error;
16783
+ let hasMissingRequestedData = false;
16080
16784
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
16081
16785
  if (partialResources && Array.isArray(fields) && fields.length > 0 && (status === "success" || status === "refetching")) {
16082
16786
  if (getGenuinelyMissingRequestedFields(itemKey, {
16083
16787
  item: rawItemState,
16084
16788
  loadedFields
16085
- }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16789
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) {
16790
+ hasMissingRequestedData = true;
16791
+ status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16792
+ }
16086
16793
  } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
16087
16794
  const isIncomplete = !snapshotIsFullyLoaded(loadedFields, rawItemState, partialResources.inferFields) && !(itemsPendingFullInvalidation.has(itemKey) && hasCachedDataInState);
16088
16795
  const isStale = !isIncomplete && !snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, rawItemState, partialResources.inferFields, itemsPendingFullInvalidation);
16089
- if (isIncomplete) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16090
- else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
16796
+ if (isIncomplete) {
16797
+ hasMissingRequestedData = true;
16798
+ status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16799
+ } else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
16091
16800
  }
16092
16801
  if (partialResources && showPartialAsRefetching) {
16093
16802
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16098,12 +16807,20 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16098
16807
  }
16099
16808
  }
16100
16809
  if (partialResources && status === "refetching" && Array.isArray(fields) && fields.length > 0 && itemFieldInvalidationFields && !fields.some((f) => itemFieldInvalidationFields.includes(f))) status = "success";
16810
+ if (status === "refetching" && !hasMissingRequestedData && isOfflineMode && itemQuery.status === "success") {
16811
+ status = "success";
16812
+ loadingFields = void 0;
16813
+ }
16101
16814
  if (!returnRefetchingStatus && status === "refetching") status = "success";
16102
16815
  const shouldHideDataWhileLoading = status === "loading" && partialResources;
16816
+ if (hasMissingRequestedData && itemQuery.status === "success" && isOfflineMode) {
16817
+ status = "error";
16818
+ error = offlineConnectivityError;
16819
+ }
16103
16820
  return {
16104
16821
  itemStateKey: itemKey,
16105
16822
  status,
16106
- error: itemQuery.error,
16823
+ error,
16107
16824
  isLoading: status === "loading",
16108
16825
  ...loadingFields ? { loadingFields } : {},
16109
16826
  data: shouldHideDataWhileLoading ? selector ? selector(null, resolvedItemPayload) : __LEGIT_CAST__(null) : data,
@@ -16115,6 +16832,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16115
16832
  }, [
16116
16833
  activeOfflineOverlays,
16117
16834
  getUnresolvedPendingInvalidationFields,
16835
+ isOfflineMode,
16118
16836
  itemsPendingFullInvalidation,
16119
16837
  loadFromStateOnly,
16120
16838
  offlineEntitiesByKey,
@@ -16324,7 +17042,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16324
17042
  const hasMissingFields = missingFields.length > 0;
16325
17043
  const hasStaleInvalidatedFields = staleInvalidatedFields.length > 0;
16326
17044
  const shouldFetchForInvalidation = hasStaleInvalidatedFields && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
16327
- if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive) {
17045
+ if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive && !isOfflineMode) {
16328
17046
  shouldFetch = true;
16329
17047
  requiredFetch = true;
16330
17048
  fieldsToFetch = Array.from(new Set([...missingFields, ...staleInvalidatedFields]));
@@ -16335,7 +17053,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16335
17053
  const hasStaleFullInvalidation = hasUnresolvedFullInvalidation && !!item;
16336
17054
  const missingFullItem = !hasStaleFullInvalidation && (!snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation);
16337
17055
  const shouldFetchForInvalidation = !missingFullItem && (unresolvedPendingInvalidationFields.length > 0 || hasStaleFullInvalidation) && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
16338
- if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive) {
17056
+ if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive && !isOfflineMode) {
16339
17057
  shouldFetch = true;
16340
17058
  requiredFetch = true;
16341
17059
  fieldsToFetch = missingFullItem || hasStaleFullInvalidation ? "*" : unresolvedPendingInvalidationFields;
@@ -16366,6 +17084,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16366
17084
  fetchQueriesWithId,
16367
17085
  getUnresolvedPendingInvalidationFields,
16368
17086
  ignoreItemsInRefetchOnMount,
17087
+ isOfflineMode,
16369
17088
  itemHasMissingRequestedData,
16370
17089
  itemPendingInvalidationFields,
16371
17090
  itemsPendingFullInvalidation,
@@ -16639,6 +17358,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16639
17358
  let staleOrMissingRequestedFields;
16640
17359
  let hasAnyIncompleteItem = false;
16641
17360
  let hasAnyStaleItem = false;
17361
+ let hasMissingRequestedData = false;
16642
17362
  const statusCanBeOverridden = status === "success" || status === "refetching";
16643
17363
  if (partialResources && (statusCanBeOverridden || showPartialAsRefetching)) {
16644
17364
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16661,17 +17381,23 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16661
17381
  item: state.items[itemKey],
16662
17382
  loadedFields: state.itemLoadedFields[itemKey]
16663
17383
  }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0);
16664
- if (!hasCachedItemsInState) status = "loading";
16665
- else if (someItemMissingFieldDataInState) status = showPartialAsRefetching ? "refetching" : "loading";
16666
- else status = "refetching";
17384
+ if (!hasCachedItemsInState) {
17385
+ hasMissingRequestedData = true;
17386
+ status = "loading";
17387
+ } else if (someItemMissingFieldDataInState) {
17388
+ hasMissingRequestedData = true;
17389
+ status = showPartialAsRefetching ? "refetching" : "loading";
17390
+ } else status = "refetching";
16667
17391
  } else if (partialResources && fields === "*" && statusCanBeOverridden) {
16668
17392
  const hasAnyFieldInvalidation = effectiveQuery.query.items.some((itemKey) => {
16669
17393
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
16670
17394
  return !!itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0;
16671
17395
  });
16672
- if (hasAnyIncompleteItem) if (!hasCachedItemsInState) status = "loading";
16673
- else status = showPartialAsRefetching ? "refetching" : "loading";
16674
- else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
17396
+ if (hasAnyIncompleteItem) {
17397
+ hasMissingRequestedData = true;
17398
+ if (!hasCachedItemsInState) status = "loading";
17399
+ else status = showPartialAsRefetching ? "refetching" : "loading";
17400
+ } else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
16675
17401
  }
16676
17402
  if (partialResources && showPartialAsRefetching) {
16677
17403
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16682,15 +17408,25 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16682
17408
  if (pendingInvalidationFields.length > 0) loadingFields = pendingInvalidationFields;
16683
17409
  }
16684
17410
  }
17411
+ if (status === "refetching" && !hasMissingRequestedData && isOfflineMode && effectiveQuery.query.status === "success") {
17412
+ status = "success";
17413
+ loadingFields = void 0;
17414
+ }
16685
17415
  if (!returnRefetchingStatus && status === "refetching") status = "success";
17416
+ const shouldHideItemsWhileLoading = status === "loading" && partialResources;
17417
+ let error = effectiveQuery.query.error;
17418
+ if (hasMissingRequestedData && isOfflineMode && effectiveQuery.query.status === "success") {
17419
+ status = "error";
17420
+ error = offlineConnectivityError;
17421
+ }
16686
17422
  return {
16687
17423
  queryKey,
16688
17424
  status,
16689
- items: status === "loading" && partialResources ? [] : selectVisibleItems(visibleItemKeys, fields, (itemKey) => ({
17425
+ items: shouldHideItemsWhileLoading ? [] : selectVisibleItems(visibleItemKeys, fields, (itemKey) => ({
16690
17426
  item: state.items[itemKey],
16691
17427
  itemPayload: state.itemQueries[itemKey]?.payload
16692
17428
  })),
16693
- error: effectiveQuery.query.error,
17429
+ error,
16694
17430
  hasMore: isOfflineMode ? !!readFallbackQueryState && effectiveQuery.query.hasMore && isStrictItemKeyPrefix(effectiveQuery.query.items, readFallbackQueryState(queryKey)?.items ?? []) : effectiveQuery.query.hasMore,
16695
17431
  isDerived: effectiveQuery.isDerived,
16696
17432
  ...loadingFields ? { loadingFields } : {},
@@ -16922,7 +17658,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16922
17658
  requiredFetch = false;
16923
17659
  shouldFetch = !!queryState?.refetchOnMount;
16924
17660
  }
16925
- if (partialResources && !shouldFetch && effectiveQueryState) {
17661
+ if (partialResources && !shouldFetch && effectiveQueryState && !isOfflineMode) {
16926
17662
  const isQueryFetchInFlight = effectiveQueryState.status === "loading" || effectiveQueryState.status === "refetching" || effectiveQueryState.status === "loadingMore";
16927
17663
  if (Array.isArray(fields) && fields.length > 0) {
16928
17664
  let hasStaleOrMissingRequestedFields = false;
@@ -17014,6 +17750,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17014
17750
  itemsPendingFullInvalidation,
17015
17751
  getHighestPendingInvalidationPriority,
17016
17752
  getUnresolvedPendingInvalidationFields,
17753
+ isOfflineMode,
17017
17754
  queryItemsHaveMissingRequestedData,
17018
17755
  stickyDerivedQueryKeys
17019
17756
  ]);
@@ -17545,34 +18282,10 @@ function createListQueryStore(storeOptions) {
17545
18282
  deleteItemState(__LEGIT_CAST__(tempId));
17546
18283
  },
17547
18284
  reconcileTempEntity: ({ tempId, reconciliation }) => {
17548
- const tempPayload = __LEGIT_CAST__(tempId);
17549
- const tempItemKey = getItemKey(tempPayload);
17550
- const currentItem = getItemState(tempPayload);
17551
- const finalData = reconciliation.finalData !== void 0 ? __LEGIT_CAST__(reconciliation.finalData) : currentItem ?? void 0;
17552
- if (finalData === void 0) return;
17553
- const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
17554
- const finalItemKey = getItemKey(finalPayload);
17555
- const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
17556
- queryKey,
17557
- index: query.items.indexOf(tempItemKey)
17558
- })).filter(({ index }) => index !== -1);
17559
- deleteItemState(tempPayload);
17560
- addItemToState(finalPayload, finalData);
17561
- storeEvents.emit("tempEntityReconciled", {
17562
- tempId: tempPayload,
17563
- finalPayload
17564
- });
17565
- if (queryMemberships.length === 0) return;
17566
- store.produceState((draft) => {
17567
- for (const { queryKey, index } of queryMemberships) {
17568
- const query = notNullish(draft.queries[queryKey]);
17569
- const existingIndex = query.items.indexOf(finalItemKey);
17570
- if (existingIndex !== -1) query.items.splice(existingIndex, 1);
17571
- query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
17572
- }
17573
- }, { action: "offline-reconcile-temp-item" });
17574
- touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
17575
- for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
18285
+ reconcileOfflineTempItem(tempId, reconciliation.finalPayload, reconciliation.finalData);
18286
+ },
18287
+ applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
18288
+ if (!runWithoutBroadcast(() => reconcileOfflineTempItem(tempId, finalPayload, void 0))) emitTempItemReconciled(tempId, finalPayload);
17576
18289
  },
17577
18290
  captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
17578
18291
  if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
@@ -17669,6 +18382,44 @@ function createListQueryStore(storeOptions) {
17669
18382
  }
17670
18383
  for (const itemKey of itemsPendingFullInvalidation.keys()) if (store.state.itemLoadedFields[itemKey] === "*") itemsPendingFullInvalidation.delete(itemKey);
17671
18384
  }
18385
+ function emitTempItemReconciled(tempId, finalPayload) {
18386
+ storeEvents.emit("tempEntityReconciled", {
18387
+ tempId: __LEGIT_CAST__(tempId),
18388
+ finalPayload: __LEGIT_CAST__(finalPayload)
18389
+ });
18390
+ }
18391
+ /**
18392
+ * Replaces an offline temp item with its final one, in place in every query
18393
+ * that lists it. Returns `false` when there is no data for the final item.
18394
+ */
18395
+ function reconcileOfflineTempItem(tempId, finalPayloadValue, finalDataValue) {
18396
+ const tempPayload = __LEGIT_CAST__(tempId);
18397
+ const tempItemKey = getItemKey(tempPayload);
18398
+ const currentItem = getItemState(tempPayload);
18399
+ const finalData = finalDataValue !== void 0 ? __LEGIT_CAST__(finalDataValue) : currentItem ?? void 0;
18400
+ if (finalData === void 0) return false;
18401
+ const finalPayload = __LEGIT_CAST__(finalPayloadValue);
18402
+ const finalItemKey = getItemKey(finalPayload);
18403
+ const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
18404
+ queryKey,
18405
+ index: query.items.indexOf(tempItemKey)
18406
+ })).filter(({ index }) => index !== -1);
18407
+ deleteItemState(tempPayload);
18408
+ addItemToState(finalPayload, finalData);
18409
+ emitTempItemReconciled(tempId, finalPayloadValue);
18410
+ if (queryMemberships.length === 0) return true;
18411
+ store.produceState((draft) => {
18412
+ for (const { queryKey, index } of queryMemberships) {
18413
+ const query = notNullish(draft.queries[queryKey]);
18414
+ const existingIndex = query.items.indexOf(finalItemKey);
18415
+ if (existingIndex !== -1) query.items.splice(existingIndex, 1);
18416
+ query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
18417
+ }
18418
+ }, { action: "offline-reconcile-temp-item" });
18419
+ touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
18420
+ for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
18421
+ return true;
18422
+ }
17672
18423
  function cleanupItemStateMetadata(itemKey) {
17673
18424
  itemPendingInvalidationFields.delete(itemKey);
17674
18425
  itemsPendingFullInvalidation.delete(itemKey);
@@ -17906,16 +18657,24 @@ function createListQueryStore(storeOptions) {
17906
18657
  }
17907
18658
  applyRemoteQuerySnapshot(message);
17908
18659
  }
18660
+ /**
18661
+ * Reactive version of `isOfflineFetchModeActive` for the hooks: it re-renders
18662
+ * them when the session enters or leaves offline mode, and, unlike the
18663
+ * session status getter, reads nothing that writes state during render.
18664
+ */
18665
+ function useIsStoreOfflineMode() {
18666
+ return useOfflineStoreIsOfflineMode({
18667
+ sessionKey: getSessionKeyForRuntime(),
18668
+ inactiveScope: id
18669
+ }) || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
18670
+ }
17909
18671
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
17910
18672
  const offlineEntities = useOfflineStoreEntities({
17911
18673
  sessionKey: getSessionKeyForRuntime(),
17912
18674
  inactiveScope: id,
17913
18675
  storeName: resolvedPersistentStorageConfig ? id : void 0
17914
18676
  });
17915
- const isStoreOfflineMode = useOfflineStoreStatus({
17916
- sessionKey: getSessionKeyForRuntime(),
17917
- inactiveScope: id
17918
- }).isOfflineMode || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
18677
+ const isStoreOfflineMode = useIsStoreOfflineMode();
17919
18678
  const offlineOverlaysSelector = useCallback((state) => {
17920
18679
  return state;
17921
18680
  }, []);
@@ -17935,7 +18694,8 @@ function createListQueryStore(storeOptions) {
17935
18694
  return state;
17936
18695
  }, []);
17937
18696
  const offlineOverlays = offlineOverlayStore.useSelector(offlineOverlaysSelector);
17938
- return useMultipleItems(items, options, store, events, getItemKey, registerActiveStandaloneItems, touchItems, scheduleAutomaticItemFetch, persistence ? (payloads) => persistence.maybeHydrateItems(payloads.map((payload) => getItemKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence?.readHydratedItem, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays);
18697
+ const isStoreOfflineMode = useIsStoreOfflineMode();
18698
+ return useMultipleItems(items, options, store, events, getItemKey, registerActiveStandaloneItems, touchItems, scheduleAutomaticItemFetch, persistence ? (payloads) => persistence.maybeHydrateItems(payloads.map((payload) => getItemKey(payload))) : void 0, !!persistence && !persistence.hasAsyncPreload, persistence?.readHydratedItem, itemInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, fetchItemFn, partialResources, offlineEntities, offlineOverlays, isStoreOfflineMode);
17939
18699
  };
17940
18700
  const useItem$3 = function useItem$2(itemPayload, options = {}) {
17941
18701
  return useItem(itemPayload, options, store, scheduleItemFetch, useMultipleItems$3);
@@ -18183,6 +18943,8 @@ function createListQueryStore(storeOptions) {
18183
18943
  inactiveScope: id,
18184
18944
  storeName: resolvedPersistentStorageConfig ? id : void 0
18185
18945
  }),
18946
+ useItemOfflineState: (itemPayload) => useOfflineStoreItemState(getSessionKeyForRuntime(), id, resolvedPersistentStorageConfig ? id : void 0, itemPayload === false || itemPayload == null ? null : getItemKey(itemPayload)),
18947
+ getItemOfflineState: (itemPayload) => offlineController?.getItemOfflineState(getItemKey(itemPayload)) ?? null,
18186
18948
  useOfflineResolutions: () => useOfflineStoreResolutions({
18187
18949
  sessionKey: getSessionKeyForRuntime(),
18188
18950
  inactiveScope: id,
@@ -18259,7 +19021,8 @@ const storedUploadMetadataRecordSchema = rc_object({
18259
19021
  e: lastErrorSchema.optionalKey(),
18260
19022
  g: rc_number.optionalKey(),
18261
19023
  l: rc_number,
18262
- d: validPayloadSchema.optionalKey()
19024
+ d: validPayloadSchema.optionalKey(),
19025
+ s: rc_string.optionalKey()
18263
19026
  });
18264
19027
  function serializeStoredUploadMetadataRecord(record) {
18265
19028
  return JSON.stringify({
@@ -18277,7 +19040,8 @@ function serializeStoredUploadMetadataRecord(record) {
18277
19040
  ...record.lastError !== void 0 ? { e: record.lastError } : {},
18278
19041
  ...record.lastOnlineSessionStartedAt !== void 0 ? { g: record.lastOnlineSessionStartedAt } : {},
18279
19042
  l: record.lastModified,
18280
- ...record.metadata !== void 0 ? { d: record.metadata } : {}
19043
+ ...record.metadata !== void 0 ? { d: record.metadata } : {},
19044
+ ...record.storeName !== void 0 ? { s: record.storeName } : {}
18281
19045
  });
18282
19046
  }
18283
19047
  function parseStoredUploadMetadataRecord(raw) {
@@ -18298,7 +19062,8 @@ function parseStoredUploadMetadataRecord(raw) {
18298
19062
  ...compactRecord.e !== void 0 ? { lastError: compactRecord.e } : {},
18299
19063
  ...compactRecord.g !== void 0 ? { lastOnlineSessionStartedAt: compactRecord.g } : {},
18300
19064
  lastModified: compactRecord.l,
18301
- ...compactRecord.d !== void 0 ? { metadata: compactRecord.d } : {}
19065
+ ...compactRecord.d !== void 0 ? { metadata: compactRecord.d } : {},
19066
+ ...compactRecord.s !== void 0 ? { storeName: compactRecord.s } : {}
18302
19067
  };
18303
19068
  }
18304
19069
  var OpfsOfflineUploadDriver = class {
@@ -18396,4 +19161,4 @@ var OpfsOfflineUploadDriver = class {
18396
19161
  };
18397
19162
  const opfsOfflineUploadAdapter = new OpfsOfflineUploadDriver();
18398
19163
  //#endregion
18399
- export { GET_ALL, IsOffScreenContext, StoreFetchError, StoreMutationError, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
19164
+ export { GET_ALL, IsOffScreenContext, StoreFetchError, StoreMutationError, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, isOfflineStoreError, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };