tsdf 18.3.1 → 18.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as removeAsyncMaintenanceEntriesIfUnchanged, B as offlineResolutionRecordSchema, C as getDefaultMaxBytesForScope, D as isQuotaExceededError, E as getSerializedStringSize, F as defaultOfflineRuntimeConfig, G as warnIfNavigatorLockUnavailable, H as getSessionProtectedKeysSnapshot, I as getIsOfflineModeFromStatus, K as createCompactLocalStorageEntry, L as isModeEffectivelyActive, M as OfflineResolutionActionError, N as OfflineResolutionConflictParseError, O as keepEntriesWithinByteBudget, P as compactOfflineStatusSnapshotSchema, R as isOfflineModeStatusValue, S as resolveTSDFLogger, T as createTimedKeySet, U as setSessionProtectedKeysSnapshot, V as clearSessionProtectedKeysSnapshot, W as getNavigatorLockManager, Z as getPayloadRecordKey, _ as OFFLINE_SESSION_STATUS_STORE_NAME, a as estimateManagedAsyncStorageEntrySizeBytes, at as createIdleCleanupContext, b as emitTSDFDebugLog, c as getRemovableStoresAsyncStorage, d as readAsyncStorageNamespaceIndexStateUsingDriver, f as registerAsyncStartupStoreCleanup, g as parseAsyncStorageNamespaceKind, h as unregisterAsyncStartupStoreCleanup, it as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, j as serializeJsonForStorage, k as keepEntriesWithinByteBudgetDuringIdle, l as isAsyncStorageMetadataOfflineProtected, m as serializeProtectedRef$1, nt as parsePersistedAsyncNamespaceKind, o as getAsyncStorageMaintenanceRemoveBatchSize, ot as scheduleIdleCleanup, p as removeAsyncStorageNamespaceEntriesIfUnchanged, q as parseCompactLocalStorageEntry, r as buildPersistedStaticPolicy, rt as serializeProtectedRef, s as getProtectedKeysFromMetadata, st as scheduleInitialMaintenanceCleanup, u as mergeManagedAsyncStorageCustomMetadata, v as getOfflineSessionStatusStorageKey, w as createShouldIgnoreItemPredicate, x as getTSDFDebugTimingMs, y as logPersistentStorageQuotaCleanup, z as offlineItemEntityRefSchema } from "./asyncStorageAdapter-NrI38v4g.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-amwSWm_p.js";
1
+ import { A as removeAsyncMaintenanceEntriesIfUnchanged, B as offlineResolutionRecordSchema, C as getDefaultMaxBytesForScope, D as isQuotaExceededError, E as getSerializedStringSize, F as defaultOfflineRuntimeConfig, G as warnIfNavigatorLockUnavailable, H as getSessionProtectedKeysSnapshot, I as getIsOfflineModeFromStatus, K as createCompactLocalStorageEntry, L as isModeEffectivelyActive, M as OfflineResolutionActionError, N as OfflineResolutionConflictParseError, O as keepEntriesWithinByteBudget, P as compactOfflineStatusSnapshotSchema, R as isOfflineModeStatusValue, S as resolveTSDFLogger, T as createTimedKeySet, U as setSessionProtectedKeysSnapshot, V as clearSessionProtectedKeysSnapshot, W as getNavigatorLockManager, Z as getPayloadRecordKey, _ as OFFLINE_SESSION_STATUS_STORE_NAME, a as estimateManagedAsyncStorageEntrySizeBytes, at as createIdleCleanupContext, b as emitTSDFDebugLog, c as getRemovableStoresAsyncStorage, d as readAsyncStorageNamespaceIndexStateUsingDriver, f as registerAsyncStartupStoreCleanup, g as parseAsyncStorageNamespaceKind, h as unregisterAsyncStartupStoreCleanup, it as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, j as serializeJsonForStorage, k as keepEntriesWithinByteBudgetDuringIdle, l as isAsyncStorageMetadataOfflineProtected, m as serializeProtectedRef$1, nt as parsePersistedAsyncNamespaceKind, o as getAsyncStorageMaintenanceRemoveBatchSize, ot as scheduleIdleCleanup, p as removeAsyncStorageNamespaceEntriesIfUnchanged, q as parseCompactLocalStorageEntry, r as buildPersistedStaticPolicy, rt as serializeProtectedRef, s as getProtectedKeysFromMetadata, st as scheduleInitialMaintenanceCleanup, u as mergeManagedAsyncStorageCustomMetadata, v as getOfflineSessionStatusStorageKey, w as createShouldIgnoreItemPredicate, x as getTSDFDebugTimingMs, y as logPersistentStorageQuotaCleanup, z as offlineItemEntityRefSchema } from "./asyncStorageAdapter-D6IVBzPg.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-CwmY3O1r.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
5
  import { deepEqual } from "@ls-stack/utils/deepEqual";
@@ -7,7 +7,7 @@ import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
7
7
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
8
8
  import { evtmitter } from "evtmitter";
9
9
  import { klona } from "klona/json";
10
- import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
10
+ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
11
11
  import { Result, isResult, resultify, unknownToError } from "t-result";
12
12
  import { Store, useSubscribeToStore } from "t-state";
13
13
  import { useOnChange } from "@ls-stack/react-utils/useOnChange";
@@ -221,6 +221,7 @@ const compactListQueryLocalStorageEntrySchema = rc_object({
221
221
  o: rc_boolean.withFallback(false).optionalKey(),
222
222
  p: rc_unknown,
223
223
  h: rc_boolean.withFallback(false).optionalKey(),
224
+ m: rc_boolean.withFallback(false).optionalKey(),
224
225
  v: rc_number.optionalKey()
225
226
  });
226
227
  function isCompactListQueryLocalStorageKey(storageKey) {
@@ -238,6 +239,7 @@ function parseCompactListQueryLocalStorageEntry(raw) {
238
239
  offlineProtected: parsed.o === true,
239
240
  payload: parsed.p,
240
241
  hasMore: parsed.h === true,
242
+ ...parsed.m === true ? { missingItems: true } : {},
241
243
  version: parsed.v
242
244
  };
243
245
  }
@@ -247,6 +249,7 @@ function createCompactListQueryLocalStorageEntry(entry) {
247
249
  i: entry.items,
248
250
  p: entry.payload,
249
251
  ...entry.hasMore ? { h: true } : {},
252
+ ...entry.missingItems ? { m: true } : {},
250
253
  ...entry.offlineProtected ? { o: true } : {},
251
254
  ...entry.version !== void 0 ? { v: entry.version } : {}
252
255
  };
@@ -1285,7 +1288,8 @@ const persistedListQueryItemDataSchema = rc_object({
1285
1288
  const persistedListQueryDataSchema = rc_object({
1286
1289
  payload: rc_unknown,
1287
1290
  items: rc_array(rc_string),
1288
- hasMore: rc_boolean
1291
+ hasMore: rc_boolean,
1292
+ missingItems: rc_boolean.optional()
1289
1293
  });
1290
1294
  function normalizePersistentStorageDataSchema(schema) {
1291
1295
  if ("storeSchema" in schema) return {
@@ -1374,7 +1378,8 @@ function parsePersistedListQueryData(value, payloadSchema) {
1374
1378
  return {
1375
1379
  payload,
1376
1380
  items: result.value.items,
1377
- hasMore: result.value.hasMore
1381
+ hasMore: result.value.hasMore,
1382
+ ...result.value.missingItems ? { missingItems: true } : {}
1378
1383
  };
1379
1384
  }
1380
1385
  //#endregion
@@ -1937,8 +1942,9 @@ async function touchLocalStorageKeyWithThrottle(key, touch) {
1937
1942
  function getLocalStorageMaxAgeMs() {
1938
1943
  return getManagedLocalStorageRuntimeConfig().maxAgeMs;
1939
1944
  }
1940
- function isOfflineNetworkModeActiveSync(networkConfig) {
1941
- if (!networkConfig?.enabled) return false;
1945
+ function isOfflineNetworkModeActiveSync(sessionConfig) {
1946
+ const networkConfig = sessionConfig?.network;
1947
+ if (!networkConfig?.enabled || sessionConfig?.enabled?.() === false) return false;
1942
1948
  try {
1943
1949
  return (networkConfig.getIsOffline?.() ?? navigator.onLine === false) === true;
1944
1950
  } catch {
@@ -2209,6 +2215,7 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2209
2215
  const debugContext = import.meta.env.DEV ? createPersistentStorageDebugContext(adapter, config.storeName, config.debugLogger, config.entryPrefix, void 0, asyncNamespaceKind) : void 0;
2210
2216
  const effectiveAsyncValueCodec = asyncValueCodec ?? valueCodec;
2211
2217
  const localCodec = toLocalStorageValueCodec(valueCodec);
2218
+ const allowExpiredRead = UNSENT_OFFLINE_WORK_ENTRY_PREFIXES.includes(config.entryPrefix);
2212
2219
  const checkLocalStorageLeftovers = config.entryPrefix === "lq" ? null : createLocalStorageLeftoversCheck(config.storeName, (storageKey) => localPersistentStorage.getManifestKeyForPrefix(`${storageKey}.${config.entryPrefix}.`), onPersistentStorageError);
2213
2220
  scheduleAdapterExpirationScan(adapter);
2214
2221
  function getPrefix() {
@@ -2398,7 +2405,8 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
2398
2405
  const key = `${prefix}${entryKey}`;
2399
2406
  const entry = readStorageEntryFromLocalStorageSync(key, version, {
2400
2407
  metadata: "namespace",
2401
- namespacePrefix: prefix
2408
+ namespacePrefix: prefix,
2409
+ allowExpiredRead
2402
2410
  }, localCodec);
2403
2411
  if (import.meta.env.DEV) logPersistentStorageOperation(withPersistentStorageDebugKey(context, key), "read-entry", entry ? "success" : "miss", startTime, { touch: options.touch });
2404
2412
  return entry;
@@ -2909,7 +2917,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2909
2917
  }
2910
2918
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2911
2919
  async function clearAllSessionStorage(sessionKey) {
2912
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Daewq7dv.js");
2920
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-CBMshtkY.js");
2913
2921
  await Promise.all([
2914
2922
  clearSessionStorage(sessionKey, "local-sync"),
2915
2923
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -3093,7 +3101,7 @@ function setupCollectionPersistence(config, options = {}) {
3093
3101
  let knownPersistedKeys = null;
3094
3102
  let maintenanceManifestKey = null;
3095
3103
  function isOfflineNetworkActive() {
3096
- return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig().network);
3104
+ return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig());
3097
3105
  }
3098
3106
  function clearSaveTimer() {
3099
3107
  if (saveTimer !== null) {
@@ -3751,7 +3759,7 @@ async function runHybridOfflineMutation(controller, offline, upload, directMutat
3751
3759
  upload
3752
3760
  });
3753
3761
  if (prepared.initialAction === "queue") {
3754
- await prepared.queueMutation();
3762
+ await prepared.queueMutation(false);
3755
3763
  return { kind: "queued" };
3756
3764
  }
3757
3765
  try {
@@ -3763,7 +3771,7 @@ async function runHybridOfflineMutation(controller, offline, upload, directMutat
3763
3771
  };
3764
3772
  } catch (error) {
3765
3773
  if (!await prepared.classifyError(error)) throw error;
3766
- await prepared.queueMutation();
3774
+ await prepared.queueMutation(true);
3767
3775
  return { kind: "queued" };
3768
3776
  }
3769
3777
  }
@@ -3774,6 +3782,34 @@ function isOfflineResolutionRecordForStore(resolution, operations) {
3774
3782
  return resolution.operation in operations;
3775
3783
  }
3776
3784
  //#endregion
3785
+ //#region src/persistentStorage/offline/offlineStoreError.typeGuards.ts
3786
+ /**
3787
+ * Whether `error` is the error TSDF reports for a fetch that could not
3788
+ * complete because the offline session is in offline mode (the request is not
3789
+ * sent while offline).
3790
+ *
3791
+ * TSDF only exposes it on reads that have nothing cached to return
3792
+ * (`status: 'error'`): a document, item or query that is returning cached data
3793
+ * stays `success` with `error: null` while offline, so this is the state the
3794
+ * app has to explain to the user ("not available offline").
3795
+ *
3796
+ * Accepts the `error` of hooks and state getters and the `StoreFetchError` of
3797
+ * the `awaitFetch` methods. The error is matched by its whole shape, not only
3798
+ * by `id`, so an app error whose `errorNormalizer` happens to use the
3799
+ * `'offline'` id is not mistaken for it.
3800
+ *
3801
+ * @example
3802
+ * ```tsx
3803
+ * const { data, error } = store.useDocument();
3804
+ *
3805
+ * if (isOfflineStoreError(error)) return <NotAvailableOffline />;
3806
+ * if (error) return <ErrorMessage error={error} />;
3807
+ * ```
3808
+ */
3809
+ function isOfflineStoreError(error) {
3810
+ return !!error && error.id === "offline" && error.code === 0 && error.message === "Offline";
3811
+ }
3812
+ //#endregion
3777
3813
  //#region src/persistentStorage/offline/overlayStoreLifecycle.ts
3778
3814
  function rebindOfflineOverlayEntries(overlayStore, itemKeyRewrites, createReboundOverlay) {
3779
3815
  if (itemKeyRewrites.length === 0) return;
@@ -4260,6 +4296,50 @@ function parseSyncMessage(message, storeType) {
4260
4296
  }
4261
4297
  //#endregion
4262
4298
  //#region src/persistentStorage/offlineUploadsShared.ts
4299
+ /**
4300
+ * Parses an upload ref that came from storage or from another tab.
4301
+ *
4302
+ * @returns The parsed ref, or `undefined` when it does not match the schema.
4303
+ */
4304
+ function parseRestoredUploadRef(schema, resolvedRef) {
4305
+ if ("~standard" in schema) {
4306
+ const result = schema["~standard"].validate(resolvedRef);
4307
+ if (isPromise(result) || result.issues) return void 0;
4308
+ return result.value;
4309
+ }
4310
+ const result = schema.parse(resolvedRef);
4311
+ return result.ok ? result.value : void 0;
4312
+ }
4313
+ /**
4314
+ * Applies the outcome of {@link parseRestoredUploadRef} to a restored upload.
4315
+ *
4316
+ * An upload whose ref failed the schema goes back to `pending` without the
4317
+ * ref, so its staged file is uploaded again the next time the ref is needed.
4318
+ */
4319
+ function applyRestoredUploadRef(upload, parsedRef) {
4320
+ if (parsedRef !== void 0) return parsedRef === upload.resolvedRef ? upload : {
4321
+ ...upload,
4322
+ resolvedRef: parsedRef
4323
+ };
4324
+ const pendingUpload = {
4325
+ ...upload,
4326
+ state: "pending"
4327
+ };
4328
+ delete pendingUpload.resolvedRef;
4329
+ delete pendingUpload.progress;
4330
+ return pendingUpload;
4331
+ }
4332
+ function createEmptyUploadFile(status) {
4333
+ return {
4334
+ status,
4335
+ url: null,
4336
+ file: null,
4337
+ error: null
4338
+ };
4339
+ }
4340
+ const idleUploadFile = createEmptyUploadFile("idle");
4341
+ const loadingUploadFile = createEmptyUploadFile("loading");
4342
+ const missingUploadFile = createEmptyUploadFile("missing");
4263
4343
  function stripStoredUploadFile(record) {
4264
4344
  const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, storeName: _storeName, ...upload } = record;
4265
4345
  return upload;
@@ -4297,12 +4377,80 @@ function normalizeUploadFile(file, fallbackName) {
4297
4377
  });
4298
4378
  }
4299
4379
  //#endregion
4380
+ //#region src/persistentStorage/offline/entityMetadata.ts
4381
+ function createOfflineEntityLookup(entities) {
4382
+ const entitiesByKey = /* @__PURE__ */ new Map();
4383
+ for (const entity of entities) entitiesByKey.set(entity.entityKey, entity);
4384
+ return entitiesByKey;
4385
+ }
4386
+ const storeEntityLookupsBySessionEntities = /* @__PURE__ */ new WeakMap();
4387
+ const emptyEntityLookup = /* @__PURE__ */ new Map();
4388
+ /**
4389
+ * Entities of one store keyed by entity key, for a snapshot of the session's
4390
+ * entities (all stores). The lookups are built once per snapshot and shared by
4391
+ * every reader, so per-item readers (one per rendered row) do a keyed read
4392
+ * instead of each scanning the whole session on every change.
4393
+ */
4394
+ function getOfflineStoreEntityLookup(sessionEntities, storeName) {
4395
+ let lookupsByStoreName = storeEntityLookupsBySessionEntities.get(sessionEntities);
4396
+ if (!lookupsByStoreName) {
4397
+ lookupsByStoreName = /* @__PURE__ */ new Map();
4398
+ for (const entity of sessionEntities) {
4399
+ let lookup = lookupsByStoreName.get(entity.storeName);
4400
+ if (!lookup) {
4401
+ lookup = /* @__PURE__ */ new Map();
4402
+ lookupsByStoreName.set(entity.storeName, lookup);
4403
+ }
4404
+ lookup.set(entity.entityKey, entity);
4405
+ }
4406
+ storeEntityLookupsBySessionEntities.set(sessionEntities, lookupsByStoreName);
4407
+ }
4408
+ return lookupsByStoreName.get(storeName) ?? emptyEntityLookup;
4409
+ }
4410
+ /**
4411
+ * @param attemptedCreationEntityIds - ids of the session's temp entities
4412
+ * whose creation was already sent or waits for a manual resolution
4413
+ */
4414
+ function toItemOfflineState(entity, attemptedCreationEntityIds) {
4415
+ if (entity?.entityKind !== "item") return null;
4416
+ const isUnsentCreation = entity.tempId !== void 0;
4417
+ return {
4418
+ syncState: entity.syncState,
4419
+ pendingMutations: entity.pendingMutations,
4420
+ requiresResolution: entity.requiresResolution,
4421
+ isUnsentCreation,
4422
+ creationAttempted: isUnsentCreation && attemptedCreationEntityIds.includes(entity.id)
4423
+ };
4424
+ }
4425
+ function getIsPendingOfflineSync(entity) {
4426
+ return !!entity && !entity.requiresResolution;
4427
+ }
4428
+ function hasPendingOfflineSync(entitiesByKey, entityKeys) {
4429
+ for (const entityKey of entityKeys) if (getIsPendingOfflineSync(entitiesByKey.get(entityKey))) return true;
4430
+ return false;
4431
+ }
4432
+ function shouldApplyOfflineOverlay(entity, overlay) {
4433
+ return !!entity && (!entity.requiresResolution || entity.blockedResolutionCount > 0 || entity.childResolutionCount > 0 || typeof overlay === "object" && overlay !== null && "keepVisibleWhileResolutionRequired" in overlay && overlay.keepVisibleWhileResolutionRequired === true);
4434
+ }
4435
+ /**
4436
+ * Batch-filters offline overlays to only include entries with a pending sync
4437
+ * (entity exists and does not require resolution). Use this instead of calling
4438
+ * {@link getActiveOfflineOverlay} per item when all active overlays are needed
4439
+ * at once.
4440
+ */
4441
+ function filterActiveOfflineOverlays(entitiesByKey, overlays) {
4442
+ const result = {};
4443
+ for (const [entityKey, overlay] of Object.entries(overlays)) if (shouldApplyOfflineOverlay(entitiesByKey.get(entityKey), overlay)) result[entityKey] = overlay;
4444
+ return result;
4445
+ }
4446
+ //#endregion
4300
4447
  //#region src/persistentStorage/offline/sessionCoordinator.ts
4301
4448
  function stripInternalEntityPayload(entity) {
4302
4449
  if (!("payload" in entity)) return entity;
4303
4450
  const { payload: _payload, ...publicEntity } = entity;
4304
4451
  return publicEntity;
4305
4452
  }
4453
+ function noop() {}
4306
4454
  const DEFAULT_OUTAGE_RECOVERY_PROBE = {
4307
4455
  initialIntervalMs: 3e4,
4308
4456
  maxIntervalMs: 3e5,
@@ -4315,7 +4463,12 @@ const DEFAULT_NETWORK_RECOVERY_PROBE = {
4315
4463
  backoffMultiplier: 2,
4316
4464
  jitterRatio: .2
4317
4465
  };
4466
+ const DEFAULT_HEALTH_CHECK_TIMEOUT_MS = 1e4;
4318
4467
  const defaultGetIsOffline = () => !navigator.onLine;
4468
+ const INACTIVE_MODE = {
4469
+ enabled: false,
4470
+ active: false
4471
+ };
4319
4472
  const defaultStatusBySession = /* @__PURE__ */ new Map();
4320
4473
  const registry = /* @__PURE__ */ new Map();
4321
4474
  const uploadsConfigByOfflineSession = /* @__PURE__ */ new WeakMap();
@@ -4376,6 +4529,7 @@ function recheckIsSessionInOfflineMode(sessionKey) {
4376
4529
  const DEFAULT_UPLOAD_CONCURRENCY = 3;
4377
4530
  const OFFLINE_UPLOAD_RETENTION_MS = 10080 * 60 * 1e3;
4378
4531
  const OFFLINE_UPLOAD_RETENTION_STABLE_ONLINE_MS = 5e3;
4532
+ const UPLOAD_FILE_RELEASE_DELAY_MS = 1e3;
4379
4533
  function createDefaultStatus(sessionKey) {
4380
4534
  return {
4381
4535
  sessionKey,
@@ -4488,6 +4642,7 @@ function normalizeRecoveryProbe(config, defaults) {
4488
4642
  }
4489
4643
  function toCanonicalConfig(config) {
4490
4644
  return {
4645
+ isSessionEnabled: config?.enabled,
4491
4646
  hasNetworkConfig: config?.network !== void 0,
4492
4647
  networkEnabledByDefault: config?.network?.enabled ?? false,
4493
4648
  networkListenToBrowserEvents: config?.network?.listenToBrowserEvents ?? true,
@@ -4502,6 +4657,8 @@ function toCanonicalConfig(config) {
4502
4657
  },
4503
4658
  classifyFailure: config?.classifyFailure,
4504
4659
  classifyRetriableFailure: config?.classifyRetryableFailure,
4660
+ healthCheck: config?.healthCheck?.check,
4661
+ healthCheckTimeoutMs: config?.healthCheck?.timeoutMs ?? DEFAULT_HEALTH_CHECK_TIMEOUT_MS,
4505
4662
  outageRecoveryCheck: config?.outage?.recoveryCheck,
4506
4663
  outageRecoveryProbe: normalizeRecoveryProbe(config?.outage?.recoveryProbe, DEFAULT_OUTAGE_RECOVERY_PROBE)
4507
4664
  };
@@ -4520,16 +4677,10 @@ function sameProbeConfig(left, right) {
4520
4677
  }
4521
4678
  const persistedLocalSessionSnapshotSchema = rc_object({ d: compactOfflineStatusSnapshotSchema });
4522
4679
  function sameCanonicalConfig(left, right) {
4523
- return left.hasNetworkConfig === right.hasNetworkConfig && left.networkEnabledByDefault === right.networkEnabledByDefault && left.networkListenToBrowserEvents === right.networkListenToBrowserEvents && left.getIsOffline === right.getIsOffline && left.networkRecoveryCheck === right.networkRecoveryCheck && sameProbeConfig(left.networkRecoveryProbe, right.networkRecoveryProbe) && left.hasOutageConfig === right.hasOutageConfig && left.outageEnabledByDefault === right.outageEnabledByDefault && left.mutationQueueingByDefault.network === right.mutationQueueingByDefault.network && left.mutationQueueingByDefault.outage === right.mutationQueueingByDefault.outage && left.classifyFailure === right.classifyFailure && left.classifyRetriableFailure === right.classifyRetriableFailure && left.outageRecoveryCheck === right.outageRecoveryCheck && sameProbeConfig(left.outageRecoveryProbe, right.outageRecoveryProbe);
4680
+ return left.isSessionEnabled === right.isSessionEnabled && left.hasNetworkConfig === right.hasNetworkConfig && left.networkEnabledByDefault === right.networkEnabledByDefault && left.networkListenToBrowserEvents === right.networkListenToBrowserEvents && left.getIsOffline === right.getIsOffline && left.networkRecoveryCheck === right.networkRecoveryCheck && sameProbeConfig(left.networkRecoveryProbe, right.networkRecoveryProbe) && left.hasOutageConfig === right.hasOutageConfig && left.outageEnabledByDefault === right.outageEnabledByDefault && left.mutationQueueingByDefault.network === right.mutationQueueingByDefault.network && left.mutationQueueingByDefault.outage === right.mutationQueueingByDefault.outage && left.classifyFailure === right.classifyFailure && left.classifyRetriableFailure === right.classifyRetriableFailure && left.healthCheck === right.healthCheck && left.healthCheckTimeoutMs === right.healthCheckTimeoutMs && left.outageRecoveryCheck === right.outageRecoveryCheck && sameProbeConfig(left.outageRecoveryProbe, right.outageRecoveryProbe);
4524
4681
  }
4525
4682
  function sameUploadsConfig(left, right) {
4526
- return left?.adapter === right?.adapter && left?.upload === right?.upload && (left?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY) === (right?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY);
4527
- }
4528
- function eraseOfflineSession(session) {
4529
- return __LEGIT_CAST__(session);
4530
- }
4531
- function eraseUploadsConfig(uploads) {
4532
- return __LEGIT_CAST__(uploads);
4683
+ return left?.adapter === right?.adapter && left?.upload === right?.upload && left?.resolvedRefSchema === right?.resolvedRefSchema && (left?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY) === (right?.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY);
4533
4684
  }
4534
4685
  function castUploads(uploads) {
4535
4686
  return __LEGIT_CAST__(uploads);
@@ -4593,13 +4744,44 @@ var SessionOfflineCoordinator = class {
4593
4744
  #onPersistentStorageError;
4594
4745
  #uploadsConfig;
4595
4746
  #uploads = /* @__PURE__ */ new Map();
4747
+ #storedUploadsRestore = null;
4748
+ /**
4749
+ * Ids other tabs deleted while this tab's stored uploads were being listed,
4750
+ * so the list result can't bring them back. `null` outside the listing.
4751
+ */
4752
+ #uploadsRemovedWhileListing = null;
4596
4753
  #referencedUploadIds = /* @__PURE__ */ new Set();
4597
4754
  #uploadQueue;
4598
4755
  #uploadPromisesById = /* @__PURE__ */ new Map();
4756
+ /**
4757
+ * Validation outcome of the refs in the latest remote snapshot, so a ref
4758
+ * repeated across snapshots is parsed once per record version.
4759
+ */
4760
+ #remoteUploadRefValidations = /* @__PURE__ */ new Map();
4761
+ /**
4762
+ * Uploads released by work that left the queue but not deleted yet: a store
4763
+ * had not reported its references, or the upload was still being sent.
4764
+ */
4765
+ #pendingUploadReleases = /* @__PURE__ */ new Set();
4766
+ /**
4767
+ * Files attached to a mutation that is still being queued: saved before the
4768
+ * queue entry that references them, so unused-mutation-upload cleanup must
4769
+ * skip them until a store reports that reference.
4770
+ */
4771
+ #stagedMutationUploadIds = /* @__PURE__ */ new Set();
4772
+ /**
4773
+ * Refs of uploads that were uploaded and then released, so data still
4774
+ * holding their ids (optimistic or draft state) resolves to the same ref
4775
+ * for the rest of the session instead of failing.
4776
+ */
4777
+ #releasedUploadRefs = /* @__PURE__ */ new Map();
4778
+ /** Adapter removals in flight, awaited before the same id is read or saved. */
4779
+ #uploadRemovals = /* @__PURE__ */ new Map();
4599
4780
  #uploadCleanupTimer = null;
4600
4781
  #uploadOnlineSessionStartedAt = null;
4601
4782
  #uploadOnlineSessionStabilizationTimer = null;
4602
4783
  #uploadRetentionToken = 0;
4784
+ #uploadFiles = /* @__PURE__ */ new Map();
4603
4785
  #cleanupNetworkListeners = null;
4604
4786
  #canonicalConfig;
4605
4787
  #hasCanonicalConfig;
@@ -4611,7 +4793,16 @@ var SessionOfflineCoordinator = class {
4611
4793
  #recoveryTimer = null;
4612
4794
  #scheduledRecoveryMode = null;
4613
4795
  #recoveryAttempt = 0;
4796
+ /** Health check in flight, shared by every caller asking meanwhile. */
4797
+ #healthCheckInFlight = null;
4614
4798
  #classifiedNetworkActive = false;
4799
+ /** Last value of the session gate applied to the status. */
4800
+ #appliedSessionEnabled = true;
4801
+ /**
4802
+ * The gate reopened and no green cycle ran since: mutations queued before
4803
+ * it closed are waiting for one to be replayed.
4804
+ */
4805
+ #gateReopenedWithoutReplay = false;
4615
4806
  /** Tabs of this session that sent anything on the session channel. */
4616
4807
  #otherTabIds = /* @__PURE__ */ new Set();
4617
4808
  #networkEnabledOverride;
@@ -4654,6 +4845,7 @@ var SessionOfflineCoordinator = class {
4654
4845
  state: () => ({
4655
4846
  status: bootstrappedLocalSnapshot?.status ?? resolveDefaultStatus(sessionKey, { bootstrapStatusFromLocalStorage: shouldBootstrapFromStorage }),
4656
4847
  entities: [],
4848
+ attemptedCreationEntityIds: [],
4657
4849
  resolutions: [],
4658
4850
  uploads: [],
4659
4851
  hasQueuedMutations: false
@@ -4696,6 +4888,10 @@ var SessionOfflineCoordinator = class {
4696
4888
  this.#registrations.get(message.storeName)?.onRemoteWorkDiscarded?.(message.discardedWork, message.removedTempEntityKeys);
4697
4889
  return;
4698
4890
  }
4891
+ if (message.kind === "offline-uploads-removed") {
4892
+ this.#applyRemoteUploadsRemoved(message.ids, message.releasedRefs);
4893
+ return;
4894
+ }
4699
4895
  this.#applyRemoteSnapshot(message);
4700
4896
  }, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, (noteFocusChange) => {
4701
4897
  if (!isWindowAvailable()) return () => {};
@@ -4753,16 +4949,12 @@ var SessionOfflineCoordinator = class {
4753
4949
  }
4754
4950
  this.#protectedKeys = [...protectedKeys].sort();
4755
4951
  setSessionProtectedKeysSnapshot(this.sessionKey, this.#protectedKeys);
4756
- if (this.#uploadsConfig) try {
4757
- const uploads = await this.#uploadsConfig.adapter.list(this.sessionKey);
4952
+ if (this.#uploadsConfig) {
4953
+ await this.#restoreStoredUploads();
4758
4954
  if (hydrationToken === this.#hydrationToken) {
4759
- this.#uploads = new Map([...uploads.map((upload) => [upload.id, upload]), ...this.#uploads]);
4760
- this.#syncUploadsState();
4761
4955
  this.#scheduleUploadOnlineSessionStabilization();
4762
4956
  this.#refreshUploadRetention();
4763
4957
  }
4764
- } catch (error) {
4765
- this.#onPersistentStorageError?.(error);
4766
4958
  }
4767
4959
  this.#persistSessionSnapshot();
4768
4960
  }
@@ -4826,6 +5018,19 @@ var SessionOfflineCoordinator = class {
4826
5018
  this.#refreshAggregates(!isRemoteChange);
4827
5019
  if (replayHeadChanged) this.#notifyGreenCycle();
4828
5020
  }
5021
+ /**
5022
+ * Lets the other stores of the session drop the queued work they declared
5023
+ * as `cancelledWith` entities of `sourceStoreName` that will never exist on
5024
+ * the server.
5025
+ */
5026
+ async notifyTempEntitiesCancelled(sourceStoreName, cancelledEntityKeys, getEntityKey) {
5027
+ const pendingCleanups = [];
5028
+ for (const registration of this.#registrations.values()) {
5029
+ if (registration.storeName === sourceStoreName || !registration.onTempEntitiesCancelled) continue;
5030
+ pendingCleanups.push(registration.onTempEntitiesCancelled(sourceStoreName, cancelledEntityKeys, getEntityKey));
5031
+ }
5032
+ for (const result of await Promise.allSettled(pendingCleanups)) if (result.status === "rejected") this.#onPersistentStorageError?.(result.reason);
5033
+ }
4829
5034
  /** Tells the other tabs that this tab saved or removed (`null`) a queue entry. */
4830
5035
  publishQueueEntryChange(storeName, entryId, entry) {
4831
5036
  if (this.#disposed) return;
@@ -4857,13 +5062,13 @@ var SessionOfflineCoordinator = class {
4857
5062
  });
4858
5063
  }
4859
5064
  /** Tells the other tabs that this tab discarded queued work of a store. */
4860
- publishWorkDiscarded(storeName, discardedWork, removedTempEntityKeys) {
5065
+ publishWorkDiscarded(storeName, discardedWork, removedEntityKeys) {
4861
5066
  if (this.#disposed) return;
4862
5067
  this.#browserTabs.coordinator.publish({
4863
5068
  kind: "offline-work-discarded",
4864
5069
  storeName,
4865
5070
  discardedWork,
4866
- removedTempEntityKeys
5071
+ removedTempEntityKeys: removedEntityKeys
4867
5072
  });
4868
5073
  }
4869
5074
  /**
@@ -4922,7 +5127,12 @@ var SessionOfflineCoordinator = class {
4922
5127
  }
4923
5128
  async saveUpload(args) {
4924
5129
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
5130
+ await this.#restoreStoredUploads();
5131
+ await this.#waitForUploadRemoval(args.id);
4925
5132
  if (this.#uploadPromisesById.has(args.id)) throw new Error(`Cannot change upload "${args.id}" while it is queued or uploading`);
5133
+ this.#pendingUploadReleases.delete(args.id);
5134
+ this.#releasedUploadRefs.delete(args.id);
5135
+ if (args.source === "mutation") this.#stagedMutationUploadIds.add(args.id);
4926
5136
  const existing = this.#uploads.get(args.id);
4927
5137
  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);
4928
5138
  await this.#saveUploadRecord(nextRecord);
@@ -4940,14 +5150,89 @@ var SessionOfflineCoordinator = class {
4940
5150
  async loadUpload(id) {
4941
5151
  return (await this.#getUploadRecord(id))?.file ?? null;
4942
5152
  }
5153
+ /**
5154
+ * Latest staged file state for `id`. The first read (while rendering) starts
5155
+ * tracking the id, so a file the session already holds is returned right
5156
+ * away instead of going through a `loading` render.
5157
+ */
5158
+ getUploadFile(id) {
5159
+ return this.#getUploadFileEntry(id).value;
5160
+ }
5161
+ /**
5162
+ * Registers a consumer of the staged file for `id`. Consumers of the same id
5163
+ * share one entry, so the file is read and its object URL is created once.
5164
+ */
5165
+ subscribeUploadFile(id, onChange) {
5166
+ const entry = this.#getUploadFileEntry(id);
5167
+ const listener = () => onChange();
5168
+ clearTimeout(entry.releaseTimer);
5169
+ entry.listeners.add(listener);
5170
+ return () => {
5171
+ entry.listeners.delete(listener);
5172
+ if (entry.listeners.size === 0) this.#scheduleUploadFileRelease(id, entry);
5173
+ };
5174
+ }
4943
5175
  async deleteUpload(id) {
5176
+ await this.#restoreStoredUploads();
4944
5177
  if (this.#referencedUploadIds.has(id)) throw new Error(`Cannot delete upload "${id}" while it is still referenced`);
4945
5178
  if (this.#uploadPromisesById.has(id)) throw new Error(`Cannot delete upload "${id}" while it is uploading`);
4946
- if (!this.#uploadsConfig) return;
4947
- this.#uploads.delete(id);
4948
- await this.#uploadsConfig.adapter.remove(this.sessionKey, id);
4949
- this.#syncUploadsState();
4950
- this.#refreshUploadRetention();
5179
+ this.#stagedMutationUploadIds.delete(id);
5180
+ this.#releasedUploadRefs.delete(id);
5181
+ await this.#removeUploads([id]);
5182
+ }
5183
+ /**
5184
+ * Deletes the given staged uploads unless queued work still needs them.
5185
+ *
5186
+ * Store controllers call this after a queue entry or resolution record left
5187
+ * the queue for good (replayed, discarded, superseded, cancelled), passing
5188
+ * the uploads that work depended on. It must run after the store synced its
5189
+ * remaining references: they are aggregated session-wide, so an upload is
5190
+ * kept while a queue entry or resolution record of any store references it.
5191
+ *
5192
+ * Uploads no queued work referenced are never passed here: the app stages a
5193
+ * file before it queues the mutation, so being unreferenced alone must not
5194
+ * delete an upload. Those are left to `deleteUpload` and to the retention
5195
+ * window.
5196
+ */
5197
+ async deleteUnreferencedUploads(uploadIds) {
5198
+ if (this.#disposed) return;
5199
+ for (const id of uploadIds) this.#pendingUploadReleases.add(id);
5200
+ await this.#releasePendingUploads();
5201
+ }
5202
+ /**
5203
+ * Deletes the released uploads nothing references anymore. Runs again when
5204
+ * the last store reports its references and when a released upload that was
5205
+ * still being sent settles.
5206
+ */
5207
+ async #releasePendingUploads() {
5208
+ if (this.#pendingUploadReleases.size === 0) return;
5209
+ await this.#restoreStoredUploads();
5210
+ const cannotRelease = () => this.#disposed || this.#pendingUploadReleases.size === 0 || this.#storeContributions.size !== this.#registrations.size;
5211
+ if (cannotRelease()) return;
5212
+ const missingIds = [...this.#pendingUploadReleases].filter((id) => !this.#uploads.has(id) && !this.#uploadPromisesById.has(id));
5213
+ if (missingIds.length > 0) {
5214
+ try {
5215
+ await Promise.all(missingIds.map((id) => this.#getUploadRecord(id)));
5216
+ } catch (error) {
5217
+ this.#onPersistentStorageError?.(error);
5218
+ }
5219
+ if (cannotRelease()) return;
5220
+ }
5221
+ const removableIds = [];
5222
+ for (const id of this.#pendingUploadReleases) {
5223
+ if (this.#uploadPromisesById.has(id)) continue;
5224
+ this.#pendingUploadReleases.delete(id);
5225
+ const upload = this.#uploads.get(id);
5226
+ if (upload && !this.#referencedUploadIds.has(id)) {
5227
+ if (upload.state === "uploaded" && upload.resolvedRef !== void 0) this.#releasedUploadRefs.set(id, upload.resolvedRef);
5228
+ removableIds.push(id);
5229
+ }
5230
+ }
5231
+ try {
5232
+ await this.#removeUploads(removableIds);
5233
+ } catch (error) {
5234
+ this.#onPersistentStorageError?.(error);
5235
+ }
4951
5236
  }
4952
5237
  async resolveUploadIds(uploadIds) {
4953
5238
  const entries = await Promise.all(uploadIds.map(async (id) => {
@@ -4955,10 +5240,62 @@ var SessionOfflineCoordinator = class {
4955
5240
  }));
4956
5241
  return Object.fromEntries(entries);
4957
5242
  }
5243
+ /**
5244
+ * Resolves the dependency uploads of a replaying operation. A failure is
5245
+ * returned with the id of the upload that caused it instead of thrown, and
5246
+ * leaves that upload `pending`: replay classifies the failure first and
5247
+ * calls `markUploadFailed` only when it gives up on the operation.
5248
+ */
5249
+ async resolveReplayUploadIds(uploadIds) {
5250
+ const failures = [];
5251
+ const entries = await Promise.all(uploadIds.map(async (id) => {
5252
+ try {
5253
+ return [id, await this.#ensureUploadResolved(id, true)];
5254
+ } catch (error) {
5255
+ failures.push({
5256
+ failedUploadId: id,
5257
+ error
5258
+ });
5259
+ throw error;
5260
+ }
5261
+ })).catch(() => null);
5262
+ return failures[0] ?? { refs: Object.fromEntries(entries ?? []) };
5263
+ }
5264
+ /**
5265
+ * Marks the dependency uploads of an operation as `failed` after replay
5266
+ * moved it to manual resolution. Uploads still being sent are marked if
5267
+ * they fail too. Uploads that are not waiting on a failure (restarted or
5268
+ * uploaded meanwhile) are left untouched.
5269
+ *
5270
+ * Never rejects: the state only drives the upload UI, so a storage error is
5271
+ * reported instead of interrupting the replay.
5272
+ */
5273
+ async markUploadsFailed(ids) {
5274
+ const reportError = (error) => this.#onPersistentStorageError?.(error);
5275
+ const settledIds = [];
5276
+ for (const id of ids) {
5277
+ const inFlight = this.#uploadPromisesById.get(id);
5278
+ if (!inFlight) {
5279
+ settledIds.push(id);
5280
+ continue;
5281
+ }
5282
+ inFlight.catch(() => this.#markUploadFailed(id)).catch(reportError);
5283
+ }
5284
+ await Promise.all(settledIds.map((id) => this.#markUploadFailed(id).catch(reportError)));
5285
+ }
5286
+ async #markUploadFailed(id) {
5287
+ const record = this.#uploads.get(id);
5288
+ if (record?.state !== "pending" || !record.lastError) return;
5289
+ await this.#updateUploadState({
5290
+ id,
5291
+ state: "failed"
5292
+ });
5293
+ }
4958
5294
  isLeader() {
4959
5295
  return this.#browserTabs.priority.getPriorityRank() <= 1;
4960
5296
  }
4961
5297
  isReplayBlocked() {
5298
+ if (!this.#syncSessionGate()) return true;
4962
5299
  if (this.store.state.status.isOfflineMode) return true;
4963
5300
  const { network, outage } = this.store.state.status;
4964
5301
  if (!outage.enabled && outage.active) return true;
@@ -4987,11 +5324,46 @@ var SessionOfflineCoordinator = class {
4987
5324
  #browserReportsOnline() {
4988
5325
  return !isWindowAvailable() || navigator.onLine !== false;
4989
5326
  }
5327
+ /**
5328
+ * Reads the session gate (`offlineSession.enabled`): while it is closed the
5329
+ * session behaves as if no offline session existed.
5330
+ */
5331
+ #isSessionEnabled() {
5332
+ return this.#canonicalConfig.isSessionEnabled?.() ?? true;
5333
+ }
4990
5334
  #isNetworkEnabled() {
4991
- return this.#canonicalConfig.hasNetworkConfig && (this.#networkEnabledOverride ?? this.#canonicalConfig.networkEnabledByDefault);
5335
+ return this.#canonicalConfig.hasNetworkConfig && (this.#networkEnabledOverride ?? this.#canonicalConfig.networkEnabledByDefault) && this.#isSessionEnabled();
4992
5336
  }
4993
5337
  #isOutageEnabled() {
4994
- return this.#canonicalConfig.hasOutageConfig && (this.#outageEnabledOverride ?? this.#canonicalConfig.outageEnabledByDefault);
5338
+ return this.#canonicalConfig.hasOutageConfig && (this.#outageEnabledOverride ?? this.#canonicalConfig.outageEnabledByDefault) && this.#isSessionEnabled();
5339
+ }
5340
+ /**
5341
+ * Applies a flip of the session gate to the status: closing it leaves
5342
+ * offline mode, whatever the cause. Returns whether the gate is open.
5343
+ *
5344
+ * Every status write runs it first, so the flip is applied whichever path
5345
+ * notices it (a fetch, a recovery check, another tab's snapshot...).
5346
+ */
5347
+ #syncSessionGate() {
5348
+ const enabled = this.#isSessionEnabled();
5349
+ if (enabled === this.#appliedSessionEnabled) return enabled;
5350
+ this.#appliedSessionEnabled = enabled;
5351
+ if (enabled) this.#gateReopenedWithoutReplay = true;
5352
+ const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5353
+ this.#updateStatus((current) => ({
5354
+ ...current,
5355
+ network: {
5356
+ enabled: this.#isNetworkEnabled(),
5357
+ active: current.network.active
5358
+ },
5359
+ outage: {
5360
+ enabled: this.#isOutageEnabled(),
5361
+ active: current.outage.active
5362
+ }
5363
+ }));
5364
+ this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5365
+ this.#handleConnectivityChange(wasEffectivelyOffline, false);
5366
+ return enabled;
4995
5367
  }
4996
5368
  #assertModeIsConfigured(mode) {
4997
5369
  if (mode === "network" ? this.#canonicalConfig.hasNetworkConfig : this.#canonicalConfig.hasOutageConfig) return;
@@ -5081,7 +5453,7 @@ var SessionOfflineCoordinator = class {
5081
5453
  this.setNetworkActive(true, { classified: false });
5082
5454
  return true;
5083
5455
  }
5084
- if (this.#classifiedNetworkActive && this.#browserReportsOnline() && this.#canonicalConfig.networkRecoveryCheck) {
5456
+ if (this.#classifiedNetworkActive && this.#browserReportsOnline() && (this.#canonicalConfig.networkRecoveryCheck || this.#canonicalConfig.healthCheck)) {
5085
5457
  this.#syncRecoveryProbe();
5086
5458
  return true;
5087
5459
  }
@@ -5101,18 +5473,26 @@ var SessionOfflineCoordinator = class {
5101
5473
  });
5102
5474
  }
5103
5475
  async refreshNetworkState() {
5476
+ const sessionEnabled = this.#syncSessionGate();
5104
5477
  const token = ++this.#networkStateToken;
5478
+ if (!sessionEnabled) return false;
5105
5479
  const detectedOffline = this.#getCurrentOfflineState();
5106
- if (typeof detectedOffline === "boolean") return Promise.resolve(this.#applyRefreshedNetworkState(token, detectedOffline));
5107
- const resolvedDetectedOffline = await Promise.resolve(detectedOffline);
5108
- return this.#applyRefreshedNetworkState(token, resolvedDetectedOffline);
5480
+ const isOffline = this.#applyRefreshedNetworkState(token, typeof detectedOffline === "boolean" ? detectedOffline : await detectedOffline);
5481
+ if (this.#gateReopenedWithoutReplay && !isOffline && !this.isReplayBlocked()) this.#notifyGreenCycle();
5482
+ return isOffline;
5109
5483
  }
5110
5484
  setNetworkActive(active, options = {}) {
5485
+ this.#syncSessionGate();
5111
5486
  const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5112
5487
  const wasReplayBlocked = this.isReplayBlocked();
5113
5488
  const nextEnabled = this.#isNetworkEnabled();
5114
5489
  const nextActive = active;
5115
5490
  this.#classifiedNetworkActive = nextActive ? options.classified ?? this.#classifiedNetworkActive : false;
5491
+ const currentStatus = this.store.state.status;
5492
+ if (currentStatus.network.enabled === nextEnabled && currentStatus.network.active === nextActive && !(nextActive && options.recordFailureAt) && (options.recoveryCheckAt === void 0 || options.recoveryCheckAt === currentStatus.lastRecoveryCheckAt)) {
5493
+ this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5494
+ return;
5495
+ }
5116
5496
  this.#updateStatus((current) => ({
5117
5497
  ...current,
5118
5498
  network: {
@@ -5125,6 +5505,7 @@ var SessionOfflineCoordinator = class {
5125
5505
  this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5126
5506
  }
5127
5507
  setOutageActive(active, options = {}) {
5508
+ this.#syncSessionGate();
5128
5509
  const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5129
5510
  const wasReplayBlocked = this.isReplayBlocked();
5130
5511
  const nextEnabled = this.#isOutageEnabled();
@@ -5141,10 +5522,24 @@ var SessionOfflineCoordinator = class {
5141
5522
  this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
5142
5523
  }
5143
5524
  async classifyFailure(error, ctx) {
5144
- if (!this.#canonicalConfig.classifyFailure) return "ignore";
5145
- const token = this.getClassificationToken();
5146
- const result = await this.#canonicalConfig.classifyFailure(error, ctx);
5147
- if (!this.isCurrentClassificationToken(token)) return "ignore";
5525
+ if (!this.#canClassifyFailures()) return "ignore";
5526
+ const { classifyFailure, healthCheck } = this.#canonicalConfig;
5527
+ let result = "unknown";
5528
+ if (classifyFailure) {
5529
+ const token = this.getClassificationToken();
5530
+ result = await classifyFailure(error, ctx);
5531
+ if (!this.#canClassifyFailures()) return "ignore";
5532
+ if (result !== "unknown" && !this.isCurrentClassificationToken(token)) return "ignore";
5533
+ }
5534
+ if (result === "unknown") {
5535
+ if (!healthCheck) return "ignore";
5536
+ if (this.store.state.status.outage.active) return "outage";
5537
+ if (this.store.state.status.network.active) return "network";
5538
+ const health = await this.#checkHealth(healthCheck);
5539
+ if (health === null || health === "up") return "ignore";
5540
+ result = health === "outage" ? "outage" : "network";
5541
+ if (this.store.state.status[result].active) return result;
5542
+ }
5148
5543
  if (result === "outage") {
5149
5544
  if (!this.#isOutageEnabled() && !this.store.state.status.outage.active) return "ignore";
5150
5545
  this.setOutageActive(true);
@@ -5160,6 +5555,49 @@ var SessionOfflineCoordinator = class {
5160
5555
  }
5161
5556
  return "ignore";
5162
5557
  }
5558
+ /**
5559
+ * Runs `offlineSession.healthCheck`. While a check is in flight every
5560
+ * caller (failing requests, a recovery tick) gets that same call instead of
5561
+ * starting its own. A finished answer is not kept: an `up` reused for a
5562
+ * later failure could hide an outage that started right after it.
5563
+ *
5564
+ * Resolves with `null` when the check gave no answer (it threw or timed
5565
+ * out), which callers treat as "nothing learned".
5566
+ */
5567
+ #checkHealth(check) {
5568
+ this.#healthCheckInFlight ??= this.#requestHealth(check).finally(() => {
5569
+ this.#healthCheckInFlight = null;
5570
+ });
5571
+ return this.#healthCheckInFlight;
5572
+ }
5573
+ async #requestHealth(check) {
5574
+ const abortController = new AbortController();
5575
+ let timeout;
5576
+ try {
5577
+ return await Promise.race([check({
5578
+ sessionKey: this.sessionKey,
5579
+ signal: abortController.signal
5580
+ }), new Promise((resolve) => {
5581
+ timeout = setTimeout(() => {
5582
+ abortController.abort();
5583
+ resolve(null);
5584
+ }, this.#canonicalConfig.healthCheckTimeoutMs);
5585
+ })]);
5586
+ } catch {
5587
+ return null;
5588
+ } finally {
5589
+ clearTimeout(timeout);
5590
+ }
5591
+ }
5592
+ /**
5593
+ * Whether classifying a failure can change anything: the session gate has
5594
+ * to be open, with a mode enabled or still active (waiting to recover).
5595
+ */
5596
+ #canClassifyFailures() {
5597
+ if (!this.#isSessionEnabled()) return false;
5598
+ const { network, outage } = this.store.state.status;
5599
+ return network.active || outage.active || this.#isNetworkEnabled() || this.#isOutageEnabled();
5600
+ }
5163
5601
  async classifyRetriableFailure(error, ctx) {
5164
5602
  if (!this.#canonicalConfig.classifyRetriableFailure) return false;
5165
5603
  const token = this.getRetriableFailureToken();
@@ -5169,6 +5607,7 @@ var SessionOfflineCoordinator = class {
5169
5607
  }
5170
5608
  #notifyGreenCycle() {
5171
5609
  if (this.store.state.status.isOfflineMode || !this.isLeader()) return;
5610
+ this.#gateReopenedWithoutReplay = false;
5172
5611
  this.#refreshUploadRetention();
5173
5612
  for (const registration of this.#registrations.values()) registration.onGreenCycle?.();
5174
5613
  }
@@ -5205,21 +5644,148 @@ var SessionOfflineCoordinator = class {
5205
5644
  const initial = this.#getCurrentOfflineState();
5206
5645
  if (typeof initial === "boolean") this.setNetworkActive(initial, { classified: false });
5207
5646
  }
5647
+ /**
5648
+ * Lists the stored uploads into memory, once per coordinator. Every upload
5649
+ * operation that reads or changes a record waits for it first: the in-memory
5650
+ * map is only authoritative after the stored records are in it, and a list
5651
+ * result applied over newer changes would drop saved uploads and bring
5652
+ * deleted ones back.
5653
+ */
5654
+ #restoreStoredUploads() {
5655
+ if (!this.#uploadsConfig) return void 0;
5656
+ return this.#storedUploadsRestore ??= this.#listStoredUploads(this.#uploadsConfig);
5657
+ }
5658
+ async #listStoredUploads(uploadsConfig) {
5659
+ const removedWhileListing = /* @__PURE__ */ new Set();
5660
+ this.#uploadsRemovedWhileListing = removedWhileListing;
5661
+ try {
5662
+ const uploads = await uploadsConfig.adapter.list(this.sessionKey);
5663
+ this.#uploads = new Map([...uploads.filter((upload) => !removedWhileListing.has(upload.id)).map((upload) => [upload.id, this.#validateRestoredUpload(upload)]), ...this.#uploads]);
5664
+ this.#syncUploadsState();
5665
+ } catch (error) {
5666
+ this.#onPersistentStorageError?.(error);
5667
+ } finally {
5668
+ this.#uploadsRemovedWhileListing = null;
5669
+ }
5670
+ }
5208
5671
  async #getUploadRecord(id) {
5209
5672
  const existing = this.#uploads.get(id);
5210
5673
  if (existing) return existing;
5211
5674
  if (!this.#uploadsConfig) return null;
5675
+ await this.#restoreStoredUploads();
5676
+ const restored = this.#uploads.get(id);
5677
+ if (restored) return restored;
5678
+ await this.#waitForUploadRemoval(id);
5212
5679
  const loaded = await this.#uploadsConfig.adapter.load(this.sessionKey, id);
5213
5680
  const current = this.#uploads.get(id);
5214
5681
  if (current) return current;
5215
- if (loaded) {
5216
- this.#uploads.set(id, loaded);
5217
- this.#syncUploadsState();
5682
+ if (!loaded) return null;
5683
+ const validated = this.#validateRestoredUpload(loaded);
5684
+ this.#uploads.set(id, validated);
5685
+ this.#syncUploadsState();
5686
+ return validated;
5687
+ }
5688
+ /**
5689
+ * Checks the ref of an upload record restored from the adapter against the
5690
+ * configured `resolvedRefSchema`. Records enter `#uploads` once, so each
5691
+ * stored ref is parsed once.
5692
+ */
5693
+ #validateRestoredUpload(upload) {
5694
+ const schema = this.#uploadsConfig?.resolvedRefSchema;
5695
+ if (schema === void 0 || upload.resolvedRef === void 0) return upload;
5696
+ return applyRestoredUploadRef(upload, parseRestoredUploadRef(schema, upload.resolvedRef));
5697
+ }
5698
+ /** Checks the refs published by another tab against `resolvedRefSchema`. */
5699
+ #validateRemoteUploads(uploads) {
5700
+ const schema = this.#uploadsConfig?.resolvedRefSchema;
5701
+ if (schema === void 0) return uploads;
5702
+ const previousValidations = this.#remoteUploadRefValidations;
5703
+ this.#remoteUploadRefValidations = /* @__PURE__ */ new Map();
5704
+ return uploads.map((upload) => {
5705
+ if (upload.resolvedRef === void 0) return upload;
5706
+ const previous = previousValidations.get(upload.id);
5707
+ const validation = previous?.updatedAt === upload.updatedAt ? previous : {
5708
+ updatedAt: upload.updatedAt,
5709
+ parsedRef: parseRestoredUploadRef(schema, upload.resolvedRef)
5710
+ };
5711
+ this.#remoteUploadRefValidations.set(upload.id, validation);
5712
+ return applyRestoredUploadRef(upload, validation.parsedRef);
5713
+ });
5714
+ }
5715
+ #getUploadFileEntry(id) {
5716
+ const existingEntry = this.#uploadFiles.get(id);
5717
+ if (existingEntry) return existingEntry;
5718
+ const entry = {
5719
+ listeners: /* @__PURE__ */ new Set(),
5720
+ value: loadingUploadFile,
5721
+ releaseTimer: void 0
5722
+ };
5723
+ this.#uploadFiles.set(id, entry);
5724
+ if (!this.#syncUploadFile(id, entry)) this.#loadUploadFile(id, entry);
5725
+ this.#scheduleUploadFileRelease(id, entry);
5726
+ return entry;
5727
+ }
5728
+ /**
5729
+ * Drops the file and revokes its object URL once no hook has consumed the
5730
+ * entry for a moment. The delay keeps the URL stable across StrictMode's
5731
+ * effect replay and components that remount right away.
5732
+ */
5733
+ #scheduleUploadFileRelease(id, entry) {
5734
+ entry.releaseTimer = setTimeout(() => {
5735
+ this.#uploadFiles.delete(id);
5736
+ this.#setUploadFile(entry, loadingUploadFile);
5737
+ }, UPLOAD_FILE_RELEASE_DELAY_MS);
5738
+ }
5739
+ #setUploadFile(entry, value) {
5740
+ const previousUrl = entry.value.url;
5741
+ entry.value = value;
5742
+ if (previousUrl !== null) URL.revokeObjectURL(previousUrl);
5743
+ for (const listener of entry.listeners) listener();
5744
+ }
5745
+ /**
5746
+ * Aligns a consumed upload file with the in-memory upload records. Returns
5747
+ * `false` when the session holds no record for the id.
5748
+ */
5749
+ #syncUploadFile(id, entry) {
5750
+ const file = this.#uploads.get(id)?.file;
5751
+ if (!file) {
5752
+ if (entry.value.file) this.#setUploadFile(entry, missingUploadFile);
5753
+ return false;
5754
+ }
5755
+ if (entry.value.file !== file) this.#setUploadFile(entry, {
5756
+ status: "success",
5757
+ url: URL.createObjectURL(file),
5758
+ file,
5759
+ error: null
5760
+ });
5761
+ return true;
5762
+ }
5763
+ async #loadUploadFile(id, entry) {
5764
+ let failure;
5765
+ try {
5766
+ await this.#getUploadRecord(id);
5767
+ } catch (error) {
5768
+ failure = unknownToError(error);
5769
+ }
5770
+ if (this.#uploadFiles.get(id) !== entry || this.#syncUploadFile(id, entry) || entry.value.status !== "loading") return;
5771
+ this.#setUploadFile(entry, failure ? {
5772
+ status: "error",
5773
+ url: null,
5774
+ file: null,
5775
+ error: failure
5776
+ } : missingUploadFile);
5777
+ }
5778
+ async #waitForUploadRemoval(id) {
5779
+ let removal = this.#uploadRemovals.get(id);
5780
+ while (removal) {
5781
+ await removal;
5782
+ removal = this.#uploadRemovals.get(id);
5218
5783
  }
5219
- return loaded;
5220
5784
  }
5221
5785
  async #saveUploadRecord(record) {
5222
5786
  if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
5787
+ const removal = this.#uploadRemovals.get(record.id);
5788
+ if (removal) await removal;
5223
5789
  this.#uploads.set(record.id, record);
5224
5790
  await this.#uploadsConfig.adapter.save(this.sessionKey, record.id, record);
5225
5791
  this.#syncUploadsState();
@@ -5295,7 +5861,11 @@ var SessionOfflineCoordinator = class {
5295
5861
  const expiredIdSet = new Set(expiredIds);
5296
5862
  if (expiredIdSet.size > 0) {
5297
5863
  for (const id of expiredIdSet) this.#uploads.delete(id);
5298
- await Promise.all(expiredIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
5864
+ try {
5865
+ await Promise.all(expiredIds.map((id) => this.#removeStoredUpload(uploadsConfig, id)));
5866
+ } finally {
5867
+ this.#publishUploadsRemoved(expiredIds);
5868
+ }
5299
5869
  didChange = true;
5300
5870
  }
5301
5871
  if (token !== this.#uploadRetentionToken || this.#disposed) return;
@@ -5314,9 +5884,10 @@ var SessionOfflineCoordinator = class {
5314
5884
  const uploads = [...this.#uploads.values()].map(stripStoredUploadFile).sort((left, right) => left.id.localeCompare(right.id));
5315
5885
  this.store.setPartialState({ uploads }, { action: "offline-session-uploads" });
5316
5886
  this.#publishSnapshot();
5887
+ for (const [id, entry] of this.#uploadFiles) this.#syncUploadFile(id, entry);
5317
5888
  }
5318
5889
  #buildNextUploadRecord(current, args) {
5319
- return {
5890
+ const nextRecord = {
5320
5891
  ...current,
5321
5892
  state: args.state,
5322
5893
  updatedAt: Date.now(),
@@ -5324,6 +5895,8 @@ var SessionOfflineCoordinator = class {
5324
5895
  ...args.progress !== void 0 ? { progress: args.progress } : {},
5325
5896
  ...args.lastError !== void 0 ? { lastError: args.lastError } : {}
5326
5897
  };
5898
+ if (args.state === "uploaded") delete nextRecord.lastError;
5899
+ return nextRecord;
5327
5900
  }
5328
5901
  async #updateUploadState(args) {
5329
5902
  const current = await this.#getUploadRecord(args.id);
@@ -5335,9 +5908,13 @@ var SessionOfflineCoordinator = class {
5335
5908
  } else await this.#saveUploadRecord(nextRecord);
5336
5909
  return nextRecord;
5337
5910
  }
5338
- async #ensureUploadResolved(id) {
5911
+ async #ensureUploadResolved(id, forReplay = false) {
5339
5912
  const existingRecord = await this.#getUploadRecord(id);
5340
- if (!existingRecord) throw new Error(`Unknown offline upload "${id}"`);
5913
+ if (!existingRecord) {
5914
+ const releasedRef = this.#releasedUploadRefs.get(id);
5915
+ if (releasedRef !== void 0) return releasedRef;
5916
+ throw new Error(`Unknown offline upload "${id}"`);
5917
+ }
5341
5918
  if (existingRecord.state === "uploaded" && existingRecord.resolvedRef !== void 0) return existingRecord.resolvedRef;
5342
5919
  const existingPromise = this.#uploadPromisesById.get(id);
5343
5920
  if (existingPromise) return existingPromise;
@@ -5345,7 +5922,11 @@ var SessionOfflineCoordinator = class {
5345
5922
  const uploadsConfig = this.#uploadsConfig;
5346
5923
  const uploadPromise = this.#uploadQueue.resultifyAdd(async () => {
5347
5924
  const queuedRecord = await this.#getUploadRecord(id);
5348
- if (!queuedRecord) throw new Error(`Unknown offline upload "${id}"`);
5925
+ if (!queuedRecord) {
5926
+ const releasedRef = this.#releasedUploadRefs.get(id);
5927
+ if (releasedRef !== void 0) return releasedRef;
5928
+ throw new Error(`Unknown offline upload "${id}"`);
5929
+ }
5349
5930
  if (queuedRecord.state === "uploaded" && queuedRecord.resolvedRef !== void 0) return queuedRecord.resolvedRef;
5350
5931
  const file = queuedRecord.file;
5351
5932
  await this.#updateUploadState({
@@ -5386,7 +5967,7 @@ var SessionOfflineCoordinator = class {
5386
5967
  } catch (error) {
5387
5968
  await this.#updateUploadState({
5388
5969
  id,
5389
- state: "failed",
5970
+ state: forReplay ? "pending" : "failed",
5390
5971
  lastError: { message: error instanceof Error ? error.message : "Upload failed" }
5391
5972
  });
5392
5973
  throw error;
@@ -5396,41 +5977,100 @@ var SessionOfflineCoordinator = class {
5396
5977
  return result.value;
5397
5978
  }).finally(() => {
5398
5979
  this.#uploadPromisesById.delete(id);
5980
+ if (this.#pendingUploadReleases.has(id)) this.#releasePendingUploads();
5399
5981
  });
5400
5982
  this.#uploadPromisesById.set(id, uploadPromise);
5401
5983
  return uploadPromise;
5402
5984
  }
5403
5985
  async #cleanupUnusedMutationUploads() {
5986
+ 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)));
5987
+ }
5988
+ async #removeUploads(ids) {
5404
5989
  const uploadsConfig = this.#uploadsConfig;
5405
- if (!uploadsConfig) return;
5406
- const removableIds = [...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));
5407
- if (removableIds.length === 0) return;
5408
- for (const id of removableIds) this.#uploads.delete(id);
5409
- await Promise.all(removableIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
5410
- this.#syncUploadsState();
5990
+ if (!uploadsConfig || ids.length === 0) return;
5991
+ try {
5992
+ await Promise.all(ids.map((id) => {
5993
+ this.#uploads.delete(id);
5994
+ return this.#removeStoredUpload(uploadsConfig, id);
5995
+ }));
5996
+ } finally {
5997
+ this.#syncUploadsState();
5998
+ this.#publishUploadsRemoved(ids);
5999
+ }
5411
6000
  this.#refreshUploadRetention();
5412
6001
  }
6002
+ /** Tells the other tabs that this tab deleted these stored uploads. */
6003
+ #publishUploadsRemoved(ids) {
6004
+ if (this.#disposed || ids.length === 0 || !this.hasOtherTabs()) return;
6005
+ const releasedRefs = [];
6006
+ for (const id of ids) {
6007
+ const ref = this.#releasedUploadRefs.get(id);
6008
+ if (ref !== void 0) releasedRefs.push([id, ref]);
6009
+ }
6010
+ this.#browserTabs.coordinator.publish({
6011
+ kind: "offline-uploads-removed",
6012
+ ids: [...ids],
6013
+ releasedRefs
6014
+ });
6015
+ }
6016
+ #applyRemoteUploadsRemoved(ids, releasedRefs) {
6017
+ const removedIds = new Set(ids);
6018
+ for (const id of removedIds) {
6019
+ this.#releasedUploadRefs.delete(id);
6020
+ this.#pendingUploadReleases.delete(id);
6021
+ this.#uploads.delete(id);
6022
+ this.#uploadsRemovedWhileListing?.add(id);
6023
+ }
6024
+ const schema = this.#uploadsConfig?.resolvedRefSchema;
6025
+ for (const [id, ref] of releasedRefs) {
6026
+ const parsedRef = schema === void 0 ? ref : parseRestoredUploadRef(schema, ref);
6027
+ if (parsedRef !== void 0) this.#releasedUploadRefs.set(id, parsedRef);
6028
+ }
6029
+ const { uploads } = this.store.state;
6030
+ if (uploads.some((upload) => removedIds.has(upload.id))) this.store.setPartialState({ uploads: uploads.filter((upload) => !removedIds.has(upload.id)) }, { action: "offline-session-uploads" });
6031
+ for (const id of removedIds) {
6032
+ const entry = this.#uploadFiles.get(id);
6033
+ if (entry) this.#syncUploadFile(id, entry);
6034
+ }
6035
+ }
6036
+ /**
6037
+ * Removes an upload from the adapter, tracking the removal so a save or
6038
+ * load of the same id waits for it.
6039
+ */
6040
+ #removeStoredUpload(uploadsConfig, id) {
6041
+ const removal = uploadsConfig.adapter.remove(this.sessionKey, id);
6042
+ const settled = removal.then(() => {}, () => {});
6043
+ this.#uploadRemovals.set(id, settled);
6044
+ settled.then(() => {
6045
+ if (this.#uploadRemovals.get(id) === settled) this.#uploadRemovals.delete(id);
6046
+ });
6047
+ return removal;
6048
+ }
5413
6049
  /**
5414
6050
  * The session-wide lists: this tab's own stores, plus what other tabs
5415
6051
  * reported for the stores this tab has not attached.
5416
6052
  */
5417
6053
  #buildItemLists() {
5418
6054
  const allEntities = [];
6055
+ const attemptedCreationEntityIds = [];
5419
6056
  const allResolutions = [];
5420
6057
  let hasQueuedMutations = false;
5421
6058
  for (const contribution of this.#storeContributions.values()) {
5422
6059
  if (contribution.replayHead !== null) hasQueuedMutations = true;
5423
6060
  allEntities.push(...contribution.entities);
6061
+ attemptedCreationEntityIds.push(...contribution.attemptedCreationEntityIds);
5424
6062
  allResolutions.push(...contribution.resolutions);
5425
6063
  }
5426
6064
  for (const [storeName, items] of this.#remoteStoreItems) {
5427
6065
  if (this.#storeContributions.has(storeName)) continue;
5428
6066
  if (items.hasQueuedMutations) hasQueuedMutations = true;
5429
6067
  allEntities.push(...items.entities);
6068
+ attemptedCreationEntityIds.push(...items.attemptedCreationEntityIds);
5430
6069
  allResolutions.push(...items.resolutions);
5431
6070
  }
5432
6071
  return {
5433
6072
  entities: dedupeById(allEntities),
6073
+ attemptedCreationEntityIds,
5434
6074
  resolutions: dedupeById(allResolutions),
5435
6075
  hasQueuedMutations
5436
6076
  };
@@ -5444,7 +6084,7 @@ var SessionOfflineCoordinator = class {
5444
6084
  existing.push(...contribution.protectedKeys);
5445
6085
  nextProtectedKeysByAdapter.set(contribution.adapter, existing);
5446
6086
  }
5447
- const { entities, resolutions, hasQueuedMutations } = this.#buildItemLists();
6087
+ const { entities, attemptedCreationEntityIds, resolutions, hasQueuedMutations } = this.#buildItemLists();
5448
6088
  for (const [adapter, keys] of nextProtectedKeysByAdapter) nextProtectedKeysByAdapter.set(adapter, [...new Set(keys)].sort());
5449
6089
  const nextProtectedKeys = [...new Set([...nextProtectedKeysByAdapter.values()].flat())].sort();
5450
6090
  const adaptersToSync = publish ? new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]) : /* @__PURE__ */ new Set();
@@ -5492,18 +6132,23 @@ var SessionOfflineCoordinator = class {
5492
6132
  }
5493
6133
  if (publish) this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
5494
6134
  this.#referencedUploadIds = referencedUploadIds;
6135
+ for (const id of this.#stagedMutationUploadIds) if (referencedUploadIds.has(id)) this.#stagedMutationUploadIds.delete(id);
5495
6136
  if (!arraysEqual(this.#protectedKeys, nextProtectedKeys)) {
5496
6137
  this.#protectedKeys = nextProtectedKeys;
5497
6138
  setSessionProtectedKeysSnapshot(this.sessionKey, nextProtectedKeys);
5498
6139
  }
5499
6140
  this.store.setPartialState({
5500
6141
  entities,
6142
+ attemptedCreationEntityIds,
5501
6143
  resolutions,
5502
6144
  hasQueuedMutations
5503
6145
  }, { action: "offline-session-aggregate" });
5504
6146
  this.#persistSessionSnapshot();
5505
6147
  if (publish) this.#publishSnapshot();
5506
- if (publish && this.#uploadsConfig && this.#uploads.size > 0 && this.#storeContributions.size === this.#registrations.size) this.#cleanupUnusedMutationUploads();
6148
+ if (publish && this.#uploadsConfig && this.#storeContributions.size === this.#registrations.size) {
6149
+ if (this.#uploads.size > 0) this.#cleanupUnusedMutationUploads();
6150
+ this.#releasePendingUploads();
6151
+ }
5507
6152
  }
5508
6153
  #stampLocalStatus(status) {
5509
6154
  return {
@@ -5513,13 +6158,19 @@ var SessionOfflineCoordinator = class {
5513
6158
  };
5514
6159
  }
5515
6160
  #deriveLocalStatus(status) {
5516
- const isOfflineMode = getIsOfflineModeFromStatus(status);
5517
- return this.#stampLocalStatus({
6161
+ const gatedStatus = this.#isSessionEnabled() ? status : {
5518
6162
  ...status,
6163
+ network: INACTIVE_MODE,
6164
+ outage: INACTIVE_MODE
6165
+ };
6166
+ const isOfflineMode = getIsOfflineModeFromStatus(gatedStatus);
6167
+ return this.#stampLocalStatus({
6168
+ ...gatedStatus,
5519
6169
  isOfflineMode
5520
6170
  });
5521
6171
  }
5522
6172
  #updateStatus(updater) {
6173
+ this.#syncSessionGate();
5523
6174
  const derived = this.#deriveLocalStatus(updater(this.store.state.status));
5524
6175
  this.store.setPartialState({ status: derived }, { action: "offline-session-status" });
5525
6176
  this.#persistSessionSnapshot();
@@ -5540,23 +6191,30 @@ var SessionOfflineCoordinator = class {
5540
6191
  status,
5541
6192
  storeNames: [...this.#storeContributions.keys()],
5542
6193
  entities: contributions.flatMap((contribution) => contribution.entities),
6194
+ attemptedCreationEntityIds: contributions.flatMap((contribution) => contribution.attemptedCreationEntityIds),
5543
6195
  resolutions: contributions.flatMap((contribution) => contribution.resolutions),
5544
6196
  uploads: this.store.state.uploads,
5545
6197
  queuedStoreNames: [...this.#storeContributions].filter(([, contribution]) => contribution.replayHead !== null).map(([storeName]) => storeName)
5546
6198
  });
5547
6199
  }
5548
6200
  #applyRemoteSnapshot(message) {
5549
- for (const storeName of message.storeNames) this.#remoteStoreItems.set(storeName, {
5550
- entities: message.entities.filter((entity) => entity.storeName === storeName),
5551
- resolutions: message.resolutions.filter((resolution) => resolution.storeName === storeName),
5552
- hasQueuedMutations: message.queuedStoreNames.includes(storeName)
5553
- });
6201
+ const attemptedCreationEntityIds = message.attemptedCreationEntityIds;
6202
+ for (const storeName of message.storeNames) {
6203
+ const entities = message.entities.filter((entity) => entity.storeName === storeName);
6204
+ this.#remoteStoreItems.set(storeName, {
6205
+ entities,
6206
+ attemptedCreationEntityIds: attemptedCreationEntityIds ? entities.filter((entity) => attemptedCreationEntityIds.includes(entity.id)).map((entity) => entity.id) : [],
6207
+ resolutions: message.resolutions.filter((resolution) => resolution.storeName === storeName),
6208
+ hasQueuedMutations: message.queuedStoreNames.includes(storeName)
6209
+ });
6210
+ }
5554
6211
  if (message.sentAt < this.#lastRemoteSnapshotAt) {
5555
6212
  this.store.setPartialState(this.#buildItemLists(), { action: "offline-session-remote" });
5556
6213
  this.#persistSessionSnapshot();
5557
6214
  return;
5558
6215
  }
5559
6216
  this.#lastRemoteSnapshotAt = message.sentAt;
6217
+ this.#syncSessionGate();
5560
6218
  const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
5561
6219
  const wasReplayBlocked = this.isReplayBlocked();
5562
6220
  const isDetectedOffline = this.#isNetworkEnabled() && (this.store.state.status.network.active && !this.#classifiedNetworkActive || !this.#browserReportsOnline());
@@ -5572,7 +6230,7 @@ var SessionOfflineCoordinator = class {
5572
6230
  updatedAt: Date.now()
5573
6231
  }),
5574
6232
  ...this.#buildItemLists(),
5575
- uploads: message.uploads
6233
+ uploads: this.#validateRemoteUploads(message.uploads)
5576
6234
  }, { action: "offline-session-remote" });
5577
6235
  if (!isDetectedOffline) this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
5578
6236
  this.#persistSessionSnapshot();
@@ -5616,20 +6274,22 @@ var SessionOfflineCoordinator = class {
5616
6274
  return Math.max(0, Math.round(baseDelay + (Math.random() * jitter * 2 - jitter)));
5617
6275
  }
5618
6276
  #getDesiredRecoveryTarget() {
5619
- if (!this.isLeader() || this.#registrations.size === 0) return null;
5620
- if (this.store.state.status.network.active && this.#classifiedNetworkActive && this.#browserReportsOnline() && this.#canonicalConfig.networkRecoveryCheck) return {
6277
+ if (this.#disposed || !this.isLeader() || this.#registrations.size === 0) return null;
6278
+ const { networkRecoveryCheck, outageRecoveryCheck, healthCheck } = this.#canonicalConfig;
6279
+ if (this.store.state.status.network.active && this.#classifiedNetworkActive && this.#browserReportsOnline() && (networkRecoveryCheck || healthCheck)) return {
5621
6280
  mode: "network",
5622
- recoveryCheck: this.#canonicalConfig.networkRecoveryCheck,
6281
+ recoveryCheck: networkRecoveryCheck,
5623
6282
  recoveryProbe: this.#canonicalConfig.networkRecoveryProbe
5624
6283
  };
5625
- if (this.store.state.status.outage.active && !this.store.state.status.network.active && this.#canonicalConfig.outageRecoveryCheck) return {
6284
+ if (this.store.state.status.outage.active && !this.store.state.status.network.active && (outageRecoveryCheck || healthCheck)) return {
5626
6285
  mode: "outage",
5627
- recoveryCheck: this.#canonicalConfig.outageRecoveryCheck,
6286
+ recoveryCheck: outageRecoveryCheck,
5628
6287
  recoveryProbe: this.#canonicalConfig.outageRecoveryProbe
5629
6288
  };
5630
6289
  return null;
5631
6290
  }
5632
6291
  #scheduleRecoveryProbe(target) {
6292
+ if (this.#recoveryTimer !== null) clearTimeout(this.#recoveryTimer);
5633
6293
  this.#scheduledRecoveryMode = target.mode;
5634
6294
  this.#recoveryTimer = setTimeout(() => {
5635
6295
  this.#recoveryTimer = null;
@@ -5638,14 +6298,22 @@ var SessionOfflineCoordinator = class {
5638
6298
  }, this.#getRecoveryProbeDelay(target.recoveryProbe));
5639
6299
  }
5640
6300
  async #runRecoveryProbe(target) {
6301
+ this.#syncSessionGate();
5641
6302
  const nextTarget = this.#getDesiredRecoveryTarget();
5642
6303
  if (nextTarget === null || nextTarget.mode !== target.mode) return;
6304
+ const { healthCheck, outageRecoveryCheck } = this.#canonicalConfig;
5643
6305
  let recovered = false;
5644
- try {
6306
+ let health = null;
6307
+ if (nextTarget.recoveryCheck) try {
5645
6308
  recovered = await nextTarget.recoveryCheck({ sessionKey: this.sessionKey });
5646
6309
  } catch {
5647
6310
  recovered = false;
5648
6311
  }
6312
+ else if (healthCheck) {
6313
+ health = await this.#checkHealth(healthCheck);
6314
+ recovered = health === "up";
6315
+ }
6316
+ if (this.#disposed) return;
5649
6317
  const recoveryCheckAt = Date.now();
5650
6318
  if (recovered) {
5651
6319
  this.#recoveryAttempt = 0;
@@ -5654,11 +6322,28 @@ var SessionOfflineCoordinator = class {
5654
6322
  classified: false,
5655
6323
  recoveryCheckAt
5656
6324
  });
6325
+ if (health === "up" && !outageRecoveryCheck && this.store.state.status.outage.active && !this.store.state.status.network.active) this.setOutageActive(false, { recoveryCheckAt });
5657
6326
  return;
5658
6327
  }
5659
6328
  this.setOutageActive(false, { recoveryCheckAt });
5660
6329
  return;
5661
6330
  }
6331
+ if (target.mode === "network" && health === "outage") {
6332
+ if (!this.store.state.status.outage.active && this.#isOutageEnabled()) this.setOutageActive(true, { recoveryCheckAt });
6333
+ this.setNetworkActive(false, {
6334
+ classified: false,
6335
+ recoveryCheckAt
6336
+ });
6337
+ return;
6338
+ }
6339
+ if (target.mode === "outage" && health === "unreachable" && this.#isNetworkEnabled()) {
6340
+ this.setNetworkActive(true, {
6341
+ classified: true,
6342
+ recordFailureAt: true,
6343
+ recoveryCheckAt
6344
+ });
6345
+ return;
6346
+ }
5662
6347
  this.#updateStatus((current) => ({
5663
6348
  ...current,
5664
6349
  lastRecoveryCheckAt: recoveryCheckAt
@@ -5748,7 +6433,7 @@ function getGlobalOfflineResolutions(sessionKey) {
5748
6433
  return registry.get(sessionKey)?.getResolutions() ?? [];
5749
6434
  }
5750
6435
  function getOfflineSessionUploadsConfig(session) {
5751
- return __LEGIT_CAST__(uploadsConfigByOfflineSession.get(eraseOfflineSession(session)));
6436
+ return uploadsConfigByOfflineSession.get(session);
5752
6437
  }
5753
6438
  function getOfflineSessionAppVersion(session) {
5754
6439
  return appVersionByOfflineSession.get(session);
@@ -5773,13 +6458,13 @@ function createOfflineSession(args) {
5773
6458
  config,
5774
6459
  ...args.appVersion !== void 0 ? { appVersion: args.appVersion } : void 0,
5775
6460
  ...import.meta.env.DEV ? { debugLogger: args.debugLogger } : void 0,
5776
- uploads: eraseUploadsConfig(uploads),
6461
+ uploads,
5777
6462
  bootstrapStatusFromLocalStorage
5778
6463
  });
5779
6464
  }
5780
6465
  function useSessionCoordinator() {
5781
6466
  const activeSessionKey = getSessionKey();
5782
- return useConfiguredSessionOfflineCoordinator(activeSessionKey === false ? resolveOfflineSessionScope(false, inactiveScope) : activeSessionKey, activeSessionKey === false ? void 0 : config, eraseUploadsConfig(activeSessionKey === false ? void 0 : uploads), activeSessionKey !== false, import.meta.env.DEV ? args.debugLogger : void 0, args.appVersion);
6467
+ return useConfiguredSessionOfflineCoordinator(activeSessionKey === false ? resolveOfflineSessionScope(false, inactiveScope) : activeSessionKey, activeSessionKey === false ? void 0 : config, activeSessionKey === false ? void 0 : uploads, activeSessionKey !== false, import.meta.env.DEV ? args.debugLogger : void 0, args.appVersion);
5783
6468
  }
5784
6469
  const session = {
5785
6470
  getSessionKey,
@@ -5870,10 +6555,14 @@ function createOfflineSession(args) {
5870
6555
  const coordinator = useSessionCoordinator();
5871
6556
  const uploadsSelector = useCallback((state) => state.uploads, []);
5872
6557
  return castUploads(coordinator.store.useSelector(uploadsSelector, { equalityFn: deepEqual }));
6558
+ },
6559
+ useOfflineUploadFile: (id) => {
6560
+ const coordinator = useSessionCoordinator();
6561
+ return useSyncExternalStore(useCallback((onChange) => id ? coordinator.subscribeUploadFile(id, onChange) : noop, [coordinator, id]), useCallback(() => id ? coordinator.getUploadFile(id) : idleUploadFile, [coordinator, id]));
5873
6562
  }
5874
6563
  };
5875
- uploadsConfigByOfflineSession.set(eraseOfflineSession(session), eraseUploadsConfig(uploads));
5876
- appVersionByOfflineSession.set(eraseOfflineSession(session), args.appVersion);
6564
+ uploadsConfigByOfflineSession.set(session, uploads);
6565
+ appVersionByOfflineSession.set(session, args.appVersion);
5877
6566
  return session;
5878
6567
  }
5879
6568
  function useSessionOfflineCoordinator(sessionKey, bootstrapStatusFromLocalStorage = false) {
@@ -5935,12 +6624,26 @@ function useOfflineStoreEntities(args) {
5935
6624
  return useMemo(() => entities.map(stripInternalEntityPayload), [entities]);
5936
6625
  }
5937
6626
  /**
5938
- * React hook returning offline status for a session or inactive scope.
6627
+ * React hook returning the offline state of one item of a store, or `null`
6628
+ * when the item has no offline work. It reads the item through the keyed
6629
+ * lookup shared by all readers and keeps the previous result while the state
6630
+ * is unchanged, so a component re-renders only when its own item changes.
5939
6631
  */
5940
- function useOfflineStoreStatus(args) {
5941
- const coordinator = useSessionOfflineCoordinator(resolveOfflineSessionScope(args.sessionKey, args.inactiveScope), false);
5942
- const statusSelector = useCallback((state) => state.status, []);
5943
- return coordinator.store.useSelector(statusSelector);
6632
+ function useOfflineStoreItemState(sessionKey, inactiveScope, storeName, itemKey) {
6633
+ const coordinator = useSessionOfflineCoordinator(resolveOfflineSessionScope(sessionKey, inactiveScope), false);
6634
+ const itemStateSelector = useCallback((state) => storeName === void 0 || itemKey === null ? null : toItemOfflineState(getOfflineStoreEntityLookup(state.entities, storeName).get(itemKey), state.attemptedCreationEntityIds), [itemKey, storeName]);
6635
+ return coordinator.store.useSelector(itemStateSelector, { equalityFn: deepEqual });
6636
+ }
6637
+ /**
6638
+ * React hook returning whether a session or inactive scope is in offline mode.
6639
+ * Only this flag is selected, so the other status changes (e.g. `updatedAt`)
6640
+ * don't re-render the store hooks using it.
6641
+ */
6642
+ function useOfflineStoreIsOfflineMode(args) {
6643
+ return useSessionOfflineCoordinator(resolveOfflineSessionScope(args.sessionKey, args.inactiveScope), false).store.useSelector(selectIsOfflineMode);
6644
+ }
6645
+ function selectIsOfflineMode(state) {
6646
+ return state.status.isOfflineMode;
5944
6647
  }
5945
6648
  /**
5946
6649
  * React hook returning offline conflict/retry resolutions for a specific store in a session.
@@ -5975,7 +6678,7 @@ const compactOfflineEntitySchema = rc_object({
5975
6678
  a: rc_number,
5976
6679
  u: rc_number,
5977
6680
  t: rc_unknown.optionalKey(),
5978
- v: rc_unknown.optionalKey()
6681
+ y: rc_unknown.optionalKey()
5979
6682
  });
5980
6683
  const compactOfflineQueueEntrySchema = rc_object({
5981
6684
  d: rc_string,
@@ -6025,6 +6728,16 @@ function deserializeCompactOfflineEntityRef(value) {
6025
6728
  entityKind: fromCompactOfflineEntityKind(compactKind)
6026
6729
  };
6027
6730
  }
6731
+ /**
6732
+ * An entity with several queued mutations reports the most urgent state among
6733
+ * them, so it shows `syncing` while any of its mutations is being sent.
6734
+ */
6735
+ const entitySyncStatePriority = {
6736
+ pending: 0,
6737
+ syncing: 1,
6738
+ "needs-confirmation": 2,
6739
+ "resolution-required": 3
6740
+ };
6028
6741
  function toCompactOfflineEntitySyncState(state) {
6029
6742
  switch (state) {
6030
6743
  case "pending": return "p";
@@ -6160,9 +6873,20 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6160
6873
  const replayRetryIntervalMs = sessionConfig.replayRetry?.intervalMs ?? DEFAULT_REPLAY_RETRY_INTERVAL_MS;
6161
6874
  const queueEntries = /* @__PURE__ */ new Map();
6162
6875
  const resolutions = /* @__PURE__ */ new Map();
6876
+ const hasCancelledWithOperations = Object.values(operations).some((operation) => operation.cancelledWith !== void 0);
6877
+ const unknownOperationUploadIds = /* @__PURE__ */ new Map();
6878
+ function trackUnknownOperationUploads(recordKey, record) {
6879
+ const uploadIds = record ? [...Object.values(record.attachedUploadIds ?? {}), ...record.dependencyUploadIds ?? []] : [];
6880
+ if (uploadIds.length > 0) unknownOperationUploadIds.set(recordKey, uploadIds);
6881
+ else unknownOperationUploadIds.delete(recordKey);
6882
+ }
6163
6883
  const countedReplayFailures = /* @__PURE__ */ new Map();
6164
6884
  const entryIdsFromAnotherTab = /* @__PURE__ */ new Set();
6165
6885
  const resolvedEntityRefBySerializedRef = /* @__PURE__ */ new Map();
6886
+ /** Reads the session gate (`offlineSession.enabled`). */
6887
+ function isSessionEnabled() {
6888
+ return sessionConfig.enabled?.() !== false;
6889
+ }
6166
6890
  function getActiveMutationQueueingCause(current) {
6167
6891
  const status = current.session.getStatus();
6168
6892
  if (isModeEffectivelyActive(status.network)) return "network";
@@ -6188,10 +6912,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6188
6912
  * Whether mutations queued earlier for the entities this mutation affects
6189
6913
  * or depends on (`dependsOn`), or that depend on an entity this mutation
6190
6914
  * affects, are still waiting to reach the server (queued, replaying or
6191
- * unconfirmed).
6915
+ * unconfirmed), or the creation of one of those entities waits for a manual
6916
+ * resolution.
6192
6917
  */
6193
6918
  function hasQueuedWorkForSameEntities(prepared) {
6194
- if (queueEntries.size === 0) return false;
6919
+ if (queueEntries.size === 0 && resolutions.size === 0) return false;
6195
6920
  const affectedEntityRefs = prepared.entityRefs ?? resolveNormalizedRefs(getOperationRawEntityRefs(prepared.operation, prepared.operationName, prepared.validatedInput));
6196
6921
  const entityRefs = [...affectedEntityRefs, ...prepared.operation.dependsOn ? resolveNormalizedRefs(prepared.operation.dependsOn({ input: prepared.validatedInput })) : []];
6197
6922
  for (const entry of queueEntries.values()) {
@@ -6199,7 +6924,13 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6199
6924
  const queuedDependencyKeys = getDependencyBlockerEntityKeys(entry);
6200
6925
  if (affectedEntityRefs.some((entityRef) => queuedDependencyKeys.has(entityRef.entityKey))) return true;
6201
6926
  }
6202
- return false;
6927
+ if ((prepared.operation.accumulation || prepared.operation.supersedes) && findHeldWorkResolutions((resolution) => resolution.entityRefs.some((resolutionRef) => affectedEntityRefs.some((entityRef) => isSameEntityRef(entityRef, resolutionRef)))).length > 0) return true;
6928
+ return isHeldBehindTempCreateResolution({
6929
+ operation: prepared.operationName,
6930
+ input: prepared.validatedInput,
6931
+ entityRefs,
6932
+ tempIds: prepared.tempIds
6933
+ });
6203
6934
  }
6204
6935
  function getInitialOfflineMutationAction(current, prepared) {
6205
6936
  if (!current.session.getStatus().isOfflineMode) return hasQueuedWorkForSameEntities(prepared) ? "queue" : "run";
@@ -6273,6 +7004,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6273
7004
  queueEntries.clear();
6274
7005
  entryIdsFromAnotherTab.clear();
6275
7006
  resolutions.clear();
7007
+ unknownOperationUploadIds.clear();
6276
7008
  nextQueueOrder = 0;
6277
7009
  hydratedSessionKey = null;
6278
7010
  hydratedPromise = null;
@@ -6388,7 +7120,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6388
7120
  a: entity.createdAt,
6389
7121
  u: entity.updatedAt,
6390
7122
  ...entity.tempId !== void 0 ? { t: entity.tempId } : {},
6391
- ...entity.payload !== void 0 ? { v: entity.payload } : {}
7123
+ ...entity.payload !== void 0 ? { y: entity.payload } : {}
6392
7124
  };
6393
7125
  },
6394
7126
  deserialize(raw) {
@@ -6415,7 +7147,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6415
7147
  createdAt: compactEntity.a,
6416
7148
  updatedAt: compactEntity.u,
6417
7149
  ...compactEntity.t !== void 0 ? { tempId: __LEGIT_CAST__(compactEntity.t) } : {},
6418
- ...compactEntity.v !== void 0 ? { payload: __LEGIT_CAST__(compactEntity.v) } : {}
7150
+ ...compactEntity.y !== void 0 ? { payload: __LEGIT_CAST__(compactEntity.y) } : {}
6419
7151
  };
6420
7152
  }
6421
7153
  } });
@@ -6430,15 +7162,20 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6430
7162
  onOfflineCycle: () => {
6431
7163
  resetReplayRetryState();
6432
7164
  },
7165
+ onTempEntitiesCancelled: hasCancelledWithOperations ? discardWorkCancelledWithExternalTempEntities : void 0,
6433
7166
  onRemoteQueueEntryChange: (entryId, entry) => {
6434
7167
  applyRecordChangeFromAnotherTab(() => {
6435
7168
  if (entry) {
6436
7169
  nextQueueOrder = Math.max(nextQueueOrder, getQueueOrder(entry) + 1);
6437
- if (!operations[entry.operation]) return;
7170
+ if (!operations[entry.operation]) {
7171
+ trackUnknownOperationUploads(`q:${entryId}`, entry);
7172
+ return;
7173
+ }
6438
7174
  queueEntries.set(entryId, entry);
6439
7175
  entryIdsFromAnotherTab.add(entryId);
6440
7176
  return;
6441
7177
  }
7178
+ trackUnknownOperationUploads(`q:${entryId}`, null);
6442
7179
  queueEntries.delete(entryId);
6443
7180
  entryIdsFromAnotherTab.delete(entryId);
6444
7181
  countedReplayFailures.delete(entryId);
@@ -6447,13 +7184,15 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6447
7184
  },
6448
7185
  onRemoteResolutionChange: (resolutionId, resolution) => {
6449
7186
  applyRecordChangeFromAnotherTab(() => {
6450
- if (resolution && rc_parse(resolution, offlineResolutionRecordSchema).ok && operations[resolution.operation]) resolutions.set(resolutionId, resolution);
7187
+ const parsedResolution = resolution && rc_parse(resolution, offlineResolutionRecordSchema).ok ? resolution : null;
7188
+ if (parsedResolution && operations[parsedResolution.operation]) resolutions.set(resolutionId, parsedResolution);
6451
7189
  else resolutions.delete(resolutionId);
7190
+ trackUnknownOperationUploads(`r:${resolutionId}`, parsedResolution && !operations[parsedResolution.operation] ? parsedResolution : null);
6452
7191
  });
6453
7192
  },
6454
- onRemoteWorkDiscarded: (discardedWork, removedTempEntityKeys) => {
7193
+ onRemoteWorkDiscarded: (discardedWork, removedEntityKeys) => {
6455
7194
  applyRecordChangeFromAnotherTab(() => {
6456
- revalidateDiscardedWork(discardedWork, new Set(removedTempEntityKeys));
7195
+ revalidateDiscardedWork(discardedWork, new Set(removedEntityKeys));
6457
7196
  });
6458
7197
  },
6459
7198
  onRemoteTempReconciled: (tempId, finalPayload) => {
@@ -6479,17 +7218,16 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6479
7218
  queueEntries.clear();
6480
7219
  entryIdsFromAnotherTab.clear();
6481
7220
  resolutions.clear();
6482
- for (const entry of loadedQueueEntries.values()) queueEntries.set(entry.id, entry);
7221
+ unknownOperationUploadIds.clear();
7222
+ for (const entry of loadedQueueEntries.values()) if (operations[entry.operation]) queueEntries.set(entry.id, entry);
7223
+ else trackUnknownOperationUploads(`q:${entry.id}`, entry);
6483
7224
  for (const resolution of loadedResolutionEntries.values()) {
6484
7225
  if (!rc_parse(resolution, offlineResolutionRecordSchema).ok) {
6485
7226
  current.resolutionNamespace.remove(resolution.id);
6486
7227
  continue;
6487
7228
  }
6488
- if (!operations[resolution.operation]) {
6489
- current.resolutionNamespace.remove(resolution.id);
6490
- continue;
6491
- }
6492
- resolutions.set(resolution.id, resolution);
7229
+ if (operations[resolution.operation]) resolutions.set(resolution.id, resolution);
7230
+ else trackUnknownOperationUploads(`r:${resolution.id}`, resolution);
6493
7231
  }
6494
7232
  nextQueueOrder = getNextQueueOrder(loadedQueueEntries.values());
6495
7233
  hydratedSessionKey = current.sessionKey;
@@ -6652,6 +7390,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6652
7390
  const sessionState = session;
6653
7391
  const dependencySnapshot = createResolutionDependencySnapshot();
6654
7392
  const entitiesByKey = /* @__PURE__ */ new Map();
7393
+ const attemptedCreationEntityKeys = /* @__PURE__ */ new Set();
6655
7394
  function createEntityBase(ref) {
6656
7395
  return {
6657
7396
  id: buildEntityId(sessionState.sessionKey, storeName, ref.entityKey),
@@ -6668,11 +7407,16 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6668
7407
  const existing = entitiesByKey.get(ref.entityKey);
6669
7408
  const childResolutionIds = dependencySnapshot.childResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
6670
7409
  const blockedByResolutionIds = dependencySnapshot.blockedByResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
7410
+ const tempId = getTempIdForEntityRef({
7411
+ entityRefs: entry.entityRefs,
7412
+ tempIds: entry.tempIds,
7413
+ entityKey: ref.entityKey
7414
+ });
6671
7415
  entitiesByKey.set(ref.entityKey, {
6672
7416
  ...createEntityBase(ref),
6673
7417
  kind: reduceOfflineEntityKind(existing?.kind, operationKind),
6674
7418
  pendingMutations: (existing?.pendingMutations ?? 0) + 1,
6675
- syncState: existing?.syncState === "needs-confirmation" ? existing.syncState : entry.syncState,
7419
+ syncState: existing && entitySyncStatePriority[existing.syncState] > entitySyncStatePriority[entry.syncState] ? existing.syncState : entry.syncState,
6676
7420
  requiresResolution: existing?.requiresResolution ?? false,
6677
7421
  blockedByResolutionIds,
6678
7422
  childResolutionIds,
@@ -6680,17 +7424,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6680
7424
  childResolutionCount: childResolutionIds.length,
6681
7425
  createdAt: existing?.createdAt ?? entry.createdAt,
6682
7426
  updatedAt: entry.updatedAt,
6683
- tempId: getTempIdForEntityRef({
6684
- entityRefs: entry.entityRefs,
6685
- tempIds: entry.tempIds,
6686
- entityKey: ref.entityKey
6687
- }) ?? existing?.tempId,
7427
+ tempId: tempId ?? existing?.tempId,
6688
7428
  payload: getPayloadForEntityRef({
6689
7429
  operationName: entry.operation,
6690
7430
  input: entry.input,
6691
7431
  entityKey: ref.entityKey
6692
7432
  }) ?? existing?.payload
6693
7433
  });
7434
+ if (tempId !== void 0 && !isUnsentQueueEntry(entry)) attemptedCreationEntityKeys.add(ref.entityKey);
6694
7435
  }
6695
7436
  }
6696
7437
  for (const resolution of resolutions.values()) {
@@ -6699,6 +7440,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6699
7440
  const existing = entitiesByKey.get(ref.entityKey);
6700
7441
  const childResolutionIds = dependencySnapshot.childResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
6701
7442
  const blockedByResolutionIds = dependencySnapshot.blockedByResolutionIdsByEntityKey.get(ref.entityKey) ?? [];
7443
+ const tempId = getTempIdForEntityRef({
7444
+ entityRefs: resolution.entityRefs,
7445
+ tempIds: resolution.tempIds,
7446
+ entityKey: ref.entityKey
7447
+ });
6702
7448
  entitiesByKey.set(ref.entityKey, {
6703
7449
  ...createEntityBase(ref),
6704
7450
  kind: reduceOfflineEntityKind(existing?.kind, operationKind),
@@ -6711,22 +7457,19 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6711
7457
  childResolutionCount: childResolutionIds.length,
6712
7458
  createdAt: existing?.createdAt ?? resolution.createdAt,
6713
7459
  updatedAt: resolution.updatedAt,
6714
- tempId: getTempIdForEntityRef({
6715
- entityRefs: resolution.entityRefs,
6716
- tempIds: resolution.tempIds,
6717
- entityKey: ref.entityKey
6718
- }) ?? existing?.tempId,
7460
+ tempId: tempId ?? existing?.tempId,
6719
7461
  payload: getPayloadForEntityRef({
6720
7462
  operationName: resolution.operation,
6721
7463
  input: resolution.input,
6722
7464
  entityKey: ref.entityKey
6723
7465
  }) ?? existing?.payload
6724
7466
  });
7467
+ if (tempId !== void 0 && !isHeldWorkResolution(resolution, dependencySnapshot)) attemptedCreationEntityKeys.add(ref.entityKey);
6725
7468
  }
6726
7469
  }
6727
7470
  const entities = [...entitiesByKey.values()].sort((left, right) => left.id.localeCompare(right.id));
6728
7471
  const derivedResolutions = buildDerivedResolutionRecords(dependencySnapshot);
6729
- const referencedUploadIds = [...new Set([...queueEntries.values(), ...resolutions.values()].flatMap((entry) => [...Object.values(entry.attachedUploadIds ?? {}), ...entry.dependencyUploadIds ?? []]))].sort((left, right) => left.localeCompare(right));
7472
+ const referencedUploadIds = [...new Set([...[...queueEntries.values(), ...resolutions.values()].flatMap((entry) => [...Object.values(entry.attachedUploadIds ?? {}), ...entry.dependencyUploadIds ?? []]), ...[...unknownOperationUploadIds.values()].flat()])].sort((left, right) => left.localeCompare(right));
6730
7473
  const protectedKeys = storeAdapter.getProtectedCacheKeys(entities.map((entity) => ({
6731
7474
  entityKey: entity.entityKey,
6732
7475
  entityKind: entity.entityKind
@@ -6739,6 +7482,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6739
7482
  sessionState.session.syncStoreData(storeName, {
6740
7483
  adapter,
6741
7484
  entities,
7485
+ attemptedCreationEntityIds: entities.filter((entity) => attemptedCreationEntityKeys.has(entity.entityKey)).map((entity) => entity.id),
6742
7486
  resolutions: derivedResolutions,
6743
7487
  referencedUploadIds,
6744
7488
  protectedKeys,
@@ -6809,15 +7553,21 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6809
7553
  let candidate = null;
6810
7554
  for (const entry of args.entries ?? queueEntries.values()) {
6811
7555
  if (entry.operation !== args.operationName) continue;
6812
- if (entry.syncState !== "pending") continue;
6813
- if (entry.attempts > 0) continue;
7556
+ if (!isUnsentQueueEntry(entry)) continue;
6814
7557
  if (entryIdsFromAnotherTab.has(entry.id)) continue;
6815
7558
  if (entry.tempIds && entry.tempIds.length > 0) continue;
6816
7559
  if (normalizeEntityRefs(entry.entityRefs) !== normalizedEntityRefs) continue;
6817
- if (!candidate || compareQueueEntries(entry, candidate) < 0) candidate = entry;
7560
+ if (!candidate || compareQueueEntries(entry, candidate) > 0) candidate = entry;
6818
7561
  }
6819
7562
  return candidate;
6820
7563
  }
7564
+ /**
7565
+ * Whether the entry was never sent: only then can it be dropped or merged
7566
+ * without the server possibly having applied it.
7567
+ */
7568
+ function isUnsentQueueEntry(entry) {
7569
+ return entry.syncState === "pending" && entry.attempts === 0;
7570
+ }
6821
7571
  function isSameEntityRef(left, right) {
6822
7572
  return left?.entityKind === right?.entityKind && left?.entityKey === right?.entityKey;
6823
7573
  }
@@ -6849,7 +7599,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6849
7599
  const targetRef = args.entityRefs[0];
6850
7600
  if (!targetRef) throw new Error(`Superseding offline operation "${args.operationName}" is missing its entity ref`);
6851
7601
  return [...args.entries ?? queueEntries.values()].filter((entry) => {
6852
- return entry.syncState === "pending" && entry.attempts === 0 && entry.entityRefs.length === 1 && getQueueOrder(entry) < args.queueOrder && matchesSupersededOperation({
7602
+ return isUnsentQueueEntry(entry) && entry.entityRefs.length === 1 && getQueueOrder(entry) < args.queueOrder && matchesSupersededOperation({
6853
7603
  candidateOperationName: entry.operation,
6854
7604
  operationName: args.operationName,
6855
7605
  supersedes: args.supersedes
@@ -6954,11 +7704,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6954
7704
  };
6955
7705
  }
6956
7706
  async function buildOperationExecuteContext(args) {
6957
- const [fileEntries, resolvedRefsById] = await Promise.all([Promise.all(Object.entries(args.entry.attachedUploadIds ?? {}).map(async ([uploadId, storedUploadId]) => {
7707
+ const fileEntries = await Promise.all(Object.entries(args.entry.attachedUploadIds ?? {}).map(async ([uploadId, storedUploadId]) => {
6958
7708
  const file = await args.current.session.loadUpload(storedUploadId);
6959
7709
  if (!file) throw new Error(`Missing offline upload "${storedUploadId}"`);
6960
7710
  return [uploadId, file];
6961
- })), args.current.session.resolveUploadIds(args.entry.dependencyUploadIds ?? [])]);
7711
+ }));
6962
7712
  const filesById = Object.fromEntries(fileEntries);
6963
7713
  return {
6964
7714
  ...buildOperationBaseContext({
@@ -6968,7 +7718,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6968
7718
  }),
6969
7719
  uploads: {
6970
7720
  filesById,
6971
- resolvedRefsById
7721
+ resolvedRefsById: args.resolvedRefsById
6972
7722
  }
6973
7723
  };
6974
7724
  }
@@ -7047,6 +7797,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7047
7797
  const tempEntities = operation.tempEntities;
7048
7798
  if (!tempEntity && !tempEntities) return;
7049
7799
  if (!storeAdapter.reconcileTempEntity) return;
7800
+ try {
7801
+ await storeAdapter.loadTempEntities?.(args.tempIds, getReplayedTempEntityQueries(tempEntity, args.input, args.tempIds));
7802
+ } catch {}
7050
7803
  if (tempEntity) {
7051
7804
  const tempId = args.tempIds[0];
7052
7805
  if (tempId === void 0) return;
@@ -7095,6 +7848,33 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7095
7848
  });
7096
7849
  }
7097
7850
  }
7851
+ /**
7852
+ * The queries a replayed temp entity was declared into, so the lists that
7853
+ * are only in persistent storage are loaded and receive the final entity.
7854
+ * Only a `tempEntity` declaration is computed again, never the batch
7855
+ * builder: the server already applied the mutation, so app code must not
7856
+ * run (or throw) again here.
7857
+ */
7858
+ function getReplayedTempEntityQueries(tempEntity, input, tempIds) {
7859
+ const tempId = tempIds[0];
7860
+ if (!tempEntity?.addToQueries || tempId === void 0) return [];
7861
+ try {
7862
+ const addToQueries = typeof tempEntity.addToQueries === "function" ? tempEntity.addToQueries(input, tempId) : tempEntity.addToQueries;
7863
+ return addToQueries ? [addToQueries] : [];
7864
+ } catch {
7865
+ return [];
7866
+ }
7867
+ }
7868
+ /**
7869
+ * Loads the queries the pending entities are declared into that are only in
7870
+ * persistent storage, so they receive the entities. Returns `undefined`
7871
+ * when there is nothing to load.
7872
+ */
7873
+ function loadPendingEntityQueries(pendingEntities) {
7874
+ const addToQueries = pendingEntities.flatMap((pendingEntity) => pendingEntity.addToQueries ? [pendingEntity.addToQueries] : []);
7875
+ if (addToQueries.length === 0) return void 0;
7876
+ return storeAdapter.loadTempEntities?.([], addToQueries)?.catch(() => {});
7877
+ }
7098
7878
  async function persistEntry(entry, current, skipRefresh) {
7099
7879
  const session = current ?? ensureActiveSession();
7100
7880
  if (!session) return;
@@ -7142,6 +7922,21 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7142
7922
  session.session.publishResolutionChange(storeName, resolutionId, null);
7143
7923
  if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
7144
7924
  }
7925
+ /**
7926
+ * Deletes the staged uploads that work items depended on, after those items
7927
+ * left the queue for good (replayed, discarded, superseded, cancelled).
7928
+ *
7929
+ * Call it after `refreshDerivedState`, which reports the references that
7930
+ * remain: the session keeps every upload a queue entry or resolution record
7931
+ * of any store still needs. Attached uploads need no call, the session drops
7932
+ * them as soon as nothing references them.
7933
+ */
7934
+ async function deleteOrphanedDependencyUploads(current, removedWorkItems) {
7935
+ if (!isActiveSessionState(current)) return;
7936
+ const uploadIds = removedWorkItems.flatMap((workItem) => workItem.dependencyUploadIds ?? []);
7937
+ if (uploadIds.length === 0) return;
7938
+ await current.session.deleteUnreferencedUploads(uploadIds);
7939
+ }
7145
7940
  function collectTempCreateDescendants(args) {
7146
7941
  const sourcesByEntityKey = new Map([[args.parentEntityKey, {
7147
7942
  entityKey: args.parentEntityKey,
@@ -7208,6 +8003,82 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7208
8003
  pendingEntity: void 0
7209
8004
  });
7210
8005
  }
8006
+ /**
8007
+ * Whether the work targets or depends on a temp entity whose creation is
8008
+ * held in a manual resolution. Such work cannot be sent (the server does
8009
+ * not know the entity) until that resolution is decided.
8010
+ */
8011
+ function isHeldBehindTempCreateResolution(workItem) {
8012
+ for (const resolution of resolutions.values()) for (const entityKey of getTempLifecycleEntityKeys(resolution)) if (workItemDependsOnDependencySource({
8013
+ workItem,
8014
+ dependencySource: {
8015
+ entityKey,
8016
+ resolutionId: resolution.id,
8017
+ sourceType: "resolution"
8018
+ }
8019
+ })) return true;
8020
+ return false;
8021
+ }
8022
+ /**
8023
+ * The resolutions holding work behind a temp creation that waits for a
8024
+ * manual resolution, among those `matches` accepts. That work was never sent
8025
+ * (it waits for the creation), so like an unsent queue entry it can still be
8026
+ * merged into or superseded by a later mutation of the same entity.
8027
+ * Otherwise the later mutation would be sent first, and the held work
8028
+ * replayed over it once the creation is retried.
8029
+ */
8030
+ function findHeldWorkResolutions(matches, excludedResolutionId) {
8031
+ if (resolutions.size === 0) return [];
8032
+ const heldResolutions = [];
8033
+ for (const resolution of resolutions.values()) {
8034
+ if (resolution.id === excludedResolutionId || !matches(resolution) || !isHeldWorkResolution(resolution)) continue;
8035
+ heldResolutions.push(resolution);
8036
+ }
8037
+ return heldResolutions.sort(compareResolutionRecords);
8038
+ }
8039
+ /**
8040
+ * Work held behind a temp creation waiting for a decision, never sent. A
8041
+ * `dependencySnapshot` of the current resolutions answers it without
8042
+ * scanning them again.
8043
+ */
8044
+ function isHeldWorkResolution(resolution, dependencySnapshot) {
8045
+ if (resolution.kind !== "retry-exhausted" || resolution.lastReplayError.message !== BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE) return false;
8046
+ return dependencySnapshot ? dependencySnapshot.blockedByResolutionIdsByResolutionId.has(resolution.id) : isHeldBehindTempCreateResolution(resolution);
8047
+ }
8048
+ /**
8049
+ * Removes the items a discarded `create` without temp entity (the app
8050
+ * generated the id on the client) added to the store, like the rollback of a
8051
+ * temp create, and adds their keys to `removedEntityKeys`. Like removed temp
8052
+ * entities, they are not refetched: the server most likely never got them.
8053
+ * If an earlier replay attempt did create one, the store's list
8054
+ * revalidation brings it back.
8055
+ */
8056
+ function rollbackClientIdCreatedItems(workItem, removedEntityKeys, unsentEntityKeys, cancelledEntityKeys) {
8057
+ for (const entityKey of getClientIdCreatedEntityKeys(workItem)) {
8058
+ const payload = getPayloadForEntityRef({
8059
+ operationName: workItem.operation,
8060
+ input: workItem.input,
8061
+ entityKey
8062
+ });
8063
+ if (payload === void 0) continue;
8064
+ storeAdapter.rollbackPendingEntity?.({
8065
+ operationName: workItem.operation,
8066
+ input: workItem.input,
8067
+ tempId: payload,
8068
+ pendingEntity: void 0
8069
+ });
8070
+ removedEntityKeys.add(entityKey);
8071
+ if (unsentEntityKeys.has(entityKey)) cancelledEntityKeys.add(entityKey);
8072
+ }
8073
+ }
8074
+ /**
8075
+ * Keys of the items a `create` without temp entity adds to the store with
8076
+ * a client-generated id.
8077
+ */
8078
+ function getClientIdCreatedEntityKeys(workItem) {
8079
+ if (getOperationLifecycleKind(workItem.operation) !== "create" || isTempCreateOperation(workItem.operation)) return [];
8080
+ return workItem.entityRefs.filter((entityRef) => entityRef.entityKind === "item").map((entityRef) => entityRef.entityKey);
8081
+ }
7211
8082
  async function promoteBlockedTempCreateDescendants(args) {
7212
8083
  const descendantQueueEntries = /* @__PURE__ */ new Map();
7213
8084
  for (const entityKey of getTempLifecycleEntityKeys(args.parentEntry)) {
@@ -7223,6 +8094,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7223
8094
  }
7224
8095
  }
7225
8096
  async function persistManualResolutionChain(args) {
8097
+ await args.current.session.markUploadsFailed(args.parentEntry.dependencyUploadIds ?? []);
7226
8098
  await persistResolution(args.parentResolution, args.current, true);
7227
8099
  await removeEntry(args.parentEntry.id, args.current, true);
7228
8100
  await promoteBlockedTempCreateDescendants({
@@ -7235,58 +8107,128 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7235
8107
  function isPersistedResolutionBlocked(resolution) {
7236
8108
  return (createResolutionDependencySnapshot().blockedResolutionIdsByResolutionId.get(resolution.id)?.size ?? 0) > 0;
7237
8109
  }
7238
- async function discardTempCreateResolutionChain(args) {
7239
- await removeResolution(args.resolution.id, args.current, true);
7240
- const parentEntityKeys = getTempLifecycleEntityKeys(args.resolution);
7241
- if (parentEntityKeys.length === 0) {
7242
- refreshDerivedState(args.current);
7243
- revalidateDiscardedWorkInEveryTab(args.current, [args.resolution], /* @__PURE__ */ new Set());
7244
- return;
7245
- }
8110
+ /**
8111
+ * Drops everything that only made sense with temp entities that will never
8112
+ * exist on the server, because their creation (`tempCreates`, already
8113
+ * removed by the caller) was cancelled before being sent or discarded:
8114
+ *
8115
+ * - the queued work and manual resolutions of this store that target or
8116
+ * depend on those entities, or on the items an unsent dropped creation
8117
+ * added with a client-generated id, recursively
8118
+ * - the temp entities themselves, and the items the dropped work created
8119
+ * with a client-generated id
8120
+ * - the work of other stores declared as `cancelledWith` those entities,
8121
+ * or the items unsent dropped creations added with a client-generated id
8122
+ *
8123
+ * The server entities the dropped work changed optimistically are
8124
+ * refetched, and the staged uploads only the dropped work and `tempCreates`
8125
+ * depended on are deleted.
8126
+ */
8127
+ async function discardTempLifecycles(current, tempCreates) {
7246
8128
  const descendantQueueEntries = /* @__PURE__ */ new Map();
7247
8129
  const descendantResolutions = /* @__PURE__ */ new Map();
8130
+ const parentEntityKeys = [];
8131
+ const unsentClientIdEntityKeys = /* @__PURE__ */ new Set();
8132
+ function addUnsentClientIdCreation(workItem) {
8133
+ for (const entityKey of getClientIdCreatedEntityKeys(workItem)) {
8134
+ parentEntityKeys.push(entityKey);
8135
+ unsentClientIdEntityKeys.add(entityKey);
8136
+ }
8137
+ }
8138
+ for (const tempCreate of tempCreates) {
8139
+ parentEntityKeys.push(...getTempLifecycleEntityKeys(tempCreate));
8140
+ if ("syncState" in tempCreate ? isUnsentQueueEntry(tempCreate) : isHeldBehindTempCreateResolution(tempCreate)) addUnsentClientIdCreation(tempCreate);
8141
+ }
7248
8142
  for (const entityKey of parentEntityKeys) {
7249
- const descendants = collectTempCreateDescendants({
7250
- parentEntityKey: entityKey,
7251
- parentResolutionId: args.resolution.id
8143
+ const descendants = collectTempCreateDescendants({ parentEntityKey: entityKey });
8144
+ for (const queueEntry of descendants.queueEntries) {
8145
+ if (descendantQueueEntries.has(queueEntry.id)) continue;
8146
+ descendantQueueEntries.set(queueEntry.id, queueEntry);
8147
+ if (isUnsentQueueEntry(queueEntry)) addUnsentClientIdCreation(queueEntry);
8148
+ }
8149
+ for (const resolution of descendants.resolutions) {
8150
+ if (descendantResolutions.has(resolution.id)) continue;
8151
+ descendantResolutions.set(resolution.id, resolution);
8152
+ addUnsentClientIdCreation(resolution);
8153
+ }
8154
+ }
8155
+ for (const queueEntry of descendantQueueEntries.values()) await removeEntry(queueEntry.id, current, true);
8156
+ for (const resolution of descendantResolutions.values()) await removeResolution(resolution.id, current, true);
8157
+ const droppedDescendants = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
8158
+ const removedEntityKeys = /* @__PURE__ */ new Set();
8159
+ const cancelledEntityKeys = /* @__PURE__ */ new Set();
8160
+ for (const workItem of [...droppedDescendants, ...tempCreates]) {
8161
+ rollbackClientIdCreatedItems(workItem, removedEntityKeys, unsentClientIdEntityKeys, cancelledEntityKeys);
8162
+ for (const entityKey of getTempLifecycleEntityKeys(workItem)) {
8163
+ removedEntityKeys.add(entityKey);
8164
+ cancelledEntityKeys.add(entityKey);
8165
+ }
8166
+ if (!workItem.tempIds || !isTempCreateOperation(workItem.operation)) continue;
8167
+ rollbackTempCreatePendingEntity(workItem);
8168
+ }
8169
+ refreshDerivedState(current);
8170
+ const discardedWork = [...droppedDescendants];
8171
+ for (const tempCreate of tempCreates) if (getTempLifecycleEntityKeys(tempCreate).length === 0) discardedWork.push(tempCreate);
8172
+ revalidateDiscardedWorkInEveryTab(current, discardedWork, removedEntityKeys);
8173
+ await deleteOrphanedDependencyUploads(current, [...tempCreates, ...droppedDescendants]);
8174
+ if (cancelledEntityKeys.size > 0) await current.session.notifyTempEntitiesCancelled(storeName, cancelledEntityKeys, getEntityKeyOfPayload);
8175
+ }
8176
+ async function discardTempCreateResolutionChain(args) {
8177
+ await removeResolution(args.resolution.id, args.current, true);
8178
+ await discardTempLifecycles(args.current, [args.resolution]);
8179
+ }
8180
+ /** Key of an entity payload of this store, as its entity refs hold it. */
8181
+ function getEntityKeyOfPayload(entityRef) {
8182
+ return resolveNormalizedRefs([entityRef])[0]?.entityKey;
8183
+ }
8184
+ /**
8185
+ * Another store of the session reported entities created offline that will
8186
+ * never exist on the server: drops the work of this store declared as
8187
+ * `cancelledWith` one of them, with its own temp lifecycles.
8188
+ */
8189
+ async function discardWorkCancelledWithExternalTempEntities(sourceStoreName, cancelledEntityKeys, getSourceEntityKey) {
8190
+ await hydrateIfNeeded();
8191
+ const current = ensureActiveSession();
8192
+ if (!current) return;
8193
+ function isCancelled(workItem) {
8194
+ const externalEntityRefs = operations[workItem.operation]?.cancelledWith?.({ input: workItem.input });
8195
+ return externalEntityRefs !== void 0 && externalEntityRefs.some((externalEntityRef) => {
8196
+ if (externalEntityRef.storeName !== sourceStoreName) return false;
8197
+ const entityKey = getSourceEntityKey(externalEntityRef.entityRef);
8198
+ return entityKey !== void 0 && cancelledEntityKeys.has(entityKey);
7252
8199
  });
7253
- for (const queueEntry of descendants.queueEntries) descendantQueueEntries.set(queueEntry.id, queueEntry);
7254
- for (const resolution of descendants.resolutions) descendantResolutions.set(resolution.id, resolution);
7255
- }
7256
- for (const queueEntry of descendantQueueEntries.values()) await removeEntry(queueEntry.id, args.current, true);
7257
- for (const resolution of descendantResolutions.values()) await removeResolution(resolution.id, args.current, true);
7258
- for (const queueEntry of descendantQueueEntries.values()) rollbackTempCreatePendingEntity(queueEntry);
7259
- for (const resolution of descendantResolutions.values()) rollbackTempCreatePendingEntity(resolution);
7260
- rollbackTempCreatePendingEntity(args.resolution);
7261
- refreshDerivedState(args.current);
7262
- const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
7263
- const removedTempEntityKeys = new Set(parentEntityKeys);
7264
- for (const workItem of discardedWork) for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedTempEntityKeys.add(entityKey);
7265
- revalidateDiscardedWorkInEveryTab(args.current, discardedWork, removedTempEntityKeys);
8200
+ }
8201
+ const cancelledQueueEntries = [...queueEntries.values()].filter((entry) => entry.syncState !== "syncing" && isCancelled(entry));
8202
+ const cancelledResolutions = [...resolutions.values()].filter(isCancelled);
8203
+ if (cancelledQueueEntries.length === 0 && cancelledResolutions.length === 0) return;
8204
+ for (const queueEntry of cancelledQueueEntries) await removeEntry(queueEntry.id, current, true);
8205
+ for (const resolution of cancelledResolutions) await removeResolution(resolution.id, current, true);
8206
+ await discardTempLifecycles(current, [...cancelledQueueEntries, ...cancelledResolutions]);
7266
8207
  }
7267
8208
  /**
7268
8209
  * {@link revalidateDiscardedWork} in this tab and in the other tabs with the
7269
8210
  * store: each one may show the discarded optimistic changes.
7270
8211
  */
7271
- function revalidateDiscardedWorkInEveryTab(current, discardedWork, removedTempEntityKeys) {
7272
- revalidateDiscardedWork(discardedWork, removedTempEntityKeys);
8212
+ function revalidateDiscardedWorkInEveryTab(current, discardedWork, removedEntityKeys) {
8213
+ revalidateDiscardedWork(discardedWork, removedEntityKeys);
7273
8214
  if (!discardedWork.some((workItem) => workItem.entityRefs.length > 0)) return;
7274
8215
  current.session.publishWorkDiscarded(storeName, discardedWork.map(({ operation, input, entityRefs }) => ({
7275
8216
  operation,
7276
8217
  input,
7277
8218
  entityRefs
7278
- })), [...removedTempEntityKeys]);
8219
+ })), [...removedEntityKeys]);
7279
8220
  }
7280
8221
  /**
7281
8222
  * Refetches the entities discarded queued work referenced (its optimistic
7282
- * changes cannot be rolled back locally), except the removed temp entities
7283
- * and the entities other changes still wait for a decision on: a refetch
8223
+ * changes cannot be rolled back locally), except the entities the discard
8224
+ * removed (temp entities and items of discarded creations) and the
8225
+ * entities other changes still wait for a decision on: a refetch
7284
8226
  * would replace those changes. The recovery revalidation refetches them
7285
8227
  * once the last one is handled.
7286
8228
  */
7287
- function revalidateDiscardedWork(discardedWork, removedTempEntityKeys) {
8229
+ function revalidateDiscardedWork(discardedWork, removedEntityKeys) {
7288
8230
  const entities = [];
7289
- const skippedEntityKeys = new Set(removedTempEntityKeys);
8231
+ const skippedEntityKeys = new Set(removedEntityKeys);
7290
8232
  for (const resolution of resolutions.values()) for (const ref of resolution.entityRefs) skippedEntityKeys.add(ref.entityKey);
7291
8233
  for (const workItem of discardedWork) for (const ref of workItem.entityRefs) {
7292
8234
  if (skippedEntityKeys.has(ref.entityKey)) continue;
@@ -7303,6 +8245,64 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7303
8245
  if (entities.length === 0) return;
7304
8246
  storeAdapter.revalidateDiscardedEntities?.(entities, resolutions.size > 0);
7305
8247
  }
8248
+ /**
8249
+ * Queues `resolutionsToRequeue` again, in order, and removes them.
8250
+ * `sentResolutionId` is the resolution whose attempts were exhausted: the
8251
+ * server may have applied it.
8252
+ */
8253
+ async function requeueResolutions(current, resolutionsToRequeue, sentResolutionId) {
8254
+ const { queueOrders, nextQueueOrderValue } = previewQueueOrders(resolutionsToRequeue.length);
8255
+ nextQueueOrder = nextQueueOrderValue;
8256
+ const nextEntries = resolutionsToRequeue.map((resolution, index) => {
8257
+ const queueOrder = queueOrders[index];
8258
+ if (queueOrder === void 0) throw new Error("Missing queue order for replay resolution requeue");
8259
+ const entry = operations[resolution.operation] ? buildFreshQueueEntry({
8260
+ current,
8261
+ operation: resolution.operation,
8262
+ input: resolution.input,
8263
+ entityRefs: resolution.entityRefs,
8264
+ queueOrder,
8265
+ attachedUploadIds: resolution.attachedUploadIds,
8266
+ dependencyUploadIds: resolution.dependencyUploadIds,
8267
+ tempIds: resolution.tempIds
8268
+ }) : null;
8269
+ if (entry && resolution.id === sentResolutionId && !(resolution.kind === "retry-exhausted" && resolution.lastReplayError.message === BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE)) entry.attempts = 1;
8270
+ return {
8271
+ resolution,
8272
+ entry
8273
+ };
8274
+ });
8275
+ for (const nextEntry of nextEntries) {
8276
+ if (!nextEntry.entry) continue;
8277
+ await persistEntry(nextEntry.entry, current, true);
8278
+ }
8279
+ for (const resolution of resolutionsToRequeue) await removeResolution(resolution.id, current, true);
8280
+ storeAdapter.captureQueuedMutationOverlays?.({
8281
+ sessionKey: current.sessionKey,
8282
+ entityRefs: nextEntries.flatMap((nextEntry) => {
8283
+ return nextEntry.entry?.entityRefs ?? [];
8284
+ })
8285
+ });
8286
+ refreshDerivedState(current);
8287
+ await deleteOrphanedDependencyUploads(current, nextEntries.flatMap((nextEntry) => nextEntry.entry ? [] : [nextEntry.resolution]));
8288
+ await ensureReplayScheduled();
8289
+ }
8290
+ /**
8291
+ * Removes from `descendants` the ones that also wait for a creation still
8292
+ * held in a resolution outside them (other than `decidedResolutionId`),
8293
+ * directly or behind one such descendant: they cannot be sent yet and go
8294
+ * with the decision about that creation.
8295
+ */
8296
+ function dropDescendantsHeldElsewhere(descendants, dependencySnapshot, decidedResolutionId) {
8297
+ let removedHeldDescendant = true;
8298
+ while (removedHeldDescendant) {
8299
+ removedHeldDescendant = false;
8300
+ for (const resolution of descendants.values()) if ((dependencySnapshot.blockedByResolutionIdsByResolutionId.get(resolution.id) ?? []).some((blockerId) => blockerId !== decidedResolutionId && !descendants.has(blockerId))) {
8301
+ descendants.delete(resolution.id);
8302
+ removedHeldDescendant = true;
8303
+ }
8304
+ }
8305
+ }
7306
8306
  function collectRetryResolutionChain(args) {
7307
8307
  if (args.scope === "self") return [args.resolution];
7308
8308
  const dependencySnapshot = createResolutionDependencySnapshot();
@@ -7317,6 +8317,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7317
8317
  descendantResolutions.set(resolution.id, resolution);
7318
8318
  }
7319
8319
  }
8320
+ dropDescendantsHeldElsewhere(descendantResolutions, dependencySnapshot, args.resolution.id);
7320
8321
  const orderedDescendants = [];
7321
8322
  const remainingDescendants = [...descendantResolutions.values()].sort(compareResolutionRecords);
7322
8323
  const orderedIds = /* @__PURE__ */ new Set();
@@ -7360,6 +8361,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7360
8361
  input: validatedInput
7361
8362
  }),
7362
8363
  upload: args.upload,
8364
+ attachedUploadIds: args.attachedUploadIds,
7363
8365
  tempIds: args.tempIds,
7364
8366
  entityRefs: args.entityRefs
7365
8367
  };
@@ -7383,14 +8385,14 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7383
8385
  return result;
7384
8386
  }
7385
8387
  async function planPreparedMutation(args) {
7386
- const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue, replacedResolutionId } = args;
8388
+ const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, attachedUploadIds, tempIds: preparedTempIds, entityRefs: preparedEntityRefs, mayHaveBeenApplied }, queueOrder, workingQueue, replacedResolutionId } = args;
7387
8389
  const tempEntity = operation.tempEntity;
7388
8390
  const tempEntities = operation.tempEntities;
7389
8391
  if (operation.accumulation && operation.supersedes) throw new Error(`Offline operation "${operationName}" cannot configure accumulation and supersedes together`);
7390
8392
  if (tempEntity && tempEntities) throw new Error(`Offline operation "${operationName}" cannot configure tempEntity and tempEntities together`);
7391
8393
  if (storeType === "document" && (tempEntity || tempEntities)) throw new Error(`Document offline operation "${operationName}" does not support tempEntity or tempEntities`);
7392
8394
  if ((tempEntity || tempEntities) && "onSuccessExecute" in operation) throw new Error(`Offline operation "${operationName}" cannot configure onSuccessExecute when tempEntity or tempEntities is present`);
7393
- if (operation.accumulation && upload !== void 0) throw new Error(`Offline operation "${operationName}" cannot configure direct uploads together with accumulation`);
8395
+ if (operation.accumulation && (upload !== void 0 || attachedUploadIds !== void 0)) throw new Error(`Offline operation "${operationName}" cannot configure direct uploads together with accumulation`);
7394
8396
  const rawEntityRefs = getOperationRawEntityRefs(operation, operationName, validatedInput);
7395
8397
  const resolvedEntityRefs = resolveNormalizedRefs(rawEntityRefs);
7396
8398
  const hasTempLifecycle = tempEntity !== void 0 || tempEntities !== void 0;
@@ -7418,26 +8420,33 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7418
8420
  const now = Date.now();
7419
8421
  const pendingEntities = !storeAdapter.applyPendingEntity ? [] : tempEntity && tempIds?.[0] !== void 0 ? [{
7420
8422
  tempId: tempIds[0],
7421
- pendingEntity: tempEntity.buildPendingEntity(validatedInput, tempIds[0])
8423
+ pendingEntity: tempEntity.buildPendingEntity(validatedInput, tempIds[0]),
8424
+ addToQueries: typeof tempEntity.addToQueries === "function" ? tempEntity.addToQueries(validatedInput, tempIds[0]) : tempEntity.addToQueries,
8425
+ loadedFields: tempEntity.loadedFields
7422
8426
  }] : tempEntities && tempIds ? orderByTempIds({
7423
8427
  operationName,
7424
8428
  label: "Temp entities",
7425
8429
  tempIds,
7426
8430
  items: tempEntities.buildPendingEntities(validatedInput, tempIds).map((entry) => ({
7427
8431
  tempId: castTempLifecyclePayload(entry.tempId),
7428
- pendingEntity: entry.pendingEntity
8432
+ pendingEntity: entry.pendingEntity,
8433
+ addToQueries: entry.addToQueries,
8434
+ loadedFields: entry.loadedFields
7429
8435
  }))
7430
8436
  }) : [];
7431
8437
  if (operation.accumulation && (!tempIds || tempIds.length === 0)) {
7432
- const existingEntry = findAccumulationCandidate({
8438
+ const normalizedEntityRefs = normalizeEntityRefs(entityRefs);
8439
+ const heldResolution = findHeldWorkResolutions((resolution) => resolution.operation === operationName && (resolution.tempIds?.length ?? 0) === 0 && normalizeEntityRefs(resolution.entityRefs) === normalizedEntityRefs, replacedResolutionId).at(-1);
8440
+ const existingEntry = heldResolution ? void 0 : findAccumulationCandidate({
7433
8441
  operationName,
7434
8442
  entityRefs,
7435
8443
  entries: workingQueue.values()
7436
8444
  });
7437
- if (existingEntry) {
8445
+ const existingWork = heldResolution ?? existingEntry;
8446
+ if (existingWork) {
7438
8447
  const mergedInput = await operation.accumulation.mergeInput({
7439
8448
  sessionKey: current.sessionKey,
7440
- existingInput: existingEntry.input,
8449
+ existingInput: existingWork.input,
7441
8450
  incomingInput: validatedInput
7442
8451
  });
7443
8452
  const validatedMergedInput = validateWithSchema(operation.inputSchema, mergedInput);
@@ -7446,22 +8455,63 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7446
8455
  operationName,
7447
8456
  input: validatedMergedInput
7448
8457
  });
7449
- const nextEntry = {
7450
- ...existingEntry,
7451
- input: validatedMergedInput,
7452
- dependencyUploadIds: mergedDependencyUploadIds.length > 0 ? mergedDependencyUploadIds : void 0,
7453
- updatedAt: now
7454
- };
7455
- workingQueue.set(nextEntry.id, nextEntry);
7456
- return {
7457
- operationName,
7458
- validatedInput,
7459
- tempIds,
7460
- pendingEntities,
7461
- nextEntry,
7462
- removedEntries: [existingEntry],
7463
- accumulatedEntry: existingEntry
7464
- };
8458
+ const dependencyUploadIdsOfMerge = mergedDependencyUploadIds.length > 0 ? mergedDependencyUploadIds : void 0;
8459
+ if (heldResolution) {
8460
+ const nextResolution = {
8461
+ ...heldResolution,
8462
+ input: validatedMergedInput,
8463
+ dependencyUploadIds: dependencyUploadIdsOfMerge,
8464
+ updatedAt: now
8465
+ };
8466
+ if (isHeldBehindTempCreateResolution(nextResolution)) return {
8467
+ operationName,
8468
+ validatedInput,
8469
+ tempIds,
8470
+ pendingEntities,
8471
+ removedEntries: [],
8472
+ replacedResolution: nextResolution,
8473
+ accumulatedResolution: heldResolution
8474
+ };
8475
+ const nextEntry = buildFreshQueueEntry({
8476
+ current,
8477
+ operation: operationName,
8478
+ input: validatedMergedInput,
8479
+ queueOrder,
8480
+ entityRefs: heldResolution.entityRefs,
8481
+ dependencyUploadIds: dependencyUploadIdsOfMerge
8482
+ });
8483
+ workingQueue.set(nextEntry.id, nextEntry);
8484
+ return {
8485
+ operationName,
8486
+ validatedInput,
8487
+ tempIds,
8488
+ pendingEntities,
8489
+ nextEntry,
8490
+ removedEntries: [],
8491
+ removedResolutions: [heldResolution],
8492
+ accumulatedResolution: heldResolution
8493
+ };
8494
+ }
8495
+ if (existingEntry) {
8496
+ const nextEntry = {
8497
+ ...existingEntry,
8498
+ input: validatedMergedInput,
8499
+ dependencyUploadIds: dependencyUploadIdsOfMerge,
8500
+ updatedAt: now
8501
+ };
8502
+ if (!isHeldBehindTempCreateResolution(nextEntry)) {
8503
+ workingQueue.set(nextEntry.id, nextEntry);
8504
+ return {
8505
+ operationName,
8506
+ validatedInput,
8507
+ tempIds,
8508
+ pendingEntities,
8509
+ nextEntry,
8510
+ removedEntries: [existingEntry],
8511
+ accumulatedEntry: existingEntry
8512
+ };
8513
+ }
8514
+ }
7465
8515
  }
7466
8516
  }
7467
8517
  const supersededEntries = operation.supersedes ? findSupersededEntries({
@@ -7471,13 +8521,22 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7471
8521
  supersedes: operation.supersedes,
7472
8522
  entries: workingQueue.values()
7473
8523
  }) : [];
8524
+ const supersedes = operation.supersedes;
8525
+ const supersededResolutions = supersedes ? findHeldWorkResolutions((resolution) => resolution.entityRefs.length === 1 && isSameEntityRef(resolution.entityRefs[0], entityRefs[0]) && matchesSupersededOperation({
8526
+ candidateOperationName: resolution.operation,
8527
+ operationName,
8528
+ supersedes
8529
+ }), replacedResolutionId) : [];
7474
8530
  for (const entry of supersededEntries) workingQueue.delete(entry.id);
7475
- if (operation.supersedes?.dropSelfIfTempLifecycleCancelled && supersededEntries.some((entry) => entry.tempIds !== void 0 && entry.tempIds.length > 0)) return {
8531
+ const cancelledTempCreates = supersedes?.dropSelfIfTempLifecycleCancelled ? [...supersededEntries, ...supersededResolutions].filter((workItem) => (workItem.tempIds?.length ?? 0) > 0 || getClientIdCreatedEntityKeys(workItem).length > 0) : [];
8532
+ if (cancelledTempCreates.length > 0) return {
7476
8533
  operationName,
7477
8534
  validatedInput,
7478
8535
  tempIds,
7479
8536
  pendingEntities,
7480
- removedEntries: supersededEntries
8537
+ removedEntries: supersededEntries,
8538
+ removedResolutions: supersededResolutions,
8539
+ cancelledTempCreates
7481
8540
  };
7482
8541
  const nextEntry = buildFreshQueueEntry({
7483
8542
  current,
@@ -7486,9 +8545,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7486
8545
  queueOrder,
7487
8546
  entityRefs,
7488
8547
  attachedUploads: upload,
8548
+ attachedUploadIds,
7489
8549
  dependencyUploadIds: dependencyUploadIds.length > 0 ? dependencyUploadIds : void 0,
7490
8550
  tempIds
7491
8551
  });
8552
+ if (mayHaveBeenApplied && getClientIdCreatedEntityKeys(nextEntry).length > 0) nextEntry.attempts = 1;
7492
8553
  workingQueue.set(nextEntry.id, nextEntry);
7493
8554
  return {
7494
8555
  operationName,
@@ -7496,7 +8557,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7496
8557
  tempIds,
7497
8558
  pendingEntities,
7498
8559
  nextEntry,
7499
- removedEntries: supersededEntries
8560
+ removedEntries: supersededEntries,
8561
+ removedResolutions: supersededResolutions
7500
8562
  };
7501
8563
  }
7502
8564
  async function queuePreparedMutations(preparedMutation, replacedResolutionId) {
@@ -7506,7 +8568,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7506
8568
  const queueOrder = queueOrders[0];
7507
8569
  if (queueOrder === void 0) throw new Error("Missing queue order for prepared offline mutation");
7508
8570
  let plannedMutation;
7509
- do
8571
+ let pendingEntityQueriesLoaded = false;
8572
+ for (;;) {
7510
8573
  plannedMutation = await planPreparedMutation({
7511
8574
  current,
7512
8575
  preparedMutation,
@@ -7514,7 +8577,17 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7514
8577
  workingQueue: new Map(queueEntries),
7515
8578
  replacedResolutionId
7516
8579
  });
7517
- while (plannedMutation.accumulatedEntry && queueEntries.get(plannedMutation.accumulatedEntry.id) !== plannedMutation.accumulatedEntry);
8580
+ if (!pendingEntityQueriesLoaded) {
8581
+ pendingEntityQueriesLoaded = true;
8582
+ const loading = loadPendingEntityQueries(plannedMutation.pendingEntities);
8583
+ if (loading) {
8584
+ await loading;
8585
+ continue;
8586
+ }
8587
+ }
8588
+ if ((!plannedMutation.accumulatedEntry || queueEntries.get(plannedMutation.accumulatedEntry.id) === plannedMutation.accumulatedEntry) && (!plannedMutation.accumulatedResolution || resolutions.get(plannedMutation.accumulatedResolution.id) === plannedMutation.accumulatedResolution)) break;
8589
+ }
8590
+ const blockedResolution = plannedMutation.nextEntry && isHeldBehindTempCreateResolution(plannedMutation.nextEntry) ? buildRetryExhaustedResolutionRecord(current, plannedMutation.nextEntry, { message: BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE }) : void 0;
7518
8591
  const persistedMutations = [];
7519
8592
  const persistedUploadIds = [];
7520
8593
  const appliedPendingMutations = [];
@@ -7523,7 +8596,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7523
8596
  const appliedMutation = {
7524
8597
  ...plannedMutation,
7525
8598
  removedEntriesApplied: [],
7526
- touchedNextEntry: false
8599
+ removedResolutionsApplied: [],
8600
+ touchedNextEntry: false,
8601
+ touchedReplacedResolution: false
7527
8602
  };
7528
8603
  persistedMutations.push(appliedMutation);
7529
8604
  if (preparedMutation.upload && plannedMutation.nextEntry) {
@@ -7548,7 +8623,16 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7548
8623
  }
7549
8624
  if (plannedMutation.nextEntry) {
7550
8625
  appliedMutation.touchedNextEntry = true;
7551
- await persistEntry(plannedMutation.nextEntry, current, true);
8626
+ if (blockedResolution) await persistResolution(blockedResolution, current, true);
8627
+ else await persistEntry(plannedMutation.nextEntry, current, true);
8628
+ }
8629
+ if (plannedMutation.replacedResolution) {
8630
+ appliedMutation.touchedReplacedResolution = true;
8631
+ await persistResolution(plannedMutation.replacedResolution, current, true);
8632
+ }
8633
+ for (const removedResolution of plannedMutation.removedResolutions ?? []) {
8634
+ appliedMutation.removedResolutionsApplied.push(removedResolution);
8635
+ await removeResolution(removedResolution.id, current, true);
7552
8636
  }
7553
8637
  nextQueueOrder = nextQueueOrderValue;
7554
8638
  if (storeAdapter.applyPendingEntity && plannedMutation.pendingEntities.length > 0) {
@@ -7556,7 +8640,9 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7556
8640
  operationName: plannedMutation.operationName,
7557
8641
  input: plannedMutation.validatedInput,
7558
8642
  tempId: pendingEntity.tempId,
7559
- pendingEntity: pendingEntity.pendingEntity
8643
+ pendingEntity: pendingEntity.pendingEntity,
8644
+ addToQueries: pendingEntity.addToQueries,
8645
+ loadedFields: pendingEntity.loadedFields
7560
8646
  });
7561
8647
  appliedPendingMutations.push({
7562
8648
  operationName: plannedMutation.operationName,
@@ -7564,9 +8650,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7564
8650
  pendingEntities: plannedMutation.pendingEntities
7565
8651
  });
7566
8652
  }
7567
- if (plannedMutation.nextEntry) storeAdapter.captureQueuedMutationOverlays?.({
8653
+ const queuedWork = plannedMutation.nextEntry ?? plannedMutation.replacedResolution;
8654
+ if (queuedWork) storeAdapter.captureQueuedMutationOverlays?.({
7568
8655
  sessionKey: current.sessionKey,
7569
- entityRefs: plannedMutation.nextEntry.entityRefs
8656
+ entityRefs: queuedWork.entityRefs
7570
8657
  });
7571
8658
  } catch (error) {
7572
8659
  for (const mutation of appliedPendingMutations.reverse()) for (const pendingEntity of [...mutation.pendingEntities].reverse()) storeAdapter.rollbackPendingEntity?.({
@@ -7581,15 +8668,25 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7581
8668
  for (const mutation of persistedMutations.reverse()) {
7582
8669
  const nextEntryReplacesRemovedEntry = mutation.nextEntry !== void 0 && mutation.removedEntries.some((removedEntry) => removedEntry.id === mutation.nextEntry?.id);
7583
8670
  if (mutation.touchedNextEntry && mutation.nextEntry) {
7584
- if (!nextEntryReplacesRemovedEntry) await removeEntry(mutation.nextEntry.id, current, true);
8671
+ if (blockedResolution) await removeResolution(blockedResolution.id, current, true);
8672
+ else if (!nextEntryReplacesRemovedEntry) await removeEntry(mutation.nextEntry.id, current, true);
7585
8673
  }
7586
8674
  for (const removedEntry of nextEntryReplacesRemovedEntry ? [...mutation.removedEntries].reverse() : [...mutation.removedEntriesApplied].reverse()) await persistEntry(removedEntry, current, true);
8675
+ if (mutation.touchedReplacedResolution && mutation.accumulatedResolution) await persistResolution(mutation.accumulatedResolution, current, true);
8676
+ for (const removedResolution of [...mutation.removedResolutionsApplied].reverse()) await persistResolution(removedResolution, current, true);
7587
8677
  }
7588
8678
  nextQueueOrder = previousNextQueueOrder;
7589
8679
  refreshDerivedState(current);
7590
8680
  throw error;
7591
8681
  }
7592
- refreshDerivedState(current);
8682
+ const { cancelledTempCreates } = plannedMutation;
8683
+ let supersededWork = [...plannedMutation.removedEntries, ...plannedMutation.removedResolutions ?? []];
8684
+ if (plannedMutation.replacedResolution && plannedMutation.accumulatedResolution) supersededWork.push(plannedMutation.accumulatedResolution);
8685
+ if (cancelledTempCreates) {
8686
+ await discardTempLifecycles(current, cancelledTempCreates);
8687
+ supersededWork = supersededWork.filter((workItem) => !cancelledTempCreates.includes(workItem));
8688
+ } else refreshDerivedState(current);
8689
+ if (supersededWork.length > 0) await deleteOrphanedDependencyUploads(current, supersededWork);
7593
8690
  await ensureReplayScheduled();
7594
8691
  }
7595
8692
  async function ensureReplayScheduled() {
@@ -7690,10 +8787,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7690
8787
  createdAt: nextEntry.createdAt
7691
8788
  })) return;
7692
8789
  const operation = operations[nextEntry.operation];
7693
- if (!operation) {
7694
- await removeEntry(nextEntry.id, current);
7695
- continue;
7696
- }
8790
+ if (!operation) return;
7697
8791
  const shouldCheckSkipBeforeRetry = nextEntry.syncState === "needs-confirmation";
7698
8792
  const conflictHandling = operation.conflictHandling;
7699
8793
  const replayCheckBaseCtx = buildOperationBaseContext({
@@ -7708,6 +8802,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7708
8802
  lastAttemptAt: Date.now()
7709
8803
  };
7710
8804
  await persistEntry(entryToUse, current);
8805
+ let failedUploadId;
7711
8806
  try {
7712
8807
  const replayCheckCtx = Boolean(shouldCheckSkipBeforeRetry && operation.shouldSkipSync || conflictHandling) ? {
7713
8808
  ...replayCheckBaseCtx,
@@ -7717,6 +8812,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7717
8812
  if (!replayCheckCtx) throw new Error("Replay check context was not prepared");
7718
8813
  if (await operation.shouldSkipSync(replayCheckCtx)) {
7719
8814
  await removeEntry(entryToUse.id, current);
8815
+ deleteOrphanedDependencyUploads(current, [entryToUse]);
7720
8816
  continue;
7721
8817
  }
7722
8818
  }
@@ -7742,9 +8838,15 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7742
8838
  });
7743
8839
  continue;
7744
8840
  }
8841
+ const dependencyUploads = await current.session.resolveReplayUploadIds(entryToUse.dependencyUploadIds ?? []);
8842
+ if (dependencyUploads.failedUploadId !== void 0) {
8843
+ failedUploadId = dependencyUploads.failedUploadId;
8844
+ throw dependencyUploads.error;
8845
+ }
7745
8846
  const executeContext = __LEGIT_CAST__(await buildOperationExecuteContext({
7746
8847
  current,
7747
- entry: entryToUse
8848
+ entry: entryToUse,
8849
+ resolvedRefsById: dependencyUploads.refs
7748
8850
  }));
7749
8851
  const result = await operation.execute(executeContext);
7750
8852
  if (entryToUse.tempIds) await reconcileTempEntitiesFromResult({
@@ -7763,21 +8865,20 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7763
8865
  });
7764
8866
  if (isPromise(successfulExecuteSync)) await successfulExecuteSync;
7765
8867
  refreshDerivedState(current);
8868
+ deleteOrphanedDependencyUploads(current, [entryToUse]);
7766
8869
  } catch (error) {
7767
8870
  const lastError = { message: unknownToError(error).message };
7768
- const classification = await current.session.classifyFailure(error, {
7769
- phase: "sync",
7770
- storeType,
7771
- operationName: entryToUse.operation,
7772
- sessionKey: current.sessionKey
7773
- });
7774
- const allowReplayRetry = classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, {
8871
+ const failureCtx = {
7775
8872
  phase: "sync",
7776
8873
  storeType,
7777
8874
  operationName: entryToUse.operation,
7778
8875
  sessionKey: current.sessionKey
7779
- }) : false;
7780
- if (classification !== "ignore" || current.session.getStatus().isOfflineMode) {
8876
+ };
8877
+ if (failedUploadId !== void 0) failureCtx.uploadId = failedUploadId;
8878
+ const classification = await current.session.classifyFailure(error, failureCtx);
8879
+ const sessionEnabled = isSessionEnabled();
8880
+ const allowReplayRetry = sessionEnabled && classification === "ignore" && !current.session.getStatus().isOfflineMode ? await current.session.classifyRetriableFailure(error, failureCtx) : false;
8881
+ if (!sessionEnabled || classification !== "ignore" || current.session.getStatus().isOfflineMode) {
7781
8882
  entryToUse = {
7782
8883
  ...entryToUse,
7783
8884
  attempts: entryToUse.attempts + 1,
@@ -7802,7 +8903,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7802
8903
  lastError,
7803
8904
  allowReplayRetry
7804
8905
  };
7805
- if (allowReplayRetry && nextFailures >= replayRetryMaxFailures) {
8906
+ if (allowReplayRetry && nextFailures >= replayRetryMaxFailures || failedUploadId !== void 0 && !allowReplayRetry) {
7806
8907
  await persistManualResolutionChain({
7807
8908
  current,
7808
8909
  parentEntry: entryToUse,
@@ -7837,7 +8938,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7837
8938
  await current.session.refreshNetworkState();
7838
8939
  return {
7839
8940
  initialAction: getInitialOfflineMutationAction(current, prepared),
7840
- queueMutation: () => queuePreparedMutations(prepared),
8941
+ queueMutation: (afterDirectAttempt) => queuePreparedMutations(afterDirectAttempt ? {
8942
+ ...prepared,
8943
+ mayHaveBeenApplied: true
8944
+ } : prepared),
7841
8945
  handleDirectSuccess: () => clearOfflineStatusOnSuccess(prepared.currentSessionKey),
7842
8946
  classifyError: async (error) => {
7843
8947
  const preparedCurrent = ensureActiveSession();
@@ -7861,6 +8965,12 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7861
8965
  if (!current) return [];
7862
8966
  return current.session.getEntities().filter((entity) => entity.storeName === storeName);
7863
8967
  }
8968
+ function getItemOfflineState(itemKey) {
8969
+ const current = ensureActiveSession();
8970
+ if (!current) return null;
8971
+ const sessionState = current.session.store.state;
8972
+ return toItemOfflineState(getOfflineStoreEntityLookup(sessionState.entities, storeName).get(itemKey), sessionState.attemptedCreationEntityIds);
8973
+ }
7864
8974
  function getOfflineResolutions() {
7865
8975
  return buildDerivedResolutionRecords();
7866
8976
  }
@@ -7874,6 +8984,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7874
8984
  const operation = operations[operationName];
7875
8985
  if (!operation) {
7876
8986
  await removeResolution(resolutionId, current);
8987
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
7877
8988
  return;
7878
8989
  }
7879
8990
  if (isPersistedResolutionBlocked(resolutionRecord)) throw new Error("Cannot resolve a blocked offline resolution before its blocking dependencies are cleared");
@@ -7888,42 +8999,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7888
8999
  });
7889
9000
  return;
7890
9001
  }
7891
- const resolutionsToRetry = collectRetryResolutionChain({
9002
+ await requeueResolutions(current, collectRetryResolutionChain({
7892
9003
  resolution: resolutionRecord,
7893
9004
  scope: resolutionAction?.scope ?? "self-and-descendants"
7894
- });
7895
- const { queueOrders, nextQueueOrderValue } = previewQueueOrders(resolutionsToRetry.length);
7896
- nextQueueOrder = nextQueueOrderValue;
7897
- const nextEntries = resolutionsToRetry.map((retryResolution, index) => {
7898
- const queueOrder = queueOrders[index];
7899
- if (queueOrder === void 0) throw new Error("Missing queue order for replay resolution requeue");
7900
- return {
7901
- resolution: retryResolution,
7902
- entry: operations[retryResolution.operation] ? buildFreshQueueEntry({
7903
- current,
7904
- operation: retryResolution.operation,
7905
- input: retryResolution.input,
7906
- entityRefs: retryResolution.entityRefs,
7907
- queueOrder,
7908
- attachedUploadIds: retryResolution.attachedUploadIds,
7909
- dependencyUploadIds: retryResolution.dependencyUploadIds,
7910
- tempIds: retryResolution.tempIds
7911
- }) : null
7912
- };
7913
- });
7914
- for (const nextEntry of nextEntries) {
7915
- if (!nextEntry.entry) continue;
7916
- await persistEntry(nextEntry.entry, current, true);
7917
- }
7918
- for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
7919
- storeAdapter.captureQueuedMutationOverlays?.({
7920
- sessionKey: current.sessionKey,
7921
- entityRefs: nextEntries.flatMap((nextEntry) => {
7922
- return nextEntry.entry?.entityRefs ?? [];
7923
- })
7924
- });
7925
- refreshDerivedState(current);
7926
- await ensureReplayScheduled();
9005
+ }), resolutionRecord.id);
7927
9006
  return;
7928
9007
  }
7929
9008
  const resolutionAction = isObject(resolution) ? resolution : null;
@@ -7935,14 +9014,35 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7935
9014
  });
7936
9015
  return;
7937
9016
  }
9017
+ const heldDescendantIds = (action === "requeue" || action === "commit") && getTempLifecycleEntityKeys(resolutionRecord).length > 0 ? collectRetryResolutionChain({
9018
+ resolution: resolutionRecord,
9019
+ scope: "self-and-descendants"
9020
+ }).slice(1).map((descendant) => descendant.id) : [];
9021
+ const requeueHeldDescendants = async () => {
9022
+ const heldDescendants = /* @__PURE__ */ new Map();
9023
+ for (const id of heldDescendantIds) {
9024
+ const descendant = resolutions.get(id);
9025
+ if (descendant) heldDescendants.set(id, descendant);
9026
+ }
9027
+ if (heldDescendants.size === 0) return;
9028
+ dropDescendantsHeldElsewhere(heldDescendants, createResolutionDependencySnapshot(), void 0);
9029
+ if (heldDescendants.size === 0) return;
9030
+ await requeueResolutions(current, [...heldDescendants.values()], void 0);
9031
+ };
7938
9032
  if (action === "requeue") {
7939
- await queuePreparedMutations(prepareMutationWithSession(current, {
7940
- operation: operationName,
7941
- input: resolutionAction?.input,
7942
- tempIds: resolutionRecord.tempIds,
7943
- entityRefs: resolutionRecord.entityRefs
7944
- }), resolutionId);
9033
+ await queuePreparedMutations({
9034
+ ...prepareMutationWithSession(current, {
9035
+ operation: operationName,
9036
+ input: resolutionAction?.input,
9037
+ attachedUploadIds: resolutionRecord.attachedUploadIds,
9038
+ tempIds: resolutionRecord.tempIds,
9039
+ entityRefs: resolutionRecord.entityRefs
9040
+ }),
9041
+ mayHaveBeenApplied: true
9042
+ }, resolutionId);
7945
9043
  await removeResolution(resolutionId, current);
9044
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
9045
+ await requeueHeldDescendants();
7946
9046
  return;
7947
9047
  }
7948
9048
  if (action === "commit") {
@@ -7956,6 +9056,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7956
9056
  result: committedResult
7957
9057
  });
7958
9058
  await removeResolution(resolutionId, current);
9059
+ await deleteOrphanedDependencyUploads(current, [resolutionRecord]);
9060
+ await requeueHeldDescendants();
7959
9061
  return;
7960
9062
  }
7961
9063
  throw new Error("Invalid offline resolution action");
@@ -7984,6 +9086,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7984
9086
  function shouldTreatFetchAsOffline() {
7985
9087
  const current = ensureActiveSession();
7986
9088
  if (!current) return false;
9089
+ if (!isSessionEnabled()) {
9090
+ current.session.refreshNetworkState();
9091
+ return false;
9092
+ }
7987
9093
  return shouldTreatFutureOperationsAsOffline(current);
7988
9094
  }
7989
9095
  async function handleFetchSuccess() {
@@ -7992,7 +9098,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
7992
9098
  await clearOfflineStatusOnSuccess(current.sessionKey);
7993
9099
  }
7994
9100
  function canQueueMutation() {
7995
- return !isDisposed && getSessionKey() !== false;
9101
+ if (isDisposed || getSessionKey() === false) return false;
9102
+ if (isSessionEnabled()) return true;
9103
+ ensureActiveSession()?.session.refreshNetworkState();
9104
+ return false;
7996
9105
  }
7997
9106
  async function prepareForFetch() {
7998
9107
  await hydrateIfNeeded();
@@ -8007,6 +9116,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
8007
9116
  prepareForMutation,
8008
9117
  queueMutation,
8009
9118
  getOfflineEntities,
9119
+ getItemOfflineState,
8010
9120
  getOfflineResolutions,
8011
9121
  parseOfflineResolutionConflict: parseConflictPayloadForResolution,
8012
9122
  resolveOfflineResolution,
@@ -9034,7 +10144,8 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
9034
10144
  useOfflineStatus: getOfflineStatus,
9035
10145
  useOfflineEntities: () => EMPTY_OFFLINE_ENTITIES,
9036
10146
  useOfflineResolutions: () => EMPTY_OFFLINE_RESOLUTIONS,
9037
- useOfflineUploads: () => emptyUploads
10147
+ useOfflineUploads: () => emptyUploads,
10148
+ useOfflineUploadFile: (id) => id ? missingUploadFile : idleUploadFile
9038
10149
  };
9039
10150
  }
9040
10151
  function createStoreManager(options) {
@@ -9099,7 +10210,8 @@ function createStoreManager(options) {
9099
10210
  useOfflineStatus: () => resolvedOfflineSession.useOfflineStatus(),
9100
10211
  useOfflineEntities: () => resolvedOfflineSession.useOfflineEntities(),
9101
10212
  useOfflineResolutions: () => resolvedOfflineSession.useOfflineResolutions(),
9102
- useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads()
10213
+ useOfflineUploads: () => resolvedOfflineSession.useOfflineUploads(),
10214
+ useOfflineUploadFile: (id) => resolvedOfflineSession.useOfflineUploadFile(id)
9103
10215
  } : createDisabledStoreManagerOfflineApi(options.getSessionKey);
9104
10216
  const storeManager = {
9105
10217
  getSessionKey: options.getSessionKey,
@@ -9189,7 +10301,7 @@ function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
9189
10301
  };
9190
10302
  }
9191
10303
  function resolveStoreManagerOfflineSession(storeManager, storeName, usesOfflineStorage) {
9192
- const offlineSession = __LEGIT_CAST__(storeManagerOfflineSessionRegistry.get(storeManager));
10304
+ const offlineSession = storeManagerOfflineSessionRegistry.get(storeManager);
9193
10305
  if (!usesOfflineStorage) return null;
9194
10306
  if (!offlineSession) throw new Error(`[tsdf] Store "${storeName}" has persistentStorage.offline configured but storeManager was created without offlineSession`);
9195
10307
  return offlineSession;
@@ -9866,34 +10978,6 @@ function useRegisterActiveKeys(keys, registerActiveKeys, touchKeys) {
9866
10978
  * ```
9867
10979
  */
9868
10980
  const IsOffScreenContext = createContext(false);
9869
- //#endregion
9870
- //#region src/persistentStorage/offline/entityMetadata.ts
9871
- function createOfflineEntityLookup(entities) {
9872
- const entitiesByKey = /* @__PURE__ */ new Map();
9873
- for (const entity of entities) entitiesByKey.set(entity.entityKey, entity);
9874
- return entitiesByKey;
9875
- }
9876
- function getIsPendingOfflineSync(entity) {
9877
- return !!entity && !entity.requiresResolution;
9878
- }
9879
- function hasPendingOfflineSync(entitiesByKey, entityKeys) {
9880
- for (const entityKey of entityKeys) if (getIsPendingOfflineSync(entitiesByKey.get(entityKey))) return true;
9881
- return false;
9882
- }
9883
- function shouldApplyOfflineOverlay(entity, overlay) {
9884
- return !!entity && (!entity.requiresResolution || entity.blockedResolutionCount > 0 || entity.childResolutionCount > 0 || typeof overlay === "object" && overlay !== null && "keepVisibleWhileResolutionRequired" in overlay && overlay.keepVisibleWhileResolutionRequired === true);
9885
- }
9886
- /**
9887
- * Batch-filters offline overlays to only include entries with a pending sync
9888
- * (entity exists and does not require resolution). Use this instead of calling
9889
- * {@link getActiveOfflineOverlay} per item when all active overlays are needed
9890
- * at once.
9891
- */
9892
- function filterActiveOfflineOverlays(entitiesByKey, overlays) {
9893
- const result = {};
9894
- for (const [entityKey, overlay] of Object.entries(overlays)) if (shouldApplyOfflineOverlay(entitiesByKey.get(entityKey), overlay)) result[entityKey] = overlay;
9895
- return result;
9896
- }
9897
10981
  function observeAutomaticFetchStatus(state, signature, currentStatus) {
9898
10982
  if (currentStatus === "success") {
9899
10983
  state.delete(signature);
@@ -10263,6 +11347,14 @@ function createCollectionStore(storeOptions) {
10263
11347
  finalPayload
10264
11348
  });
10265
11349
  },
11350
+ loadTempEntities: async (tempIds) => {
11351
+ if (!persistence?.hasAsyncPreload) return;
11352
+ const unloadedItemKeys = filterAndMap(tempIds, (tempId) => {
11353
+ const itemKey = getItemKey(__LEGIT_CAST__(tempId));
11354
+ return Object.hasOwn(store.state, itemKey) ? false : itemKey;
11355
+ });
11356
+ if (unloadedItemKeys.length > 0) await persistence.preloadItems(unloadedItemKeys);
11357
+ },
10266
11358
  applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
10267
11359
  storeEvents.emit("tempEntityReconciled", {
10268
11360
  tempId: __LEGIT_CAST__(tempId),
@@ -10639,7 +11731,7 @@ function createCollectionStore(storeOptions) {
10639
11731
  error: new AbortedStoreError()
10640
11732
  };
10641
11733
  let item = getItemFromStateOrPersistence(itemId, { materializeSyncState: true });
10642
- if (item?.error?.id === "offline") {
11734
+ if (isOfflineStoreError(item?.error)) {
10643
11735
  const hydratedItem = persistence?.readHydratedItem(itemId);
10644
11736
  if (hydratedItem?.data) {
10645
11737
  item = hydratedItem;
@@ -10851,18 +11943,18 @@ function createCollectionStore(storeOptions) {
10851
11943
  const payloadToUse = payload === null ? [] : payload;
10852
11944
  const affectedItems = Array.isArray(payloadToUse) ? payloadToUse : [payloadToUse];
10853
11945
  const affectedItemEntries = getItemsKeyArray(payloadToUse);
10854
- if (offline && offlineController && !offlineController.canQueueMutation()) return Result.err(toStoreMutationError(new OfflineSessionUnavailableError(), errorNormalizer));
10855
11946
  const mutationId = getAutoIncrementId();
10856
11947
  storeEvents.emit("mutationStart", {
10857
11948
  mutationId,
10858
11949
  items: affectedItems
10859
11950
  });
10860
11951
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
10861
- let accepted = false;
10862
- const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
11952
+ const runOnlineMutation = async () => ({
10863
11953
  kind: "online",
10864
11954
  data: await directMutation()
10865
- }), (exception, rollbacks) => {
11955
+ });
11956
+ let accepted = false;
11957
+ const result = await performMutationWithLifecycle(() => startMutation(payloadToUse), offline ? () => offlineController?.canQueueMutation() ? runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : runOnlineMutation() : runOnlineMutation, (exception, rollbacks) => {
10866
11958
  const error = toStoreMutationError(exception, errorNormalizer);
10867
11959
  const revertedItems = /* @__PURE__ */ new Map();
10868
11960
  const changedItems = /* @__PURE__ */ new Map();
@@ -11127,6 +12219,8 @@ function createCollectionStore(storeOptions) {
11127
12219
  inactiveScope: id,
11128
12220
  storeName: resolvedPersistentStorageConfig ? id : void 0
11129
12221
  }),
12222
+ useItemOfflineState: (itemPayload) => useOfflineStoreItemState(getSessionKeyForRuntime(), id, resolvedPersistentStorageConfig ? id : void 0, itemPayload === false || itemPayload == null ? null : getItemKey(itemPayload)),
12223
+ getItemOfflineState: (itemPayload) => offlineController?.getItemOfflineState(getItemKey(itemPayload)) ?? null,
11130
12224
  useOfflineResolutions: () => useOfflineStoreResolutions({
11131
12225
  sessionKey: getSessionKeyForRuntime(),
11132
12226
  inactiveScope: id,
@@ -11201,7 +12295,7 @@ function setupDocumentPersistence(config) {
11201
12295
  let preloadPromise = null;
11202
12296
  let syncHydrationMissKnown = false;
11203
12297
  function isOfflineNetworkActive() {
11204
- return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig().network);
12298
+ return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig());
11205
12299
  }
11206
12300
  function readSyncHydratedDocumentData() {
11207
12301
  if (localStorageAdapter === null) return null;
@@ -11532,7 +12626,6 @@ function createDocumentStore(storeOptions) {
11532
12626
  }, testOptions?.browserTabsTransportFactory, import.meta.env.DEV ? storeManager.debugLogger : void 0, browserTabsTabId, getStoreManagerAppVersion(storeManager));
11533
12627
  async function executeFetch(fetchCtx) {
11534
12628
  const currentStatus = store.state.status;
11535
- const wasLoadedBeforeFetch = currentStatus === "success";
11536
12629
  store.setPartialState({
11537
12630
  status: currentStatus === "success" ? "refetching" : "loading",
11538
12631
  error: null,
@@ -11542,7 +12635,7 @@ function createDocumentStore(storeOptions) {
11542
12635
  const result = await runOfflineAwareFetch(offlineController, () => fetchFn(fetchCtx.signal));
11543
12636
  if (!result.ok) {
11544
12637
  if (result.offline) {
11545
- store.setPartialState(wasLoadedBeforeFetch ? {
12638
+ store.setPartialState(store.state.data !== null ? {
11546
12639
  error: null,
11547
12640
  status: "success"
11548
12641
  } : {
@@ -11747,18 +12840,18 @@ function createDocumentStore(storeOptions) {
11747
12840
  const pendingDebounceRollbacks = /* @__PURE__ */ new Map();
11748
12841
  const optimisticMutations = createOptimisticMutationTracker();
11749
12842
  async function performMutation({ optimisticUpdate, mutation, debounce, silentErrors, revalidateOnSuccess, offline, upload }) {
11750
- if (offline && offlineController && !offlineController.canQueueMutation()) return Result.err(toStoreMutationError(new OfflineSessionUnavailableError(), errorNormalizer));
11751
12843
  const mutationId = getAutoIncrementId();
11752
12844
  storeEvents.emit("mutationStart", { mutationId });
11753
12845
  const directMutation = async () => unwrapTSDFResult(await mutation({
11754
12846
  updateState,
11755
12847
  currentState: store.state.data
11756
12848
  }));
11757
- let accepted = false;
11758
- const result = await performMutationWithLifecycle(startMutation, offline ? () => runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : async () => ({
12849
+ const runOnlineMutation = async () => ({
11759
12850
  kind: "online",
11760
12851
  data: await directMutation()
11761
- }), (exception, rollbacks) => {
12852
+ });
12853
+ let accepted = false;
12854
+ const result = await performMutationWithLifecycle(startMutation, offline ? () => offlineController?.canQueueMutation() ? runHybridOfflineMutation(__LEGIT_CAST__(offlineController), offline, upload, directMutation) : runOnlineMutation() : runOnlineMutation, (exception, rollbacks) => {
11762
12855
  let data = store.state.data;
11763
12856
  let changedSince = false;
11764
12857
  for (let i = rollbacks.length - 1; i >= 0; i--) {
@@ -12025,6 +13118,14 @@ function toItemState(persisted, dataSchema, shouldIgnoreItem) {
12025
13118
  loadedFields
12026
13119
  };
12027
13120
  }
13121
+ /**
13122
+ * Whether the rows left of a persisted list are its first rows, so only its
13123
+ * end is missing (e.g. cut by the byte budget). Like `maxQuerySize`
13124
+ * truncation, such a list is still a loaded list that has more pages.
13125
+ */
13126
+ function isOnlyTailMissing(remainingItemKeys, persistedItemKeys) {
13127
+ return remainingItemKeys.length > 0 && isStrictItemKeyPrefix(remainingItemKeys, persistedItemKeys);
13128
+ }
12028
13129
  function limitPersistedQueryItems(itemKeys, hasMore, maxQuerySize) {
12029
13130
  const limitedItemKeys = itemKeys.slice(0, maxQuerySize);
12030
13131
  return {
@@ -12209,6 +13310,7 @@ function setupListQueryPersistence(config, options = {}) {
12209
13310
  const querySizeBytesByKey = /* @__PURE__ */ new Map();
12210
13311
  const hydratedPersistedItemKeys = /* @__PURE__ */ new Set();
12211
13312
  const hydratedPersistedQueryKeys = /* @__PURE__ */ new Set();
13313
+ const incompleteRestoredQueryKeys = /* @__PURE__ */ new Set();
12212
13314
  const budgetEvictedItemRecency = /* @__PURE__ */ new Map();
12213
13315
  const budgetEvictedQueryRecency = /* @__PURE__ */ new Map();
12214
13316
  const syncHydrationItemMissCache = createTimedKeySet();
@@ -12218,7 +13320,7 @@ function setupListQueryPersistence(config, options = {}) {
12218
13320
  let maintenanceCallbackKey = null;
12219
13321
  const pendingLocalQueryReconciliationSessions = /* @__PURE__ */ new Set();
12220
13322
  function isOfflineNetworkActive() {
12221
- return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig().network);
13323
+ return isOfflineNetworkModeActiveSync(config.offline?.session.getConfig());
12222
13324
  }
12223
13325
  function clearSaveTimer() {
12224
13326
  if (saveTimer !== null) {
@@ -12275,6 +13377,7 @@ function setupListQueryPersistence(config, options = {}) {
12275
13377
  items: entry.items,
12276
13378
  hasMore: entry.hasMore,
12277
13379
  lastAccessAt: entry.lastAccessAt,
13380
+ missingItems: entry.missingItems === true,
12278
13381
  offlineProtected: entry.offlineProtected,
12279
13382
  rawValue: rawEntry,
12280
13383
  sizeBytes
@@ -12361,6 +13464,7 @@ function setupListQueryPersistence(config, options = {}) {
12361
13464
  payload: data.payload,
12362
13465
  items: data.items,
12363
13466
  hasMore: data.hasMore,
13467
+ missingItems: data.missingItems,
12364
13468
  version
12365
13469
  }));
12366
13470
  rememberQueryMetadataSize(queryKey, sizeBytes);
@@ -12468,6 +13572,7 @@ function setupListQueryPersistence(config, options = {}) {
12468
13572
  payload: entry.payload,
12469
13573
  items: entry.items,
12470
13574
  hasMore: entry.hasMore,
13575
+ missingItems: entry.missingItems,
12471
13576
  version
12472
13577
  }));
12473
13578
  rememberQueryMetadataSize(queryKey, sizeBytes);
@@ -12645,6 +13750,7 @@ function setupListQueryPersistence(config, options = {}) {
12645
13750
  }
12646
13751
  function forgetPersistedQuery(queryKey) {
12647
13752
  hydratedPersistedQueryKeys.delete(queryKey);
13753
+ incompleteRestoredQueryKeys.delete(queryKey);
12648
13754
  querySnapshotByKey.delete(queryKey);
12649
13755
  querySizeBytesByKey.delete(queryKey);
12650
13756
  knownPersistedQueryKeys?.delete(queryKey);
@@ -12780,11 +13886,21 @@ function setupListQueryPersistence(config, options = {}) {
12780
13886
  const snapshot = querySnapshotByKey.get(queryKey);
12781
13887
  return snapshot ? parseHydratedQuerySnapshot(snapshot) : void 0;
12782
13888
  }
12783
- function filterRetainableHydratedSuffix(suffixItemKeys) {
12784
- return suffixItemKeys.filter((itemKey) => {
13889
+ /**
13890
+ * Returns the cached rows that can follow a refreshed first page. Stops at
13891
+ * the first row that can't be restored: keeping the rows after it would
13892
+ * save a list with a hole that is later restored as a complete one. The
13893
+ * query still has more pages, so the rows left out are loaded again.
13894
+ */
13895
+ function getRetainableHydratedSuffix(previousPersistedQuery, suffixItemKeys) {
13896
+ if (previousPersistedQuery.missingItems) return [];
13897
+ const retainable = [];
13898
+ for (const itemKey of suffixItemKeys) {
12785
13899
  const hydratedItem = readHydratedItem(itemKey);
12786
- return hydratedItem?.item != null && !shouldIgnoreItem(hydratedItem.itemQuery.payload);
12787
- });
13900
+ if (hydratedItem?.item == null || shouldIgnoreItem(hydratedItem.itemQuery.payload)) break;
13901
+ retainable.push(itemKey);
13902
+ }
13903
+ return retainable;
12788
13904
  }
12789
13905
  async function hydrateMissingAsyncItems(itemKeys) {
12790
13906
  if (localStorageAdapter !== null) return;
@@ -12828,7 +13944,8 @@ function setupListQueryPersistence(config, options = {}) {
12828
13944
  const persistedQuery = parsePersistedListQueryData({
12829
13945
  payload: entry.payload,
12830
13946
  items: entry.items,
12831
- hasMore: entry.hasMore
13947
+ hasMore: entry.hasMore,
13948
+ missingItems: entry.missingItems
12832
13949
  }, config.queryPayloadSchema);
12833
13950
  if (!persistedQuery) {
12834
13951
  syncHydrationQueryMissCache.remember(queryKey);
@@ -12843,24 +13960,43 @@ function setupListQueryPersistence(config, options = {}) {
12843
13960
  rememberHydratedQuery(queryKey, {
12844
13961
  payload: persistedQuery.payload,
12845
13962
  items: persistedQuery.items,
12846
- hasMore: persistedQuery.hasMore
13963
+ hasMore: persistedQuery.hasMore,
13964
+ ...persistedQuery.missingItems ? { missingItems: true } : {}
12847
13965
  }, getSerializedStringSize(rawEntry));
12848
13966
  return persistedQuery;
12849
13967
  }
12850
- function buildHydratedQueryState(persistedQuery) {
12851
- const limitedQuery = limitPersistedQueryItems(persistedQuery.items.filter((itemKey) => {
12852
- return readHydratedItem(itemKey) !== void 0;
12853
- }), persistedQuery.hasMore, maxQuerySize);
13968
+ /**
13969
+ * Builds the state of a query restored from storage. A persisted query
13970
+ * lists the rows it had when it was saved. When some of them can no longer
13971
+ * be restored (evicted by the byte budget, discarded on read, ...), the rows
13972
+ * that are left are still restored. If only the end of the list is missing,
13973
+ * it is restored as loaded with more pages, like `maxQuerySize` truncation.
13974
+ * Otherwise (a gap before a row that is left, or no row left) the query is
13975
+ * not restored as loaded: it would be reported as a complete `success` with
13976
+ * a list missing rows. A query that was not loaded is reported as `loading`
13977
+ * and always fetched, and fails with the offline error while offline.
13978
+ */
13979
+ function createRestoredQueryState(queryKey, persistedQuery, restoredItemKeys) {
13980
+ const hasAllRows = !persistedQuery.missingItems && restoredItemKeys.length === persistedQuery.items.length;
13981
+ const isTailMissing = !hasAllRows && !persistedQuery.missingItems && isOnlyTailMissing(restoredItemKeys, persistedQuery.items);
13982
+ const wasLoaded = hasAllRows || isTailMissing;
13983
+ const limitedQuery = limitPersistedQueryItems(restoredItemKeys, persistedQuery.hasMore || isTailMissing, maxQuerySize);
13984
+ if (!wasLoaded) incompleteRestoredQueryKeys.add(queryKey);
12854
13985
  return {
12855
13986
  error: null,
12856
13987
  hasMore: limitedQuery.hasMore,
12857
13988
  items: limitedQuery.itemKeys,
12858
13989
  payload: persistedQuery.payload,
12859
13990
  refetchOnMount: "lowPriority",
12860
- status: "success",
12861
- wasLoaded: true
13991
+ status: wasLoaded ? "success" : "loading",
13992
+ wasLoaded
12862
13993
  };
12863
13994
  }
13995
+ function buildHydratedQueryState(queryKey, persistedQuery) {
13996
+ return createRestoredQueryState(queryKey, persistedQuery, persistedQuery.items.filter((itemKey) => {
13997
+ return readHydratedItem(itemKey) !== void 0;
13998
+ }));
13999
+ }
12864
14000
  function createInitialState(baseState) {
12865
14001
  syncMaintenanceRegistration();
12866
14002
  return baseState;
@@ -12872,7 +14008,7 @@ function setupListQueryPersistence(config, options = {}) {
12872
14008
  }
12873
14009
  function readHydratedQuery(queryKey) {
12874
14010
  const persistedQuery = readPersistedQueryData(queryKey);
12875
- return persistedQuery ? buildHydratedQueryState(persistedQuery) : void 0;
14011
+ return persistedQuery ? buildHydratedQueryState(queryKey, persistedQuery) : void 0;
12876
14012
  }
12877
14013
  function resolveAsyncPreloadedItem(itemKey, cached, currentGeneration) {
12878
14014
  if (currentGeneration !== generation || !storeRef) return false;
@@ -12966,18 +14102,9 @@ function setupListQueryPersistence(config, options = {}) {
12966
14102
  if (!persistedQuery) return false;
12967
14103
  const activeStore = storeRef;
12968
14104
  for (const itemKey of persistedQuery.items) preloadItem(itemKey);
12969
- const limitedQuery = limitPersistedQueryItems(persistedQuery.items.filter((itemKey) => {
14105
+ materializeHydratedQueryState(queryKey, createRestoredQueryState(queryKey, persistedQuery, persistedQuery.items.filter((itemKey) => {
12970
14106
  return activeStore.state.items[itemKey] !== void 0 && activeStore.state.itemQueries[itemKey] !== void 0;
12971
- }), persistedQuery.hasMore, maxQuerySize);
12972
- materializeHydratedQueryState(queryKey, {
12973
- error: null,
12974
- hasMore: limitedQuery.hasMore,
12975
- items: limitedQuery.itemKeys,
12976
- payload: persistedQuery.payload,
12977
- refetchOnMount: "lowPriority",
12978
- status: "success",
12979
- wasLoaded: true
12980
- });
14107
+ })));
12981
14108
  return true;
12982
14109
  }
12983
14110
  const existingPromise = pendingQueryPreloads.get(queryKey);
@@ -12995,23 +14122,15 @@ function setupListQueryPersistence(config, options = {}) {
12995
14122
  await preloadItems(persistedQuery.items);
12996
14123
  if (currentGeneration !== generation || activeStore !== storeRef) return false;
12997
14124
  if (activeStore.state.queries[queryKey] !== void 0) return true;
12998
- const limitedQuery = limitPersistedQueryItems(persistedQuery.items.filter((itemKey) => {
14125
+ const filteredItemKeys = persistedQuery.items.filter((itemKey) => {
12999
14126
  return activeStore.state.items[itemKey] !== void 0 && activeStore.state.itemQueries[itemKey] !== void 0;
13000
- }), persistedQuery.hasMore, maxQuerySize);
14127
+ });
13001
14128
  suppressedPersistedStateFlushes++;
13002
14129
  activeStore.setState({
13003
14130
  ...activeStore.state,
13004
14131
  queries: {
13005
14132
  ...activeStore.state.queries,
13006
- [queryKey]: {
13007
- error: null,
13008
- hasMore: limitedQuery.hasMore,
13009
- items: limitedQuery.itemKeys,
13010
- payload: persistedQuery.payload,
13011
- refetchOnMount: "lowPriority",
13012
- status: "success",
13013
- wasLoaded: true
13014
- }
14133
+ [queryKey]: createRestoredQueryState(queryKey, persistedQuery, filteredItemKeys)
13015
14134
  }
13016
14135
  });
13017
14136
  return true;
@@ -13325,18 +14444,23 @@ function setupListQueryPersistence(config, options = {}) {
13325
14444
  knownPersistedQueryKeys = null;
13326
14445
  return;
13327
14446
  }
13328
- const limitedQuery = limitPersistedQueryItems(queryData.items.filter((itemKey) => keptItemKeys.has(itemKey)), queryData.hasMore, maxQuerySize);
14447
+ const filteredItems = queryData.items.filter((itemKey) => keptItemKeys.has(itemKey));
14448
+ const hasMissingRows = filteredItems.length < queryData.items.length;
14449
+ const isTailMissing = hasMissingRows && !queryData.missingItems && isOnlyTailMissing(filteredItems, queryData.items);
14450
+ const limitedQuery = limitPersistedQueryItems(filteredItems, queryData.hasMore || isTailMissing, maxQuerySize);
13329
14451
  if (limitedQuery.itemKeys.length === queryData.items.length && limitedQuery.hasMore === queryData.hasMore) continue;
13330
14452
  const nextQueryData = {
13331
14453
  payload: queryData.payload,
13332
14454
  items: limitedQuery.itemKeys,
13333
- hasMore: limitedQuery.hasMore
14455
+ hasMore: limitedQuery.hasMore,
14456
+ ...queryData.missingItems || hasMissingRows && !isTailMissing ? { missingItems: true } : {}
13334
14457
  };
13335
14458
  let saved = true;
13336
14459
  if (idleContext === void 0) await saveLocalStorageQueryEntry(queryData.queryKey, nextQueryData);
13337
14460
  else if (localMaintenanceScope !== void 0) saved = await saveLocalStorageQueryEntryIfUnchanged(queryData, nextQueryData, idleContext, localMaintenanceScope);
13338
14461
  else saved = false;
13339
14462
  if (!saved) staleQueryFound = true;
14463
+ else if (querySnapshotByKey.has(queryData.queryKey)) querySnapshotByKey.set(queryData.queryKey, JSON.stringify(nextQueryData));
13340
14464
  }
13341
14465
  if (staleQueryFound) {
13342
14466
  knownPersistedQueryKeys = null;
@@ -13447,7 +14571,14 @@ function setupListQueryPersistence(config, options = {}) {
13447
14571
  const persistedQueryItemKeys = /* @__PURE__ */ new Set();
13448
14572
  for (const [, query] of queryEntries) for (const itemKey of query.items) queryReferencedItemKeys.add(itemKey);
13449
14573
  for (const [queryKey, query] of queryEntries) {
13450
- if (query.status !== "success" && !query.wasLoaded) continue;
14574
+ if (query.status !== "success" && !query.wasLoaded) {
14575
+ if (incompleteRestoredQueryKeys.has(queryKey)) {
14576
+ nextQueryKeys.add(queryKey);
14577
+ for (const itemKey of query.items) persistedQueryItemKeys.add(itemKey);
14578
+ }
14579
+ continue;
14580
+ }
14581
+ if (incompleteRestoredQueryKeys.size > 0) incompleteRestoredQueryKeys.delete(queryKey);
13451
14582
  const filteredItems = query.items.filter((itemKey) => {
13452
14583
  const hasItemInState = Object.hasOwn(state.items, itemKey);
13453
14584
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
@@ -13462,7 +14593,7 @@ function setupListQueryPersistence(config, options = {}) {
13462
14593
  if (previousPersistedQuery && isStrictItemKeyPrefix(filteredItems, previousPersistedQuery.items)) {
13463
14594
  const suffixItemKeys = previousPersistedQuery.items.slice(filteredItems.length);
13464
14595
  await hydrateMissingAsyncItems(suffixItemKeys);
13465
- const cachedSuffix = filterRetainableHydratedSuffix(suffixItemKeys);
14596
+ const cachedSuffix = getRetainableHydratedSuffix(previousPersistedQuery, suffixItemKeys);
13466
14597
  queryItemsToPersist = [...filteredItems, ...cachedSuffix];
13467
14598
  }
13468
14599
  }
@@ -13611,6 +14742,7 @@ function setupListQueryPersistence(config, options = {}) {
13611
14742
  const finalPersistedQueryKeys = new Set(previousKnownLocalQueryKeys);
13612
14743
  for (const [queryKey, query] of queryEntries) {
13613
14744
  if (query.status !== "success" && !query.wasLoaded) continue;
14745
+ if (incompleteRestoredQueryKeys.size > 0) incompleteRestoredQueryKeys.delete(queryKey);
13614
14746
  const filteredItems = query.items.filter((itemKey) => {
13615
14747
  const hasItemInState = Object.hasOwn(state.items, itemKey);
13616
14748
  const hasItemQueryInState = Object.hasOwn(state.itemQueries, itemKey);
@@ -13625,7 +14757,7 @@ function setupListQueryPersistence(config, options = {}) {
13625
14757
  if (previousPersistedQuery && isStrictItemKeyPrefix(filteredItems, previousPersistedQuery.items)) {
13626
14758
  const suffixItemKeys = previousPersistedQuery.items.slice(filteredItems.length);
13627
14759
  await hydrateMissingAsyncItems(suffixItemKeys);
13628
- const cachedSuffix = filterRetainableHydratedSuffix(suffixItemKeys);
14760
+ const cachedSuffix = getRetainableHydratedSuffix(previousPersistedQuery, suffixItemKeys);
13629
14761
  queryItemsToPersist = [...filteredItems, ...cachedSuffix];
13630
14762
  }
13631
14763
  }
@@ -13642,6 +14774,7 @@ function setupListQueryPersistence(config, options = {}) {
13642
14774
  for (const queryKey of previousKnownLocalQueryKeys) {
13643
14775
  if (finalQueryDataByKey.has(queryKey)) continue;
13644
14776
  if (!hydratedPersistedQueryKeys.has(queryKey)) continue;
14777
+ if (incompleteRestoredQueryKeys.has(queryKey)) continue;
13645
14778
  finalPersistedQueryKeys.delete(queryKey);
13646
14779
  }
13647
14780
  const commitTimestamp = Date.now();
@@ -13916,6 +15049,7 @@ function setupListQueryPersistence(config, options = {}) {
13916
15049
  pendingQueryPreloads.clear();
13917
15050
  hydratedPersistedItemKeys.clear();
13918
15051
  hydratedPersistedQueryKeys.clear();
15052
+ incompleteRestoredQueryKeys.clear();
13919
15053
  syncHydrationItemMissCache.clearAll();
13920
15054
  syncHydrationQueryMissCache.clearAll();
13921
15055
  knownPersistedItemKeys = null;
@@ -13951,6 +15085,7 @@ function setupListQueryPersistence(config, options = {}) {
13951
15085
  budgetEvictedQueryRecency.clear();
13952
15086
  hydratedPersistedItemKeys.clear();
13953
15087
  hydratedPersistedQueryKeys.clear();
15088
+ incompleteRestoredQueryKeys.clear();
13954
15089
  syncHydrationItemMissCache.clearAll();
13955
15090
  syncHydrationQueryMissCache.clearAll();
13956
15091
  await Promise.all([itemNamespace.clear(), clearLocalStorageQueries()]);
@@ -14360,6 +15495,7 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14360
15495
  const { payload, limit, fields } = fetchPayload;
14361
15496
  const offset = !!offsetPagination && fetchPayload.type === "loadMore" && fetchPayload.offset > 0 ? Math.min(fetchPayload.offset, store.state.queries[queryKey]?.items.length ?? fetchPayload.offset) : fetchPayload.offset;
14362
15497
  const appendToExisting = !!offsetPagination && fetchPayload.type === "loadMore" && offset > 0;
15498
+ let failure = null;
14363
15499
  try {
14364
15500
  const useChunkedInvalidation = offsetPagination && !appendToExisting && limit > offsetPagination.maxInvalidationLimit;
14365
15501
  let allItems;
@@ -14380,7 +15516,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14380
15516
  signal: fetchCtx.signal,
14381
15517
  fields
14382
15518
  })).then((result) => {
14383
- if (!result.ok) throw result.offline ? offlineConnectivityError : result.error;
15519
+ if (!result.ok) {
15520
+ failure ??= result;
15521
+ throw result.offline ? offlineConnectivityError : result.error;
15522
+ }
14384
15523
  return result.data;
14385
15524
  })));
14386
15525
  const successResults = (await Promise.all(chunkResultPromises)).map((r) => r.unwrap());
@@ -14392,7 +15531,10 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14392
15531
  signal: fetchCtx.signal,
14393
15532
  fields
14394
15533
  }));
14395
- if (!fetchResult.ok) throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
15534
+ if (!fetchResult.ok) {
15535
+ failure = fetchResult;
15536
+ throw fetchResult.offline ? offlineConnectivityError : fetchResult.error;
15537
+ }
14396
15538
  const result = fetchResult.data;
14397
15539
  allItems = result.items;
14398
15540
  hasMore = result.hasMore;
@@ -14411,11 +15553,12 @@ async function executeQueryFetch(requests, fetchCtx, store, normalizedFetchListF
14411
15553
  results.set(queryKey, false);
14412
15554
  return;
14413
15555
  }
14414
- const error = exception && typeof exception === "object" && "id" in exception && exception.id === "offline" ? offlineConnectivityError : normalizeStoreError(exception, errorNormalizer);
15556
+ const failedOffline = failure?.offline === true;
15557
+ const error = failedOffline ? offlineConnectivityError : normalizeStoreError(failure && !failure.offline ? failure.error : exception, errorNormalizer);
14415
15558
  store.produceState((draft) => {
14416
15559
  const query = draft.queries[queryKey];
14417
15560
  if (!query) return;
14418
- if (error === offlineConnectivityError && query.wasLoaded) {
15561
+ if (failedOffline && query.wasLoaded) {
14419
15562
  query.status = "success";
14420
15563
  query.error = null;
14421
15564
  } else {
@@ -14830,7 +15973,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
14830
15973
  function loadMoreFromHydratedQuery(queryKey, queryState, loadSize, fields) {
14831
15974
  if (!persistence) return "skipped";
14832
15975
  const hydratedQuery = persistence.readHydratedQuery(queryKey);
14833
- if (!hydratedQuery) return "skipped";
15976
+ if (!hydratedQuery?.wasLoaded) return "skipped";
14834
15977
  if (!isStrictItemKeyPrefix(queryState.items, hydratedQuery.items)) return "skipped";
14835
15978
  const start = queryState.items.length;
14836
15979
  const end = Math.min(start + loadSize, hydratedQuery.items.length);
@@ -14919,9 +16062,9 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
14919
16062
  hasMore: false
14920
16063
  };
14921
16064
  let query = getQueryStateByKey(queryKey);
14922
- if (query?.error?.id === "offline") {
16065
+ if (isOfflineStoreError(query?.error)) {
14923
16066
  const hydratedQuery = persistence?.readHydratedQuery(queryKey);
14924
- if (hydratedQuery) {
16067
+ if (hydratedQuery?.wasLoaded) {
14925
16068
  query = hydratedQuery;
14926
16069
  store.produceState((draft) => {
14927
16070
  draft.queries[queryKey] = hydratedQuery;
@@ -15028,7 +16171,7 @@ function createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchIte
15028
16171
  error: new AbortedStoreError()
15029
16172
  };
15030
16173
  let itemState = readItemState(itemKey);
15031
- if (itemState?.itemQuery?.error?.id === "offline") {
16174
+ if (isOfflineStoreError(itemState?.itemQuery?.error)) {
15032
16175
  const hydratedItem = persistence?.readHydratedItem(itemKey);
15033
16176
  if (hydratedItem) {
15034
16177
  itemState = hydratedItem;
@@ -15740,11 +16883,12 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
15740
16883
  }
15741
16884
  return someItemWasUpdated;
15742
16885
  }
15743
- function addItemToState(itemPayload, data, options = {}) {
16886
+ function addItemToState(itemPayload, data, options = {}, loadedFields) {
15744
16887
  const itemKey = getItemKey(itemPayload);
15745
16888
  store.batch(() => {
15746
16889
  store.produceState((draftState) => {
15747
16890
  draftState.items[itemKey] = data;
16891
+ if (loadedFields !== void 0) draftState.itemLoadedFields[itemKey] = loadedFields;
15748
16892
  draftState.itemQueries[itemKey] = {
15749
16893
  status: "success",
15750
16894
  wasLoaded: true,
@@ -15813,7 +16957,6 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
15813
16957
  }
15814
16958
  async function performMutation(payload, { optimisticUpdate, mutation, silentErrors, revalidateOnSuccess, onSuccess, onError, debounce, offline, upload }) {
15815
16959
  const payloadToUse = payload === null ? [] : payload;
15816
- if (offline && offlineController && !offlineController.canQueueMutation()) return Result.err(toStoreMutationError(new OfflineSessionUnavailableError(), errorNormalizer));
15817
16960
  const affectedItemEntries = optimisticUpdate ? getItemsKeyArray(payloadToUse) : void 0;
15818
16961
  const affectedItems = affectedItemEntries ? affectedItemEntries.map(({ payload: p }) => p) : resolveAffectedItems(payloadToUse);
15819
16962
  const normalizedRevalidateOnSuccess = normalizeRevalidateOnSuccessOption(revalidateOnSuccess);
@@ -15829,6 +16972,10 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
15829
16972
  items: affectedItems
15830
16973
  });
15831
16974
  const directMutation = async () => unwrapTSDFResult(await mutation(payloadToUse));
16975
+ const runOnlineMutation = async () => ({
16976
+ kind: "online",
16977
+ data: await directMutation()
16978
+ });
15832
16979
  let accepted = false;
15833
16980
  const result = await performMutationWithLifecycle(() => {
15834
16981
  const endBaseMutations = startItemMutation(payloadToUse);
@@ -15836,10 +16983,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
15836
16983
  endBaseMutations();
15837
16984
  for (const endQueryMutation of optimisticMutationQueryContext.dynamicQueryMutationEnders) endQueryMutation();
15838
16985
  };
15839
- }, offline ? () => runHybridOfflineMutation(offlineController, offline, upload, directMutation) : async () => ({
15840
- kind: "online",
15841
- data: await directMutation()
15842
- }), (exception, rollbacks) => {
16986
+ }, offline ? () => offlineController?.canQueueMutation() ? runHybridOfflineMutation(offlineController, offline, upload, directMutation) : runOnlineMutation() : runOnlineMutation, (exception, rollbacks) => {
15843
16987
  const error = toStoreMutationError(exception, errorNormalizer);
15844
16988
  revertOptimisticMutations(rollbacks, mutationId);
15845
16989
  if (onMutationError) onMutationError(exception, { silentErrors });
@@ -16265,7 +17409,7 @@ const cacheMissError = {
16265
17409
  id: "cache-miss",
16266
17410
  message: "Cache miss"
16267
17411
  };
16268
- 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) {
17412
+ 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) {
16269
17413
  const isOffScreenFromContext = useContext(IsOffScreenContext);
16270
17414
  const queriesWithId = useMemo(() => {
16271
17415
  return items.map((itemProps) => {
@@ -16370,17 +17514,24 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16370
17514
  };
16371
17515
  }
16372
17516
  let status = itemQuery.status;
17517
+ let error = itemQuery.error;
17518
+ let hasMissingRequestedData = false;
16373
17519
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
16374
17520
  if (partialResources && Array.isArray(fields) && fields.length > 0 && (status === "success" || status === "refetching")) {
16375
17521
  if (getGenuinelyMissingRequestedFields(itemKey, {
16376
17522
  item: rawItemState,
16377
17523
  loadedFields
16378
- }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
17524
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) {
17525
+ hasMissingRequestedData = true;
17526
+ status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
17527
+ }
16379
17528
  } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
16380
17529
  const isIncomplete = !snapshotIsFullyLoaded(loadedFields, rawItemState, partialResources.inferFields) && !(itemsPendingFullInvalidation.has(itemKey) && hasCachedDataInState);
16381
17530
  const isStale = !isIncomplete && !snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, rawItemState, partialResources.inferFields, itemsPendingFullInvalidation);
16382
- if (isIncomplete) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
16383
- else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
17531
+ if (isIncomplete) {
17532
+ hasMissingRequestedData = true;
17533
+ status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
17534
+ } else if (isStale || itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) status = "refetching";
16384
17535
  }
16385
17536
  if (partialResources && showPartialAsRefetching) {
16386
17537
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16391,12 +17542,20 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16391
17542
  }
16392
17543
  }
16393
17544
  if (partialResources && status === "refetching" && Array.isArray(fields) && fields.length > 0 && itemFieldInvalidationFields && !fields.some((f) => itemFieldInvalidationFields.includes(f))) status = "success";
17545
+ if (status === "refetching" && !hasMissingRequestedData && isOfflineMode && itemQuery.status === "success") {
17546
+ status = "success";
17547
+ loadingFields = void 0;
17548
+ }
16394
17549
  if (!returnRefetchingStatus && status === "refetching") status = "success";
16395
17550
  const shouldHideDataWhileLoading = status === "loading" && partialResources;
17551
+ if (hasMissingRequestedData && itemQuery.status === "success" && isOfflineMode) {
17552
+ status = "error";
17553
+ error = offlineConnectivityError;
17554
+ }
16396
17555
  return {
16397
17556
  itemStateKey: itemKey,
16398
17557
  status,
16399
- error: itemQuery.error,
17558
+ error,
16400
17559
  isLoading: status === "loading",
16401
17560
  ...loadingFields ? { loadingFields } : {},
16402
17561
  data: shouldHideDataWhileLoading ? selector ? selector(null, resolvedItemPayload) : __LEGIT_CAST__(null) : data,
@@ -16408,6 +17567,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16408
17567
  }, [
16409
17568
  activeOfflineOverlays,
16410
17569
  getUnresolvedPendingInvalidationFields,
17570
+ isOfflineMode,
16411
17571
  itemsPendingFullInvalidation,
16412
17572
  loadFromStateOnly,
16413
17573
  offlineEntitiesByKey,
@@ -16617,7 +17777,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16617
17777
  const hasMissingFields = missingFields.length > 0;
16618
17778
  const hasStaleInvalidatedFields = staleInvalidatedFields.length > 0;
16619
17779
  const shouldFetchForInvalidation = hasStaleInvalidatedFields && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
16620
- if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive) {
17780
+ if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive && !isOfflineMode) {
16621
17781
  shouldFetch = true;
16622
17782
  requiredFetch = true;
16623
17783
  fieldsToFetch = Array.from(new Set([...missingFields, ...staleInvalidatedFields]));
@@ -16628,7 +17788,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16628
17788
  const hasStaleFullInvalidation = hasUnresolvedFullInvalidation && !!item;
16629
17789
  const missingFullItem = !hasStaleFullInvalidation && (!snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation);
16630
17790
  const shouldFetchForInvalidation = !missingFullItem && (unresolvedPendingInvalidationFields.length > 0 || hasStaleFullInvalidation) && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
16631
- if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive) {
17791
+ if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive && !isOfflineMode) {
16632
17792
  shouldFetch = true;
16633
17793
  requiredFetch = true;
16634
17794
  fieldsToFetch = missingFullItem || hasStaleFullInvalidation ? "*" : unresolvedPendingInvalidationFields;
@@ -16659,6 +17819,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16659
17819
  fetchQueriesWithId,
16660
17820
  getUnresolvedPendingInvalidationFields,
16661
17821
  ignoreItemsInRefetchOnMount,
17822
+ isOfflineMode,
16662
17823
  itemHasMissingRequestedData,
16663
17824
  itemPendingInvalidationFields,
16664
17825
  itemsPendingFullInvalidation,
@@ -16673,6 +17834,14 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
16673
17834
  }
16674
17835
  //#endregion
16675
17836
  //#region src/listQueryStore/useMultipleListQueries.ts
17837
+ /**
17838
+ * Whether the cached query has rows after `items` that offline `loadMore` can
17839
+ * append. A cached list missing some of its rows can't: its next rows may come
17840
+ * after a missing row.
17841
+ */
17842
+ function canLoadMoreFromCachedQuery(items, cachedQuery) {
17843
+ return cachedQuery?.wasLoaded === true && isStrictItemKeyPrefix(items, cachedQuery.items);
17844
+ }
16676
17845
  function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, showPartialAsRefetching: allItemsShowPartialAsRefetching, omitPayload: allItemsOmitPayload, disableRefetches: allItemsDisableRefetches, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, loadSize: allItemsLoadSize, debouncePayload }, store, events, getQueryKey, registerActiveQueries, touchQueries, getQueryState, readFallbackQueryState, preloadQueries, preloadQueriesBeforePaint, preloadDerivedQueryItems, readFallbackItemState, scheduleAutomaticListQueryFetch, queryInvalidationWasTriggered, itemPendingInvalidationFields, itemsPendingFullInvalidation, globalDisableRefetchOnMount, partialResources, derivedQueries, isOfflineMode, offlineEntities, offlineOverlays) {
16677
17846
  const isOffScreenFromContext = useContext(IsOffScreenContext);
16678
17847
  const queriesWithId = useMemo(() => {
@@ -16852,7 +18021,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16852
18021
  };
16853
18022
  const groupKey = derivedQueries.getQueryGroup(queryConfig.payload);
16854
18023
  if (!isOfflineMode && !stickyDerived) {
16855
- const groupQueries = Object.values(state.queries).filter((query) => derivedQueries.getQueryGroup(query.payload) === groupKey).map((query) => ({
18024
+ const groupQueries = Object.values(state.queries).filter((query) => query.wasLoaded && derivedQueries.getQueryGroup(query.payload) === groupKey).map((query) => ({
16856
18025
  payload: query.payload,
16857
18026
  hasMore: query.hasMore,
16858
18027
  itemCount: query.items.length
@@ -16932,6 +18101,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16932
18101
  let staleOrMissingRequestedFields;
16933
18102
  let hasAnyIncompleteItem = false;
16934
18103
  let hasAnyStaleItem = false;
18104
+ let hasMissingRequestedData = false;
16935
18105
  const statusCanBeOverridden = status === "success" || status === "refetching";
16936
18106
  if (partialResources && (statusCanBeOverridden || showPartialAsRefetching)) {
16937
18107
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16954,17 +18124,23 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16954
18124
  item: state.items[itemKey],
16955
18125
  loadedFields: state.itemLoadedFields[itemKey]
16956
18126
  }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0);
16957
- if (!hasCachedItemsInState) status = "loading";
16958
- else if (someItemMissingFieldDataInState) status = showPartialAsRefetching ? "refetching" : "loading";
16959
- else status = "refetching";
18127
+ if (!hasCachedItemsInState) {
18128
+ hasMissingRequestedData = true;
18129
+ status = "loading";
18130
+ } else if (someItemMissingFieldDataInState) {
18131
+ hasMissingRequestedData = true;
18132
+ status = showPartialAsRefetching ? "refetching" : "loading";
18133
+ } else status = "refetching";
16960
18134
  } else if (partialResources && fields === "*" && statusCanBeOverridden) {
16961
18135
  const hasAnyFieldInvalidation = effectiveQuery.query.items.some((itemKey) => {
16962
18136
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
16963
18137
  return !!itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0;
16964
18138
  });
16965
- if (hasAnyIncompleteItem) if (!hasCachedItemsInState) status = "loading";
16966
- else status = showPartialAsRefetching ? "refetching" : "loading";
16967
- else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
18139
+ if (hasAnyIncompleteItem) {
18140
+ hasMissingRequestedData = true;
18141
+ if (!hasCachedItemsInState) status = "loading";
18142
+ else status = showPartialAsRefetching ? "refetching" : "loading";
18143
+ } else if (hasAnyStaleItem || hasAnyFieldInvalidation) status = "refetching";
16968
18144
  }
16969
18145
  if (partialResources && showPartialAsRefetching) {
16970
18146
  if (Array.isArray(fields) && fields.length > 0) {
@@ -16975,16 +18151,26 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
16975
18151
  if (pendingInvalidationFields.length > 0) loadingFields = pendingInvalidationFields;
16976
18152
  }
16977
18153
  }
18154
+ if (status === "refetching" && !hasMissingRequestedData && isOfflineMode && effectiveQuery.query.status === "success") {
18155
+ status = "success";
18156
+ loadingFields = void 0;
18157
+ }
16978
18158
  if (!returnRefetchingStatus && status === "refetching") status = "success";
18159
+ const shouldHideItemsWhileLoading = status === "loading" && partialResources;
18160
+ let error = effectiveQuery.query.error;
18161
+ if (hasMissingRequestedData && isOfflineMode && effectiveQuery.query.status === "success") {
18162
+ status = "error";
18163
+ error = offlineConnectivityError;
18164
+ }
16979
18165
  return {
16980
18166
  queryKey,
16981
18167
  status,
16982
- items: status === "loading" && partialResources ? [] : selectVisibleItems(visibleItemKeys, fields, (itemKey) => ({
18168
+ items: shouldHideItemsWhileLoading ? [] : selectVisibleItems(visibleItemKeys, fields, (itemKey) => ({
16983
18169
  item: state.items[itemKey],
16984
18170
  itemPayload: state.itemQueries[itemKey]?.payload
16985
18171
  })),
16986
- error: effectiveQuery.query.error,
16987
- hasMore: isOfflineMode ? !!readFallbackQueryState && effectiveQuery.query.hasMore && isStrictItemKeyPrefix(effectiveQuery.query.items, readFallbackQueryState(queryKey)?.items ?? []) : effectiveQuery.query.hasMore,
18172
+ error,
18173
+ hasMore: isOfflineMode ? effectiveQuery.query.hasMore && canLoadMoreFromCachedQuery(effectiveQuery.query.items, readFallbackQueryState?.(queryKey)) : effectiveQuery.query.hasMore,
16988
18174
  isDerived: effectiveQuery.isDerived,
16989
18175
  ...loadingFields ? { loadingFields } : {},
16990
18176
  isLoading: status === "loading",
@@ -17014,7 +18200,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17014
18200
  if (result.status !== "loading" && result.status !== "idle") return result;
17015
18201
  if (queryConfig && readFallbackQueryState && !store.state.queries[queryConfig.key]?.wasLoaded && !(derivedQueries && (isOfflineMode || stickyDerivedQueryKeys.has(queryConfig.key)))) {
17016
18202
  const fallbackQuery = readFallbackQueryState(queryConfig.key);
17017
- if (fallbackQuery && readFallbackItemState) {
18203
+ if (fallbackQuery?.wasLoaded && readFallbackItemState) {
17018
18204
  const visibleItemKeys = getVisibleQueryItemKeys(result.queryKey, fallbackQuery.items);
17019
18205
  const requestedFields = Array.isArray(queryConfig.fields) ? queryConfig.fields : void 0;
17020
18206
  const requiresFullItems = queryConfig.fields === "*";
@@ -17215,7 +18401,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17215
18401
  requiredFetch = false;
17216
18402
  shouldFetch = !!queryState?.refetchOnMount;
17217
18403
  }
17218
- if (partialResources && !shouldFetch && effectiveQueryState) {
18404
+ if (partialResources && !shouldFetch && effectiveQueryState && !isOfflineMode) {
17219
18405
  const isQueryFetchInFlight = effectiveQueryState.status === "loading" || effectiveQueryState.status === "refetching" || effectiveQueryState.status === "loadingMore";
17220
18406
  if (Array.isArray(fields) && fields.length > 0) {
17221
18407
  let hasStaleOrMissingRequestedFields = false;
@@ -17307,6 +18493,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
17307
18493
  itemsPendingFullInvalidation,
17308
18494
  getHighestPendingInvalidationPriority,
17309
18495
  getUnresolvedPendingInvalidationFields,
18496
+ isOfflineMode,
17310
18497
  queryItemsHaveMissingRequestedData,
17311
18498
  stickyDerivedQueryKeys
17312
18499
  ]);
@@ -17547,7 +18734,7 @@ function createListQueryStore(storeOptions) {
17547
18734
  }
17548
18735
  let offlineController = null;
17549
18736
  function isOfflineFetchModeActive() {
17550
- return (offlineController?.shouldTreatFetchAsOffline() ?? false) || resolvedOfflineConfig?.session.getOfflineStatus().isOfflineMode === true || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
18737
+ return (offlineController?.shouldTreatFetchAsOffline() ?? false) || resolvedOfflineConfig?.session.getOfflineStatus().isOfflineMode === true || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig());
17551
18738
  }
17552
18739
  const offlineFetchController = {
17553
18740
  prepareForFetch: () => offlineController?.prepareForFetch() ?? Promise.resolve(),
@@ -17830,9 +19017,9 @@ function createListQueryStore(storeOptions) {
17830
19017
  if (sessionKey === false) return [];
17831
19018
  return entityRefs.map((ref) => createProtectedStorageKey(sessionKey, id, "listQuery.item", ref.entityKey, resolvedPersistentStorageConfig.adapter !== "local-sync" ? "async" : "localStorage"));
17832
19019
  },
17833
- applyPendingEntity: ({ tempId, pendingEntity }) => {
19020
+ applyPendingEntity: ({ tempId, pendingEntity, addToQueries, loadedFields }) => {
17834
19021
  if (!pendingEntity || typeof pendingEntity !== "object") return;
17835
- addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity));
19022
+ addItemToState(__LEGIT_CAST__(tempId), __LEGIT_CAST__(pendingEntity), addToQueries && { addItemToQueries: addToQueries }, partialResources ? loadedFields : void 0);
17836
19023
  },
17837
19024
  rollbackPendingEntity: ({ tempId }) => {
17838
19025
  deleteItemState(__LEGIT_CAST__(tempId));
@@ -17840,6 +19027,7 @@ function createListQueryStore(storeOptions) {
17840
19027
  reconcileTempEntity: ({ tempId, reconciliation }) => {
17841
19028
  reconcileOfflineTempItem(tempId, reconciliation.finalPayload, reconciliation.finalData);
17842
19029
  },
19030
+ loadTempEntities: (tempIds, addToQueries) => loadOfflineTempEntities(__LEGIT_CAST__(tempIds), addToQueries),
17843
19031
  applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
17844
19032
  if (!runWithoutBroadcast(() => reconcileOfflineTempItem(tempId, finalPayload, void 0))) emitTempItemReconciled(tempId, finalPayload);
17845
19033
  },
@@ -17945,6 +19133,23 @@ function createListQueryStore(storeOptions) {
17945
19133
  });
17946
19134
  }
17947
19135
  /**
19136
+ * Loads offline temp items, and the queries they are declared into, that are
19137
+ * only in persistent storage: the queries then receive the pending items,
19138
+ * and reconciliation reads the items' data and loaded fields from memory.
19139
+ * Returns `undefined` when there is nothing to load.
19140
+ */
19141
+ function loadOfflineTempEntities(tempPayloads, addToQueries) {
19142
+ if (!persistence) return void 0;
19143
+ const unloadedItemKeys = filterAndMap(tempPayloads, (tempPayload) => {
19144
+ const itemKey = getItemKey(tempPayload);
19145
+ return store.state.items[itemKey] === void 0 ? itemKey : false;
19146
+ });
19147
+ const unloadedQueries = /* @__PURE__ */ new Map();
19148
+ for (const { queries } of addToQueries) for (const { key, payload } of getQueriesKeyArray(queries)) if (store.state.queries[key] === void 0) unloadedQueries.set(key, payload);
19149
+ if (unloadedItemKeys.length === 0 && unloadedQueries.size === 0) return;
19150
+ return Promise.all([unloadedItemKeys.length > 0 && persistence.preloadItems(unloadedItemKeys), unloadedQueries.size > 0 && preloadQueryFromPersistentStorage([...unloadedQueries.values()])]);
19151
+ }
19152
+ /**
17948
19153
  * Replaces an offline temp item with its final one, in place in every query
17949
19154
  * that lists it. Returns `false` when there is no data for the final item.
17950
19155
  */
@@ -17960,8 +19165,9 @@ function createListQueryStore(storeOptions) {
17960
19165
  queryKey,
17961
19166
  index: query.items.indexOf(tempItemKey)
17962
19167
  })).filter(({ index }) => index !== -1);
19168
+ const tempLoadedFields = store.state.itemLoadedFields[tempItemKey];
17963
19169
  deleteItemState(tempPayload);
17964
- addItemToState(finalPayload, finalData);
19170
+ addItemToState(finalPayload, finalData, void 0, tempLoadedFields);
17965
19171
  emitTempItemReconciled(tempId, finalPayloadValue);
17966
19172
  if (queryMemberships.length === 0) return true;
17967
19173
  store.produceState((draft) => {
@@ -18213,16 +19419,24 @@ function createListQueryStore(storeOptions) {
18213
19419
  }
18214
19420
  applyRemoteQuerySnapshot(message);
18215
19421
  }
19422
+ /**
19423
+ * Reactive version of `isOfflineFetchModeActive` for the hooks: it re-renders
19424
+ * them when the session enters or leaves offline mode, and, unlike the
19425
+ * session status getter, reads nothing that writes state during render.
19426
+ */
19427
+ function useIsStoreOfflineMode() {
19428
+ return useOfflineStoreIsOfflineMode({
19429
+ sessionKey: getSessionKeyForRuntime(),
19430
+ inactiveScope: id
19431
+ }) || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig());
19432
+ }
18216
19433
  const useMultipleListQueries$2 = function useMultipleListQueries$1(queries, options = {}) {
18217
19434
  const offlineEntities = useOfflineStoreEntities({
18218
19435
  sessionKey: getSessionKeyForRuntime(),
18219
19436
  inactiveScope: id,
18220
19437
  storeName: resolvedPersistentStorageConfig ? id : void 0
18221
19438
  });
18222
- const isStoreOfflineMode = useOfflineStoreStatus({
18223
- sessionKey: getSessionKeyForRuntime(),
18224
- inactiveScope: id
18225
- }).isOfflineMode || isOfflineNetworkModeActiveSync(resolvedOfflineConfig?.session.getConfig().network);
19439
+ const isStoreOfflineMode = useIsStoreOfflineMode();
18226
19440
  const offlineOverlaysSelector = useCallback((state) => {
18227
19441
  return state;
18228
19442
  }, []);
@@ -18242,7 +19456,8 @@ function createListQueryStore(storeOptions) {
18242
19456
  return state;
18243
19457
  }, []);
18244
19458
  const offlineOverlays = offlineOverlayStore.useSelector(offlineOverlaysSelector);
18245
- 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);
19459
+ const isStoreOfflineMode = useIsStoreOfflineMode();
19460
+ 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);
18246
19461
  };
18247
19462
  const useItem$3 = function useItem$2(itemPayload, options = {}) {
18248
19463
  return useItem(itemPayload, options, store, scheduleItemFetch, useMultipleItems$3);
@@ -18438,8 +19653,8 @@ function createListQueryStore(storeOptions) {
18438
19653
  touchUpdatedItemEntries(itemEntries);
18439
19654
  return wasUpdated;
18440
19655
  }
18441
- function addItemToState(itemPayload, data, options) {
18442
- addItemToStateBase(itemPayload, data, options);
19656
+ function addItemToState(itemPayload, data, options, loadedFields) {
19657
+ addItemToStateBase(itemPayload, data, options, loadedFields);
18443
19658
  touchUpdatedItemEntries([{
18444
19659
  itemKey: getItemKey(itemPayload),
18445
19660
  payload: itemPayload
@@ -18490,6 +19705,8 @@ function createListQueryStore(storeOptions) {
18490
19705
  inactiveScope: id,
18491
19706
  storeName: resolvedPersistentStorageConfig ? id : void 0
18492
19707
  }),
19708
+ useItemOfflineState: (itemPayload) => useOfflineStoreItemState(getSessionKeyForRuntime(), id, resolvedPersistentStorageConfig ? id : void 0, itemPayload === false || itemPayload == null ? null : getItemKey(itemPayload)),
19709
+ getItemOfflineState: (itemPayload) => offlineController?.getItemOfflineState(getItemKey(itemPayload)) ?? null,
18493
19710
  useOfflineResolutions: () => useOfflineStoreResolutions({
18494
19711
  sessionKey: getSessionKeyForRuntime(),
18495
19712
  inactiveScope: id,
@@ -18706,4 +19923,4 @@ var OpfsOfflineUploadDriver = class {
18706
19923
  };
18707
19924
  const opfsOfflineUploadAdapter = new OpfsOfflineUploadDriver();
18708
19925
  //#endregion
18709
- export { GET_ALL, IsOffScreenContext, StoreFetchError, StoreMutationError, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
19926
+ export { GET_ALL, IsOffScreenContext, StoreFetchError, StoreMutationError, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, isOfflineStoreError, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };