tsdf 18.3.0 → 18.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/async-storage.d.ts +1 -1
- package/dist/{asyncStorageAdapter-BDWpJ1vC.d.ts → asyncStorageAdapter-D_Ltk0xg.d.ts} +1 -1
- package/dist/indexed-db-storage.d.ts +1 -1
- package/dist/main.d.ts +10 -2
- package/dist/main.js +388 -78
- package/dist/opfs-storage.d.ts +1 -1
- package/dist/{opfsPersistentStorage-CcdWYuhc.d.ts → opfsPersistentStorage-HRMP5gzd.d.ts} +1 -1
- package/dist/{types-2UJIjziu.d.ts → types-DeZ9VDOe.d.ts} +6 -0
- package/docs/offline.md +27 -9
- package/package.json +1 -1
package/dist/async-storage.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-
|
|
1
|
+
import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-D_Ltk0xg.js";
|
|
2
2
|
export { createAsyncStorageAdapter };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-
|
|
1
|
+
import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-DeZ9VDOe.js";
|
|
2
2
|
|
|
3
3
|
//#region src/persistentStorage/asyncStorageAdapter.d.ts
|
|
4
4
|
declare function createAsyncStorageAdapter(driver: AsyncStorageDriver): AsyncStorageAdapter;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as AsyncStorageAdapter } from "./types-
|
|
1
|
+
import { t as AsyncStorageAdapter } from "./types-DeZ9VDOe.js";
|
|
2
2
|
//#region src/persistentStorage/indexedDbAsyncStorageAdapter.d.ts
|
|
3
3
|
/** Options for creating the IndexedDB persistent storage adapter. */
|
|
4
4
|
type IndexedDbPersistentStorageOptions = {
|
package/dist/main.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as OfflineResolutionConflictParseError, $t as TSFDUseListQueryReturn, A as DefineListQueryOfflineOperations, At as OfflineUploadTransportContext, B as OfflineEntityMutationKind, Bt as ListQueryUseMultipleItemsQuery, C as PersistentStorageSchema, Cn as TSDFFocusDebugOperation, Ct as OfflineSessionUploadsConfig, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadProgress, E as CollectionOfflineEntityRef, Et as OfflineUploadAdapter, F as ListQueryOfflineEntityRef, Ft as DerivedQuerySource, G as OfflineMutationQueueingPolicy, Gt as OptimisticListUpdate, H as OfflineMutationInput, Ht as OffsetPaginationConfig, I as ListQueryOfflineOperationDefinition, It as FetchListFnReturn, J as OfflineReplayRetryConfig, Jt as QueryStatus, K as OfflineOperationKind, Kt as PartialResourcesConfig, L as OfflineAccumulationConfig, Lt as FetchListFnReturnItem, M as DocumentOfflineOperationDefinition, Mt as SaveOfflineUploadArgs, N as GlobalOfflineEntity, Nt as DerivedQueriesConfig, O as DefineCollectionOfflineOperations, Ot as OfflineUploadSource, P as GlobalOfflineStatus, Pt as DerivedQueryContext, Q as OfflineResolutionActionForOperation, Qt as TSFDUseListItemReturn, R as OfflineAccumulationMergeContext, Rt as FieldsInput, S as PersistentStoragePreloadResult, Sn as TSDFDebugLogger, St as OfflineOperationUploadsContext, T as AnyOfflineOperationDefinition, Tt as OfflineUpload, U as OfflineMutationQueueingCause, Ut as OnListQueryInvalidate, V as OfflineMutationDescriptor, Vt as ListQueryUseMultipleListQueriesQuery, W as OfflineMutationQueueingConfig, Wt as OnListQueryItemInvalidate, X as OfflineResolutionActionError, Xt as TSFDListQuery, Y as OfflineResolutionAction, Yt as TSDFItemQuery, Z as OfflineResolutionActionErrorCode, Zt as TSFDListQueryState, _ as ListQueryOfflineOperationsConfig, _n as ScheduleFetchOptions, _t as OperationResult, a as AsyncStorageMetadataOrder, an as StoreFetchError, at as OfflineRetryExhaustedResolutionAction, b as PersistentStorageDataSchema, bn as TSDFDebugLogEntry, bt as defaultOfflineRuntimeConfig, c as AsyncStorageNamespaceCommitUpsert, cn as TSDFStatus, ct as OfflineSession, d as AsyncStorageNamespaceKind, dn as ValidStoreState, dt as OfflineSyncState, en as TSFDUsePendingOfflineItemsReturn, et as OfflineResolutionConflictParseErrorCode, f as AsyncStorageNamespaceScope, fn as fetchTypePriority, ft as OfflineTempEntitiesConfig, g as DocumentPersistentStorageConfig, gn as RequestSchedulerEvents, gt as OperationConflict, h as ConvertedPersistentStorageDataSchema, hn as RequestSchedulerEventData, ht as OfflineTempEntityPendingEntry, i as AsyncStorageDriverSetEntry, in as StoreError, it as OfflineResolutionRecordForStore, j as DefineOfflineOperation, jt as ReplaceOfflineUploadArgs, k as DefineDocumentOfflineOperations, kt as OfflineUploadState, l as AsyncStorageNamespaceGetResult, ln as UnwrapTSDFResult, lt as OfflineSessionConfig, m as CollectionPersistentStorageConfig, mn as FetchType, mt as OfflineTempEntityConfig, n as AsyncStorageDiscoveredScope, nn as MutationSkipped, nt as OfflineResolutionRecord, o as AsyncStorageNamespaceCommitArgs, on as StoreMutationError, ot as OfflineRuntimeConfig, p as AsyncStorageReadOptions, pn as mutationSkipped, pt as OfflineTempEntitiesReconciliation, q as OfflineQueueEntry, qt as QueryFetchPayload, r as AsyncStorageDriver, rn as PayloadDebounce, rt as OfflineResolutionRecordForOperation, s as AsyncStorageNamespaceCommitTouch, sn as StoreMutationErrorOptions, st as OfflineRuntimeConfigUpdate, t as AsyncStorageAdapter, tn as MaybeTSDFResult, tt as OfflineResolutionGenericAction, u as AsyncStorageNamespaceHandle, un as ValidPayload, ut as OfflineSupersedeConfig, v as ListQueryPersistentStorageConfig, vn as ScheduleFetchResults, vt as ParsedOfflineResolutionConflictResultForOperation, w as StorageAdapter, wn as TSDFLoggerOptions, wt as OfflineStoredUploadRecord, x as PersistentStorageErrorHandler, xn as TSDFDebugLogLevel, xt as OfflineMutationUploadsInput, y as PersistentStorageBaseConfig, yn as TSDFDebugLogArea, yt as ParsedOfflineResolutionConflictResultForStore, z as OfflineConflictResolutionAction, zt as FieldsOption } from "./types-
|
|
1
|
+
import { $ as OfflineResolutionConflictParseError, $t as TSFDUseListQueryReturn, A as DefineListQueryOfflineOperations, At as OfflineUploadTransportContext, B as OfflineEntityMutationKind, Bt as ListQueryUseMultipleItemsQuery, C as PersistentStorageSchema, Cn as TSDFFocusDebugOperation, Ct as OfflineSessionUploadsConfig, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadProgress, E as CollectionOfflineEntityRef, Et as OfflineUploadAdapter, F as ListQueryOfflineEntityRef, Ft as DerivedQuerySource, G as OfflineMutationQueueingPolicy, Gt as OptimisticListUpdate, H as OfflineMutationInput, Ht as OffsetPaginationConfig, I as ListQueryOfflineOperationDefinition, It as FetchListFnReturn, J as OfflineReplayRetryConfig, Jt as QueryStatus, K as OfflineOperationKind, Kt as PartialResourcesConfig, L as OfflineAccumulationConfig, Lt as FetchListFnReturnItem, M as DocumentOfflineOperationDefinition, Mt as SaveOfflineUploadArgs, N as GlobalOfflineEntity, Nt as DerivedQueriesConfig, O as DefineCollectionOfflineOperations, Ot as OfflineUploadSource, P as GlobalOfflineStatus, Pt as DerivedQueryContext, Q as OfflineResolutionActionForOperation, Qt as TSFDUseListItemReturn, R as OfflineAccumulationMergeContext, Rt as FieldsInput, S as PersistentStoragePreloadResult, Sn as TSDFDebugLogger, St as OfflineOperationUploadsContext, T as AnyOfflineOperationDefinition, Tt as OfflineUpload, U as OfflineMutationQueueingCause, Ut as OnListQueryInvalidate, V as OfflineMutationDescriptor, Vt as ListQueryUseMultipleListQueriesQuery, W as OfflineMutationQueueingConfig, Wt as OnListQueryItemInvalidate, X as OfflineResolutionActionError, Xt as TSFDListQuery, Y as OfflineResolutionAction, Yt as TSDFItemQuery, Z as OfflineResolutionActionErrorCode, Zt as TSFDListQueryState, _ as ListQueryOfflineOperationsConfig, _n as ScheduleFetchOptions, _t as OperationResult, a as AsyncStorageMetadataOrder, an as StoreFetchError, at as OfflineRetryExhaustedResolutionAction, b as PersistentStorageDataSchema, bn as TSDFDebugLogEntry, bt as defaultOfflineRuntimeConfig, c as AsyncStorageNamespaceCommitUpsert, cn as TSDFStatus, ct as OfflineSession, d as AsyncStorageNamespaceKind, dn as ValidStoreState, dt as OfflineSyncState, en as TSFDUsePendingOfflineItemsReturn, et as OfflineResolutionConflictParseErrorCode, f as AsyncStorageNamespaceScope, fn as fetchTypePriority, ft as OfflineTempEntitiesConfig, g as DocumentPersistentStorageConfig, gn as RequestSchedulerEvents, gt as OperationConflict, h as ConvertedPersistentStorageDataSchema, hn as RequestSchedulerEventData, ht as OfflineTempEntityPendingEntry, i as AsyncStorageDriverSetEntry, in as StoreError, it as OfflineResolutionRecordForStore, j as DefineOfflineOperation, jt as ReplaceOfflineUploadArgs, k as DefineDocumentOfflineOperations, kt as OfflineUploadState, l as AsyncStorageNamespaceGetResult, ln as UnwrapTSDFResult, lt as OfflineSessionConfig, m as CollectionPersistentStorageConfig, mn as FetchType, mt as OfflineTempEntityConfig, n as AsyncStorageDiscoveredScope, nn as MutationSkipped, nt as OfflineResolutionRecord, o as AsyncStorageNamespaceCommitArgs, on as StoreMutationError, ot as OfflineRuntimeConfig, p as AsyncStorageReadOptions, pn as mutationSkipped, pt as OfflineTempEntitiesReconciliation, q as OfflineQueueEntry, qt as QueryFetchPayload, r as AsyncStorageDriver, rn as PayloadDebounce, rt as OfflineResolutionRecordForOperation, s as AsyncStorageNamespaceCommitTouch, sn as StoreMutationErrorOptions, st as OfflineRuntimeConfigUpdate, t as AsyncStorageAdapter, tn as MaybeTSDFResult, tt as OfflineResolutionGenericAction, u as AsyncStorageNamespaceHandle, un as ValidPayload, ut as OfflineSupersedeConfig, v as ListQueryPersistentStorageConfig, vn as ScheduleFetchResults, vt as ParsedOfflineResolutionConflictResultForOperation, w as StorageAdapter, wn as TSDFLoggerOptions, wt as OfflineStoredUploadRecord, x as PersistentStorageErrorHandler, xn as TSDFDebugLogLevel, xt as OfflineMutationUploadsInput, y as PersistentStorageBaseConfig, yn as TSDFDebugLogArea, yt as ParsedOfflineResolutionConflictResultForStore, z as OfflineConflictResolutionAction, zt as FieldsOption } from "./types-DeZ9VDOe.js";
|
|
2
2
|
import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
|
|
3
3
|
import { Emitter } from "evtmitter";
|
|
4
4
|
import { Context } from "react";
|
|
@@ -262,7 +262,11 @@ type CollectionStoreStoreEvents<ItemPayload extends ValidPayload> = {
|
|
|
262
262
|
mutationId: number;
|
|
263
263
|
items: ItemPayload[];
|
|
264
264
|
status: 'success' | 'error' | 'skipped';
|
|
265
|
-
};
|
|
265
|
+
};
|
|
266
|
+
/**
|
|
267
|
+
* Emitted when an offline temp item is reconciled to its final payload, in
|
|
268
|
+
* every tab of the session, not only the one that sent the creation.
|
|
269
|
+
*/
|
|
266
270
|
tempEntityReconciled: {
|
|
267
271
|
tempId: ItemPayload;
|
|
268
272
|
finalPayload: ItemPayload;
|
|
@@ -828,6 +832,10 @@ type ListQueryStoreStoreEvents<ItemPayload extends ValidPayload> = {
|
|
|
828
832
|
items: ItemPayload[];
|
|
829
833
|
status: 'success' | 'error' | 'skipped';
|
|
830
834
|
};
|
|
835
|
+
/**
|
|
836
|
+
* Emitted when an offline temp item is reconciled to its final payload, in
|
|
837
|
+
* every tab of the session, not only the one that sent the creation.
|
|
838
|
+
*/
|
|
831
839
|
tempEntityReconciled: {
|
|
832
840
|
tempId: ItemPayload;
|
|
833
841
|
finalPayload: ItemPayload;
|
package/dist/main.js
CHANGED
|
@@ -3986,7 +3986,11 @@ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWin
|
|
|
3986
3986
|
}
|
|
3987
3987
|
//#endregion
|
|
3988
3988
|
//#region src/utils/browserTabsSync.ts
|
|
3989
|
-
|
|
3989
|
+
/**
|
|
3990
|
+
* Bump when a message shape changes: tabs running another tsdf release then
|
|
3991
|
+
* ignore each other instead of misreading messages.
|
|
3992
|
+
*/
|
|
3993
|
+
const PROTOCOL_VERSION = 2;
|
|
3990
3994
|
const CHANNEL_PREFIX = "tsdf";
|
|
3991
3995
|
function createBrowserTabsChannelName(storeType, storeKey, appVersion) {
|
|
3992
3996
|
return `${CHANNEL_PREFIX}${appVersion === void 0 ? "" : `:app:${encodeURIComponent(appVersion)}`}:${storeType}:${storeKey}`;
|
|
@@ -4257,10 +4261,10 @@ function parseSyncMessage(message, storeType) {
|
|
|
4257
4261
|
//#endregion
|
|
4258
4262
|
//#region src/persistentStorage/offlineUploadsShared.ts
|
|
4259
4263
|
function stripStoredUploadFile(record) {
|
|
4260
|
-
const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, ...upload } = record;
|
|
4264
|
+
const { file: _file, lastOnlineSessionStartedAt: _lastOnlineSessionStartedAt, lastModified: _lastModified, storeName: _storeName, ...upload } = record;
|
|
4261
4265
|
return upload;
|
|
4262
4266
|
}
|
|
4263
|
-
function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt, metadata) {
|
|
4267
|
+
function createStoredUploadRecord(id, sessionKey, fileInput, source, state, createdAtInput, progress, resolvedRef, lastError, lastOnlineSessionStartedAt, metadata, storeName) {
|
|
4264
4268
|
const file = normalizeUploadFile(fileInput, id);
|
|
4265
4269
|
const now = Date.now();
|
|
4266
4270
|
const createdAt = createdAtInput ?? now;
|
|
@@ -4281,7 +4285,8 @@ function createStoredUploadRecord(id, sessionKey, fileInput, source, state, crea
|
|
|
4281
4285
|
...lastOnlineSessionStartedAt !== void 0 ? { lastOnlineSessionStartedAt } : {},
|
|
4282
4286
|
...metadata !== void 0 ? { metadata } : {},
|
|
4283
4287
|
file,
|
|
4284
|
-
lastModified: file.lastModified
|
|
4288
|
+
lastModified: file.lastModified,
|
|
4289
|
+
...storeName !== void 0 ? { storeName } : {}
|
|
4285
4290
|
};
|
|
4286
4291
|
}
|
|
4287
4292
|
function normalizeUploadFile(file, fallbackName) {
|
|
@@ -4576,6 +4581,12 @@ var SessionOfflineCoordinator = class {
|
|
|
4576
4581
|
store;
|
|
4577
4582
|
#registrations = /* @__PURE__ */ new Map();
|
|
4578
4583
|
#storeContributions = /* @__PURE__ */ new Map();
|
|
4584
|
+
/**
|
|
4585
|
+
* Latest entities and resolutions other tabs reported for their stores. Only
|
|
4586
|
+
* used for stores this tab has not attached, e.g. a store only another tab
|
|
4587
|
+
* created.
|
|
4588
|
+
*/
|
|
4589
|
+
#remoteStoreItems = /* @__PURE__ */ new Map();
|
|
4579
4590
|
#adapters = /* @__PURE__ */ new Set();
|
|
4580
4591
|
#sessionHandle;
|
|
4581
4592
|
#browserTabs;
|
|
@@ -4601,6 +4612,8 @@ var SessionOfflineCoordinator = class {
|
|
|
4601
4612
|
#scheduledRecoveryMode = null;
|
|
4602
4613
|
#recoveryAttempt = 0;
|
|
4603
4614
|
#classifiedNetworkActive = false;
|
|
4615
|
+
/** Tabs of this session that sent anything on the session channel. */
|
|
4616
|
+
#otherTabIds = /* @__PURE__ */ new Set();
|
|
4604
4617
|
#networkEnabledOverride;
|
|
4605
4618
|
#outageEnabledOverride;
|
|
4606
4619
|
#mutationQueueingOverrides;
|
|
@@ -4656,13 +4669,51 @@ var SessionOfflineCoordinator = class {
|
|
|
4656
4669
|
for (const listener of offlineRecoveryListeners) listener(sessionKey, (storeName) => !awaitingStores.has(storeName) && (prevAwaitingStores === null || prevAwaitingStores.has(storeName)));
|
|
4657
4670
|
});
|
|
4658
4671
|
this.#browserTabs = createBrowserTabsCoordinatorWithPriority("offline", `session:${sessionKey}`, () => this.sessionKey, (message) => {
|
|
4672
|
+
const isNewTab = !this.#otherTabIds.has(message.tabId);
|
|
4673
|
+
this.#otherTabIds.add(message.tabId);
|
|
4659
4674
|
if (message.kind === "tab-status") {
|
|
4660
4675
|
this.#browserTabs.priority.onTabStatusMessage(message.tabId, message);
|
|
4676
|
+
if (isNewTab) {
|
|
4677
|
+
this.#browserTabs.priority.publishLocalStatus();
|
|
4678
|
+
this.#publishSnapshot();
|
|
4679
|
+
}
|
|
4661
4680
|
this.#refreshLeadership();
|
|
4662
4681
|
return;
|
|
4663
4682
|
}
|
|
4683
|
+
if (message.kind === "offline-queue-entry") {
|
|
4684
|
+
this.#registrations.get(message.storeName)?.onRemoteQueueEntryChange?.(message.entryId, message.entry);
|
|
4685
|
+
return;
|
|
4686
|
+
}
|
|
4687
|
+
if (message.kind === "offline-resolution") {
|
|
4688
|
+
this.#registrations.get(message.storeName)?.onRemoteResolutionChange?.(message.resolutionId, message.resolution);
|
|
4689
|
+
return;
|
|
4690
|
+
}
|
|
4691
|
+
if (message.kind === "offline-temp-reconciled") {
|
|
4692
|
+
this.#registrations.get(message.storeName)?.onRemoteTempReconciled?.(message.tempId, message.finalPayload);
|
|
4693
|
+
return;
|
|
4694
|
+
}
|
|
4695
|
+
if (message.kind === "offline-work-discarded") {
|
|
4696
|
+
this.#registrations.get(message.storeName)?.onRemoteWorkDiscarded?.(message.discardedWork, message.removedTempEntityKeys);
|
|
4697
|
+
return;
|
|
4698
|
+
}
|
|
4664
4699
|
this.#applyRemoteSnapshot(message);
|
|
4665
|
-
}, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden,
|
|
4700
|
+
}, void 0, void 0, import.meta.env.DEV ? debugLogger : void 0, () => !isWindowAvailable() || !document.hidden, (noteFocusChange) => {
|
|
4701
|
+
if (!isWindowAvailable()) return () => {};
|
|
4702
|
+
const onChange = () => {
|
|
4703
|
+
noteFocusChange();
|
|
4704
|
+
this.#refreshLeadership();
|
|
4705
|
+
};
|
|
4706
|
+
window.addEventListener("focus", onChange);
|
|
4707
|
+
window.addEventListener("blur", onChange);
|
|
4708
|
+
window.addEventListener("pagehide", onChange);
|
|
4709
|
+
document.addEventListener("visibilitychange", onChange);
|
|
4710
|
+
return () => {
|
|
4711
|
+
window.removeEventListener("focus", onChange);
|
|
4712
|
+
window.removeEventListener("blur", onChange);
|
|
4713
|
+
window.removeEventListener("pagehide", onChange);
|
|
4714
|
+
document.removeEventListener("visibilitychange", onChange);
|
|
4715
|
+
};
|
|
4716
|
+
}, void 0, void 0, options.appVersion);
|
|
4666
4717
|
this.#refreshLeadership();
|
|
4667
4718
|
if (shouldBootstrapFromStorage) this.hydrate();
|
|
4668
4719
|
if (this.#hasCanonicalConfig) this.#refreshNetworkConfig();
|
|
@@ -4762,18 +4813,66 @@ var SessionOfflineCoordinator = class {
|
|
|
4762
4813
|
return () => {
|
|
4763
4814
|
this.#registrations.delete(registration.storeName);
|
|
4764
4815
|
this.#storeContributions.delete(registration.storeName);
|
|
4816
|
+
this.#remoteStoreItems.delete(registration.storeName);
|
|
4765
4817
|
this.#refreshAggregates();
|
|
4766
4818
|
this.#notifyGreenCycle();
|
|
4767
4819
|
if (this.#registrations.size === 0) this.#stopRecoveryProbe();
|
|
4768
4820
|
};
|
|
4769
4821
|
}
|
|
4770
|
-
syncStoreData(storeName, contribution) {
|
|
4822
|
+
syncStoreData(storeName, contribution, isRemoteChange = false) {
|
|
4771
4823
|
if (this.#disposed) return;
|
|
4772
4824
|
const replayHeadChanged = !replayHeadsEqual(this.#storeContributions.get(storeName)?.replayHead, contribution.replayHead);
|
|
4773
4825
|
this.#storeContributions.set(storeName, contribution);
|
|
4774
|
-
this.#refreshAggregates();
|
|
4826
|
+
this.#refreshAggregates(!isRemoteChange);
|
|
4775
4827
|
if (replayHeadChanged) this.#notifyGreenCycle();
|
|
4776
4828
|
}
|
|
4829
|
+
/** Tells the other tabs that this tab saved or removed (`null`) a queue entry. */
|
|
4830
|
+
publishQueueEntryChange(storeName, entryId, entry) {
|
|
4831
|
+
if (this.#disposed) return;
|
|
4832
|
+
this.#browserTabs.coordinator.publish({
|
|
4833
|
+
kind: "offline-queue-entry",
|
|
4834
|
+
storeName,
|
|
4835
|
+
entryId,
|
|
4836
|
+
entry
|
|
4837
|
+
});
|
|
4838
|
+
}
|
|
4839
|
+
/** Tells the other tabs that this tab saved or removed (`null`) a resolution. */
|
|
4840
|
+
publishResolutionChange(storeName, resolutionId, resolution) {
|
|
4841
|
+
if (this.#disposed) return;
|
|
4842
|
+
this.#browserTabs.coordinator.publish({
|
|
4843
|
+
kind: "offline-resolution",
|
|
4844
|
+
storeName,
|
|
4845
|
+
resolutionId,
|
|
4846
|
+
resolution
|
|
4847
|
+
});
|
|
4848
|
+
}
|
|
4849
|
+
/** Tells the other tabs that this tab reconciled a temp entity. */
|
|
4850
|
+
publishTempReconciled(storeName, tempId, finalPayload) {
|
|
4851
|
+
if (this.#disposed) return;
|
|
4852
|
+
this.#browserTabs.coordinator.publish({
|
|
4853
|
+
kind: "offline-temp-reconciled",
|
|
4854
|
+
storeName,
|
|
4855
|
+
tempId,
|
|
4856
|
+
finalPayload
|
|
4857
|
+
});
|
|
4858
|
+
}
|
|
4859
|
+
/** Tells the other tabs that this tab discarded queued work of a store. */
|
|
4860
|
+
publishWorkDiscarded(storeName, discardedWork, removedTempEntityKeys) {
|
|
4861
|
+
if (this.#disposed) return;
|
|
4862
|
+
this.#browserTabs.coordinator.publish({
|
|
4863
|
+
kind: "offline-work-discarded",
|
|
4864
|
+
storeName,
|
|
4865
|
+
discardedWork,
|
|
4866
|
+
removedTempEntityKeys
|
|
4867
|
+
});
|
|
4868
|
+
}
|
|
4869
|
+
/**
|
|
4870
|
+
* Whether another tab of this session was seen. While `false`, this tab is
|
|
4871
|
+
* the only one changing the queue, so it can skip the cross-tab safeguards.
|
|
4872
|
+
*/
|
|
4873
|
+
hasOtherTabs() {
|
|
4874
|
+
return this.#otherTabIds.size > 0;
|
|
4875
|
+
}
|
|
4777
4876
|
canReplayEntry(args) {
|
|
4778
4877
|
const nextReplayHead = [...this.#storeContributions.values()].map((contribution) => contribution.replayHead).filter((head) => head !== null).sort(compareReplayHeads)[0];
|
|
4779
4878
|
if (!nextReplayHead) return true;
|
|
@@ -4825,7 +4924,7 @@ var SessionOfflineCoordinator = class {
|
|
|
4825
4924
|
if (!this.#uploadsConfig) throw new Error(`[tsdf] Offline uploads are not configured for session "${this.sessionKey}"`);
|
|
4826
4925
|
if (this.#uploadPromisesById.has(args.id)) throw new Error(`Cannot change upload "${args.id}" while it is queued or uploading`);
|
|
4827
4926
|
const existing = this.#uploads.get(args.id);
|
|
4828
|
-
const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt(), args.metadata);
|
|
4927
|
+
const nextRecord = createStoredUploadRecord(args.id, this.sessionKey, args.file, args.source ?? "manual", void 0, existing?.createdAt, void 0, void 0, void 0, this.#getCurrentUploadOnlineSessionStartedAt(), args.metadata, args.storeName);
|
|
4829
4928
|
await this.#saveUploadRecord(nextRecord);
|
|
4830
4929
|
}
|
|
4831
4930
|
async replaceUpload(args) {
|
|
@@ -4834,7 +4933,8 @@ var SessionOfflineCoordinator = class {
|
|
|
4834
4933
|
id: args.id,
|
|
4835
4934
|
file: args.file,
|
|
4836
4935
|
source: existing?.source ?? "manual",
|
|
4837
|
-
metadata: args.metadata ?? existing?.metadata
|
|
4936
|
+
metadata: args.metadata ?? existing?.metadata,
|
|
4937
|
+
storeName: existing?.storeName
|
|
4838
4938
|
});
|
|
4839
4939
|
}
|
|
4840
4940
|
async loadUpload(id) {
|
|
@@ -5303,33 +5403,51 @@ var SessionOfflineCoordinator = class {
|
|
|
5303
5403
|
async #cleanupUnusedMutationUploads() {
|
|
5304
5404
|
const uploadsConfig = this.#uploadsConfig;
|
|
5305
5405
|
if (!uploadsConfig) return;
|
|
5306
|
-
const removableIds = [...this.#uploads.values()].filter((upload) => upload.source === "mutation").map((upload) => upload.id).filter((id) => !this.#referencedUploadIds.has(id) && !this.#uploadPromisesById.has(id));
|
|
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));
|
|
5307
5407
|
if (removableIds.length === 0) return;
|
|
5308
5408
|
for (const id of removableIds) this.#uploads.delete(id);
|
|
5309
5409
|
await Promise.all(removableIds.map((id) => uploadsConfig.adapter.remove(this.sessionKey, id)));
|
|
5310
5410
|
this.#syncUploadsState();
|
|
5311
5411
|
this.#refreshUploadRetention();
|
|
5312
5412
|
}
|
|
5313
|
-
|
|
5413
|
+
/**
|
|
5414
|
+
* The session-wide lists: this tab's own stores, plus what other tabs
|
|
5415
|
+
* reported for the stores this tab has not attached.
|
|
5416
|
+
*/
|
|
5417
|
+
#buildItemLists() {
|
|
5314
5418
|
const allEntities = [];
|
|
5315
5419
|
const allResolutions = [];
|
|
5316
|
-
const referencedUploadIds = /* @__PURE__ */ new Set();
|
|
5317
|
-
const nextProtectedKeysByAdapter = /* @__PURE__ */ new Map();
|
|
5318
5420
|
let hasQueuedMutations = false;
|
|
5319
5421
|
for (const contribution of this.#storeContributions.values()) {
|
|
5320
5422
|
if (contribution.replayHead !== null) hasQueuedMutations = true;
|
|
5321
5423
|
allEntities.push(...contribution.entities);
|
|
5322
5424
|
allResolutions.push(...contribution.resolutions);
|
|
5425
|
+
}
|
|
5426
|
+
for (const [storeName, items] of this.#remoteStoreItems) {
|
|
5427
|
+
if (this.#storeContributions.has(storeName)) continue;
|
|
5428
|
+
if (items.hasQueuedMutations) hasQueuedMutations = true;
|
|
5429
|
+
allEntities.push(...items.entities);
|
|
5430
|
+
allResolutions.push(...items.resolutions);
|
|
5431
|
+
}
|
|
5432
|
+
return {
|
|
5433
|
+
entities: dedupeById(allEntities),
|
|
5434
|
+
resolutions: dedupeById(allResolutions),
|
|
5435
|
+
hasQueuedMutations
|
|
5436
|
+
};
|
|
5437
|
+
}
|
|
5438
|
+
#refreshAggregates(publish = true) {
|
|
5439
|
+
const referencedUploadIds = /* @__PURE__ */ new Set();
|
|
5440
|
+
const nextProtectedKeysByAdapter = /* @__PURE__ */ new Map();
|
|
5441
|
+
for (const contribution of this.#storeContributions.values()) {
|
|
5323
5442
|
for (const uploadId of contribution.referencedUploadIds) referencedUploadIds.add(uploadId);
|
|
5324
5443
|
const existing = nextProtectedKeysByAdapter.get(contribution.adapter) ?? [];
|
|
5325
5444
|
existing.push(...contribution.protectedKeys);
|
|
5326
5445
|
nextProtectedKeysByAdapter.set(contribution.adapter, existing);
|
|
5327
5446
|
}
|
|
5328
|
-
const entities =
|
|
5329
|
-
const resolutions = dedupeById(allResolutions);
|
|
5447
|
+
const { entities, resolutions, hasQueuedMutations } = this.#buildItemLists();
|
|
5330
5448
|
for (const [adapter, keys] of nextProtectedKeysByAdapter) nextProtectedKeysByAdapter.set(adapter, [...new Set(keys)].sort());
|
|
5331
5449
|
const nextProtectedKeys = [...new Set([...nextProtectedKeysByAdapter.values()].flat())].sort();
|
|
5332
|
-
const adaptersToSync = new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]);
|
|
5450
|
+
const adaptersToSync = publish ? new Set([...this.#protectedKeysByAdapter.keys(), ...nextProtectedKeysByAdapter.keys()]) : /* @__PURE__ */ new Set();
|
|
5333
5451
|
const debugLogger = this.#debugLogger;
|
|
5334
5452
|
const sessionKey = this.sessionKey;
|
|
5335
5453
|
const emitSyncProtectedKeysLog = (adapterKind, status, count, startTime, error) => {
|
|
@@ -5372,7 +5490,7 @@ var SessionOfflineCoordinator = class {
|
|
|
5372
5490
|
});
|
|
5373
5491
|
}
|
|
5374
5492
|
}
|
|
5375
|
-
this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
|
|
5493
|
+
if (publish) this.#protectedKeysByAdapter = nextProtectedKeysByAdapter;
|
|
5376
5494
|
this.#referencedUploadIds = referencedUploadIds;
|
|
5377
5495
|
if (!arraysEqual(this.#protectedKeys, nextProtectedKeys)) {
|
|
5378
5496
|
this.#protectedKeys = nextProtectedKeys;
|
|
@@ -5384,8 +5502,8 @@ var SessionOfflineCoordinator = class {
|
|
|
5384
5502
|
hasQueuedMutations
|
|
5385
5503
|
}, { action: "offline-session-aggregate" });
|
|
5386
5504
|
this.#persistSessionSnapshot();
|
|
5387
|
-
this.#publishSnapshot();
|
|
5388
|
-
if (this.#uploadsConfig && this.#uploads.size > 0 && this.#storeContributions.size === this.#registrations.size) this.#cleanupUnusedMutationUploads();
|
|
5505
|
+
if (publish) this.#publishSnapshot();
|
|
5506
|
+
if (publish && this.#uploadsConfig && this.#uploads.size > 0 && this.#storeContributions.size === this.#registrations.size) this.#cleanupUnusedMutationUploads();
|
|
5389
5507
|
}
|
|
5390
5508
|
#stampLocalStatus(status) {
|
|
5391
5509
|
return {
|
|
@@ -5416,31 +5534,50 @@ var SessionOfflineCoordinator = class {
|
|
|
5416
5534
|
#publishSnapshot() {
|
|
5417
5535
|
if (this.#disposed) return;
|
|
5418
5536
|
const status = this.store.state.status;
|
|
5537
|
+
const contributions = [...this.#storeContributions.values()];
|
|
5419
5538
|
this.#browserTabs.coordinator.publish({
|
|
5420
5539
|
kind: "offline-session-snapshot",
|
|
5421
5540
|
status,
|
|
5422
|
-
|
|
5423
|
-
|
|
5541
|
+
storeNames: [...this.#storeContributions.keys()],
|
|
5542
|
+
entities: contributions.flatMap((contribution) => contribution.entities),
|
|
5543
|
+
resolutions: contributions.flatMap((contribution) => contribution.resolutions),
|
|
5424
5544
|
uploads: this.store.state.uploads,
|
|
5425
|
-
|
|
5545
|
+
queuedStoreNames: [...this.#storeContributions].filter(([, contribution]) => contribution.replayHead !== null).map(([storeName]) => storeName)
|
|
5426
5546
|
});
|
|
5427
5547
|
}
|
|
5428
5548
|
#applyRemoteSnapshot(message) {
|
|
5429
|
-
|
|
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
|
+
});
|
|
5554
|
+
if (message.sentAt < this.#lastRemoteSnapshotAt) {
|
|
5555
|
+
this.store.setPartialState(this.#buildItemLists(), { action: "offline-session-remote" });
|
|
5556
|
+
this.#persistSessionSnapshot();
|
|
5557
|
+
return;
|
|
5558
|
+
}
|
|
5430
5559
|
this.#lastRemoteSnapshotAt = message.sentAt;
|
|
5560
|
+
const wasEffectivelyOffline = this.store.state.status.isOfflineMode;
|
|
5561
|
+
const wasReplayBlocked = this.isReplayBlocked();
|
|
5562
|
+
const isDetectedOffline = this.#isNetworkEnabled() && (this.store.state.status.network.active && !this.#classifiedNetworkActive || !this.#browserReportsOnline());
|
|
5431
5563
|
this.store.setState({
|
|
5432
|
-
status: this.#restampHydratedStatus(
|
|
5564
|
+
status: this.#restampHydratedStatus(isDetectedOffline ? {
|
|
5565
|
+
...message.status,
|
|
5566
|
+
network: {
|
|
5567
|
+
...message.status.network,
|
|
5568
|
+
active: true
|
|
5569
|
+
}
|
|
5570
|
+
} : message.status, {
|
|
5433
5571
|
isLeader: this.isLeader(),
|
|
5434
5572
|
updatedAt: Date.now()
|
|
5435
5573
|
}),
|
|
5436
|
-
|
|
5437
|
-
|
|
5438
|
-
uploads: message.uploads,
|
|
5439
|
-
hasQueuedMutations: message.hasQueuedMutations
|
|
5574
|
+
...this.#buildItemLists(),
|
|
5575
|
+
uploads: message.uploads
|
|
5440
5576
|
}, { action: "offline-session-remote" });
|
|
5441
|
-
this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
|
|
5577
|
+
if (!isDetectedOffline) this.#syncClassifiedNetworkStateFromStatus(this.store.state.status);
|
|
5442
5578
|
this.#persistSessionSnapshot();
|
|
5443
5579
|
this.#refreshLeadership();
|
|
5580
|
+
this.#handleConnectivityChange(wasEffectivelyOffline, wasReplayBlocked);
|
|
5444
5581
|
}
|
|
5445
5582
|
#shouldPersistSessionSnapshot() {
|
|
5446
5583
|
return this.store.state.status.isOfflineMode || this.store.state.entities.length > 0 || this.store.state.resolutions.length > 0 || this.#protectedKeys.length > 0;
|
|
@@ -5820,6 +5957,12 @@ function useOfflineStoreResolutions(args) {
|
|
|
5820
5957
|
//#region src/persistentStorage/offline/storeController.ts
|
|
5821
5958
|
const DEFAULT_REPLAY_RETRY_MAX_FAILURES = 3;
|
|
5822
5959
|
const DEFAULT_REPLAY_RETRY_INTERVAL_MS = 5e3;
|
|
5960
|
+
/**
|
|
5961
|
+
* Time given to a tab to learn about the queue changes of the tab that just
|
|
5962
|
+
* replayed, before it may replay itself.
|
|
5963
|
+
*/
|
|
5964
|
+
const REPLAY_HANDOFF_SETTLE_MS = 500;
|
|
5965
|
+
const REPLAY_LOCK_UNAVAILABLE_WARNING = "[TSDF] navigator.locks is unavailable; with several tabs open, a queued offline mutation can be sent more than once.";
|
|
5823
5966
|
const BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE = "Blocked by unresolved dependency";
|
|
5824
5967
|
const compactOfflineEntitySchema = rc_object({
|
|
5825
5968
|
k: rc_string,
|
|
@@ -6009,12 +6152,16 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6009
6152
|
let replayRetryTimer = null;
|
|
6010
6153
|
let hydratedSessionKey = null;
|
|
6011
6154
|
let hydratedPromise = null;
|
|
6155
|
+
let releaseReplayLock = null;
|
|
6156
|
+
let heldReplayLockName = null;
|
|
6157
|
+
let replayLockReleaseTimer = null;
|
|
6012
6158
|
let nextQueueOrder = 0;
|
|
6013
6159
|
const replayRetryMaxFailures = sessionConfig.replayRetry?.maxFailures ?? DEFAULT_REPLAY_RETRY_MAX_FAILURES;
|
|
6014
6160
|
const replayRetryIntervalMs = sessionConfig.replayRetry?.intervalMs ?? DEFAULT_REPLAY_RETRY_INTERVAL_MS;
|
|
6015
6161
|
const queueEntries = /* @__PURE__ */ new Map();
|
|
6016
6162
|
const resolutions = /* @__PURE__ */ new Map();
|
|
6017
6163
|
const countedReplayFailures = /* @__PURE__ */ new Map();
|
|
6164
|
+
const entryIdsFromAnotherTab = /* @__PURE__ */ new Set();
|
|
6018
6165
|
const resolvedEntityRefBySerializedRef = /* @__PURE__ */ new Map();
|
|
6019
6166
|
function getActiveMutationQueueingCause(current) {
|
|
6020
6167
|
const status = current.session.getStatus();
|
|
@@ -6121,8 +6268,10 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6121
6268
|
activeSession?.unregister?.();
|
|
6122
6269
|
activeSession = null;
|
|
6123
6270
|
resetReplayRetryState();
|
|
6271
|
+
if (!replayScheduled) releaseHeldReplayLock();
|
|
6124
6272
|
resolvedEntityRefBySerializedRef.clear();
|
|
6125
6273
|
queueEntries.clear();
|
|
6274
|
+
entryIdsFromAnotherTab.clear();
|
|
6126
6275
|
resolutions.clear();
|
|
6127
6276
|
nextQueueOrder = 0;
|
|
6128
6277
|
hydratedSessionKey = null;
|
|
@@ -6280,6 +6429,36 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6280
6429
|
},
|
|
6281
6430
|
onOfflineCycle: () => {
|
|
6282
6431
|
resetReplayRetryState();
|
|
6432
|
+
},
|
|
6433
|
+
onRemoteQueueEntryChange: (entryId, entry) => {
|
|
6434
|
+
applyRecordChangeFromAnotherTab(() => {
|
|
6435
|
+
if (entry) {
|
|
6436
|
+
nextQueueOrder = Math.max(nextQueueOrder, getQueueOrder(entry) + 1);
|
|
6437
|
+
if (!operations[entry.operation]) return;
|
|
6438
|
+
queueEntries.set(entryId, entry);
|
|
6439
|
+
entryIdsFromAnotherTab.add(entryId);
|
|
6440
|
+
return;
|
|
6441
|
+
}
|
|
6442
|
+
queueEntries.delete(entryId);
|
|
6443
|
+
entryIdsFromAnotherTab.delete(entryId);
|
|
6444
|
+
countedReplayFailures.delete(entryId);
|
|
6445
|
+
if (queueEntries.size === 0) clearReplayRetryTimer();
|
|
6446
|
+
});
|
|
6447
|
+
},
|
|
6448
|
+
onRemoteResolutionChange: (resolutionId, resolution) => {
|
|
6449
|
+
applyRecordChangeFromAnotherTab(() => {
|
|
6450
|
+
if (resolution && rc_parse(resolution, offlineResolutionRecordSchema).ok && operations[resolution.operation]) resolutions.set(resolutionId, resolution);
|
|
6451
|
+
else resolutions.delete(resolutionId);
|
|
6452
|
+
});
|
|
6453
|
+
},
|
|
6454
|
+
onRemoteWorkDiscarded: (discardedWork, removedTempEntityKeys) => {
|
|
6455
|
+
applyRecordChangeFromAnotherTab(() => {
|
|
6456
|
+
revalidateDiscardedWork(discardedWork, new Set(removedTempEntityKeys));
|
|
6457
|
+
});
|
|
6458
|
+
},
|
|
6459
|
+
onRemoteTempReconciled: (tempId, finalPayload) => {
|
|
6460
|
+
rememberResolvedEntityRef(tempId, finalPayload);
|
|
6461
|
+
storeAdapter.applyTempReconciliationFromAnotherTab?.(tempId, finalPayload);
|
|
6283
6462
|
}
|
|
6284
6463
|
}),
|
|
6285
6464
|
queueNamespace,
|
|
@@ -6298,6 +6477,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6298
6477
|
const [loadedQueueEntries, loadedResolutionEntries] = await Promise.all([loadNamespaceRecords(current.queueNamespace), loadNamespaceRecords(current.resolutionNamespace)]);
|
|
6299
6478
|
if (!isActiveSessionState(current)) return;
|
|
6300
6479
|
queueEntries.clear();
|
|
6480
|
+
entryIdsFromAnotherTab.clear();
|
|
6301
6481
|
resolutions.clear();
|
|
6302
6482
|
for (const entry of loadedQueueEntries.values()) queueEntries.set(entry.id, entry);
|
|
6303
6483
|
for (const resolution of loadedResolutionEntries.values()) {
|
|
@@ -6319,6 +6499,25 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6319
6499
|
});
|
|
6320
6500
|
return hydratedPromise;
|
|
6321
6501
|
}
|
|
6502
|
+
/**
|
|
6503
|
+
* Applies to this tab's in-memory queue a record change made by another tab,
|
|
6504
|
+
* so the leader replays entries queued by any tab and every tab stops
|
|
6505
|
+
* showing (and can never replay) an entry another tab already replayed.
|
|
6506
|
+
*/
|
|
6507
|
+
function applyRecordChangeFromAnotherTab(applyChange, changeSession = activeSession) {
|
|
6508
|
+
const current = activeSession;
|
|
6509
|
+
if (!current || current !== changeSession) return;
|
|
6510
|
+
if (hydratedPromise) {
|
|
6511
|
+
const applyAfterHydration = () => {
|
|
6512
|
+
applyRecordChangeFromAnotherTab(applyChange, current);
|
|
6513
|
+
};
|
|
6514
|
+
hydratedPromise.then(applyAfterHydration, applyAfterHydration);
|
|
6515
|
+
return;
|
|
6516
|
+
}
|
|
6517
|
+
if (hydratedSessionKey !== current.sessionKey) return;
|
|
6518
|
+
applyChange();
|
|
6519
|
+
refreshDerivedState(current, true);
|
|
6520
|
+
}
|
|
6322
6521
|
function parseConflictPayloadForOperation(operationName, conflict) {
|
|
6323
6522
|
const operation = operations[operationName];
|
|
6324
6523
|
if (!operation) return Result.err(new OfflineResolutionConflictParseError({
|
|
@@ -6447,7 +6646,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6447
6646
|
};
|
|
6448
6647
|
}).sort(compareResolutionRecords));
|
|
6449
6648
|
}
|
|
6450
|
-
function refreshDerivedState(current) {
|
|
6649
|
+
function refreshDerivedState(current, isRemoteChange) {
|
|
6451
6650
|
const session = current ?? ensureActiveSession();
|
|
6452
6651
|
if (!session || !isActiveSessionState(session)) return;
|
|
6453
6652
|
const sessionState = session;
|
|
@@ -6549,8 +6748,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6549
6748
|
queueOrder: getQueueOrder(nextReplayEntry),
|
|
6550
6749
|
createdAt: nextReplayEntry.createdAt
|
|
6551
6750
|
}
|
|
6552
|
-
});
|
|
6553
|
-
syncEntityNamespace(sessionState, entities);
|
|
6751
|
+
}, isRemoteChange);
|
|
6752
|
+
if (!isRemoteChange) syncEntityNamespace(sessionState, entities);
|
|
6554
6753
|
}
|
|
6555
6754
|
async function syncEntityNamespace(current, entities) {
|
|
6556
6755
|
await current.entityNamespace.replaceAll(entities.map((entity) => ({
|
|
@@ -6612,6 +6811,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6612
6811
|
if (entry.operation !== args.operationName) continue;
|
|
6613
6812
|
if (entry.syncState !== "pending") continue;
|
|
6614
6813
|
if (entry.attempts > 0) continue;
|
|
6814
|
+
if (entryIdsFromAnotherTab.has(entry.id)) continue;
|
|
6615
6815
|
if (entry.tempIds && entry.tempIds.length > 0) continue;
|
|
6616
6816
|
if (normalizeEntityRefs(entry.entityRefs) !== normalizedEntityRefs) continue;
|
|
6617
6817
|
if (!candidate || compareQueueEntries(entry, candidate) < 0) candidate = entry;
|
|
@@ -6812,6 +7012,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6812
7012
|
};
|
|
6813
7013
|
resolutions.set(rewrittenResolution.id, rewrittenResolution);
|
|
6814
7014
|
await args.current.resolutionNamespace.save(rewrittenResolution.id, rewrittenResolution);
|
|
7015
|
+
args.current.session.publishResolutionChange(storeName, rewrittenResolution.id, rewrittenResolution);
|
|
6815
7016
|
entityRefRewrites.push({
|
|
6816
7017
|
previousEntityRefs: resolution.entityRefs,
|
|
6817
7018
|
nextEntityRefs: rewrittenResolution.entityRefs
|
|
@@ -6850,6 +7051,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6850
7051
|
const tempId = args.tempIds[0];
|
|
6851
7052
|
if (tempId === void 0) return;
|
|
6852
7053
|
const reconciliation = tempEntity.reconcileServerEntity(args.result, tempId);
|
|
7054
|
+
args.current.session.publishTempReconciled(storeName, tempId, reconciliation.finalPayload);
|
|
6853
7055
|
storeAdapter.reconcileTempEntity({
|
|
6854
7056
|
operationName: args.operationName,
|
|
6855
7057
|
input: args.input,
|
|
@@ -6877,6 +7079,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6877
7079
|
}))
|
|
6878
7080
|
});
|
|
6879
7081
|
for (const reconciliation of reconciliations) {
|
|
7082
|
+
args.current.session.publishTempReconciled(storeName, reconciliation.tempId, reconciliation.finalPayload);
|
|
6880
7083
|
storeAdapter.reconcileTempEntity({
|
|
6881
7084
|
operationName: args.operationName,
|
|
6882
7085
|
input: args.input,
|
|
@@ -6897,6 +7100,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6897
7100
|
if (!session) return;
|
|
6898
7101
|
if (isActiveSessionState(session)) queueEntries.set(entry.id, entry);
|
|
6899
7102
|
await session.queueNamespace.save(entry.id, entry);
|
|
7103
|
+
session.session.publishQueueEntryChange(storeName, entry.id, entry);
|
|
6900
7104
|
if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
|
|
6901
7105
|
}
|
|
6902
7106
|
function runSuccessfulExecuteSync(args) {
|
|
@@ -6914,9 +7118,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6914
7118
|
if (!session) return;
|
|
6915
7119
|
if (isActiveSessionState(session)) {
|
|
6916
7120
|
queueEntries.delete(entryId);
|
|
7121
|
+
entryIdsFromAnotherTab.delete(entryId);
|
|
6917
7122
|
countedReplayFailures.delete(entryId);
|
|
6918
7123
|
if (queueEntries.size === 0) clearReplayRetryTimer();
|
|
6919
7124
|
}
|
|
7125
|
+
session.session.publishQueueEntryChange(storeName, entryId, null);
|
|
6920
7126
|
await session.queueNamespace.remove(entryId);
|
|
6921
7127
|
if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
|
|
6922
7128
|
}
|
|
@@ -6925,6 +7131,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6925
7131
|
if (!session) return;
|
|
6926
7132
|
if (isActiveSessionState(session)) resolutions.set(resolution.id, resolution);
|
|
6927
7133
|
await session.resolutionNamespace.save(resolution.id, resolution);
|
|
7134
|
+
session.session.publishResolutionChange(storeName, resolution.id, resolution);
|
|
6928
7135
|
if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
|
|
6929
7136
|
}
|
|
6930
7137
|
async function removeResolution(resolutionId, current, skipRefresh) {
|
|
@@ -6932,6 +7139,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
6932
7139
|
if (!session) return;
|
|
6933
7140
|
if (isActiveSessionState(session)) resolutions.delete(resolutionId);
|
|
6934
7141
|
await session.resolutionNamespace.remove(resolutionId);
|
|
7142
|
+
session.session.publishResolutionChange(storeName, resolutionId, null);
|
|
6935
7143
|
if (!skipRefresh && isActiveSessionState(session)) refreshDerivedState(session);
|
|
6936
7144
|
}
|
|
6937
7145
|
function collectTempCreateDescendants(args) {
|
|
@@ -7010,13 +7218,13 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7010
7218
|
for (const entry of descendants.queueEntries) descendantQueueEntries.set(entry.id, entry);
|
|
7011
7219
|
}
|
|
7012
7220
|
for (const dependentEntry of descendantQueueEntries.values()) {
|
|
7013
|
-
await removeEntry(dependentEntry.id, args.current, true);
|
|
7014
7221
|
await persistResolution(buildRetryExhaustedResolutionRecord(args.current, dependentEntry, { message: BLOCKED_DEPENDENCY_RESOLUTION_MESSAGE }), args.current, true);
|
|
7222
|
+
await removeEntry(dependentEntry.id, args.current, true);
|
|
7015
7223
|
}
|
|
7016
7224
|
}
|
|
7017
7225
|
async function persistManualResolutionChain(args) {
|
|
7018
|
-
await removeEntry(args.parentEntry.id, args.current, true);
|
|
7019
7226
|
await persistResolution(args.parentResolution, args.current, true);
|
|
7227
|
+
await removeEntry(args.parentEntry.id, args.current, true);
|
|
7020
7228
|
await promoteBlockedTempCreateDescendants({
|
|
7021
7229
|
current: args.current,
|
|
7022
7230
|
parentEntry: args.parentEntry,
|
|
@@ -7032,7 +7240,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7032
7240
|
const parentEntityKeys = getTempLifecycleEntityKeys(args.resolution);
|
|
7033
7241
|
if (parentEntityKeys.length === 0) {
|
|
7034
7242
|
refreshDerivedState(args.current);
|
|
7035
|
-
|
|
7243
|
+
revalidateDiscardedWorkInEveryTab(args.current, [args.resolution], /* @__PURE__ */ new Set());
|
|
7036
7244
|
return;
|
|
7037
7245
|
}
|
|
7038
7246
|
const descendantQueueEntries = /* @__PURE__ */ new Map();
|
|
@@ -7054,7 +7262,20 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7054
7262
|
const discardedWork = [...descendantQueueEntries.values(), ...descendantResolutions.values()];
|
|
7055
7263
|
const removedTempEntityKeys = new Set(parentEntityKeys);
|
|
7056
7264
|
for (const workItem of discardedWork) for (const entityKey of getTempLifecycleEntityKeys(workItem)) removedTempEntityKeys.add(entityKey);
|
|
7265
|
+
revalidateDiscardedWorkInEveryTab(args.current, discardedWork, removedTempEntityKeys);
|
|
7266
|
+
}
|
|
7267
|
+
/**
|
|
7268
|
+
* {@link revalidateDiscardedWork} in this tab and in the other tabs with the
|
|
7269
|
+
* store: each one may show the discarded optimistic changes.
|
|
7270
|
+
*/
|
|
7271
|
+
function revalidateDiscardedWorkInEveryTab(current, discardedWork, removedTempEntityKeys) {
|
|
7057
7272
|
revalidateDiscardedWork(discardedWork, removedTempEntityKeys);
|
|
7273
|
+
if (!discardedWork.some((workItem) => workItem.entityRefs.length > 0)) return;
|
|
7274
|
+
current.session.publishWorkDiscarded(storeName, discardedWork.map(({ operation, input, entityRefs }) => ({
|
|
7275
|
+
operation,
|
|
7276
|
+
input,
|
|
7277
|
+
entityRefs
|
|
7278
|
+
})), [...removedTempEntityKeys]);
|
|
7058
7279
|
}
|
|
7059
7280
|
/**
|
|
7060
7281
|
* Refetches the entities discarded queued work referenced (its optimistic
|
|
@@ -7162,7 +7383,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7162
7383
|
return result;
|
|
7163
7384
|
}
|
|
7164
7385
|
async function planPreparedMutation(args) {
|
|
7165
|
-
const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue } = args;
|
|
7386
|
+
const { current, preparedMutation: { operation, operationName, validatedInput, dependencyUploadIds, upload, tempIds: preparedTempIds, entityRefs: preparedEntityRefs }, queueOrder, workingQueue, replacedResolutionId } = args;
|
|
7166
7387
|
const tempEntity = operation.tempEntity;
|
|
7167
7388
|
const tempEntities = operation.tempEntities;
|
|
7168
7389
|
if (operation.accumulation && operation.supersedes) throw new Error(`Offline operation "${operationName}" cannot configure accumulation and supersedes together`);
|
|
@@ -7190,7 +7411,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7190
7411
|
entityRefs,
|
|
7191
7412
|
tempIds,
|
|
7192
7413
|
entries: workingQueue.values(),
|
|
7193
|
-
resolutionEntries: resolutions.values()
|
|
7414
|
+
resolutionEntries: replacedResolutionId ? [...resolutions.values()].filter((resolution) => resolution.id !== replacedResolutionId) : resolutions.values()
|
|
7194
7415
|
});
|
|
7195
7416
|
if (duplicateTempEntityKey !== null) throw new Error(`Offline operation "${operationName}" cannot queue temp entity "${duplicateTempEntityKey}" more than once while it is still pending`);
|
|
7196
7417
|
}
|
|
@@ -7278,7 +7499,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7278
7499
|
removedEntries: supersededEntries
|
|
7279
7500
|
};
|
|
7280
7501
|
}
|
|
7281
|
-
async function queuePreparedMutations(preparedMutation) {
|
|
7502
|
+
async function queuePreparedMutations(preparedMutation, replacedResolutionId) {
|
|
7282
7503
|
const current = ensureActiveSession();
|
|
7283
7504
|
if (!current || current.sessionKey !== preparedMutation.currentSessionKey) throw new OfflineSessionUnavailableError();
|
|
7284
7505
|
const { queueOrders, nextQueueOrderValue } = previewQueueOrders(1);
|
|
@@ -7290,7 +7511,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7290
7511
|
current,
|
|
7291
7512
|
preparedMutation,
|
|
7292
7513
|
queueOrder,
|
|
7293
|
-
workingQueue: new Map(queueEntries)
|
|
7514
|
+
workingQueue: new Map(queueEntries),
|
|
7515
|
+
replacedResolutionId
|
|
7294
7516
|
});
|
|
7295
7517
|
while (plannedMutation.accumulatedEntry && queueEntries.get(plannedMutation.accumulatedEntry.id) !== plannedMutation.accumulatedEntry);
|
|
7296
7518
|
const persistedMutations = [];
|
|
@@ -7314,7 +7536,8 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7314
7536
|
return current.session.saveUpload({
|
|
7315
7537
|
id: storedUploadId,
|
|
7316
7538
|
file,
|
|
7317
|
-
source: "mutation"
|
|
7539
|
+
source: "mutation",
|
|
7540
|
+
storeName
|
|
7318
7541
|
});
|
|
7319
7542
|
}));
|
|
7320
7543
|
}
|
|
@@ -7379,19 +7602,84 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7379
7602
|
}
|
|
7380
7603
|
if (replayScheduled || replayRetryTimer !== null || current.session.getStatus().isOfflineMode || current.session.isReplayBlocked() || !current.session.isLeader() || queueEntries.size === 0) return;
|
|
7381
7604
|
replayScheduled = true;
|
|
7605
|
+
const replaySession = current;
|
|
7382
7606
|
replayQueue.resultifyAdd(async () => {
|
|
7383
7607
|
try {
|
|
7384
|
-
await
|
|
7608
|
+
await acquireReplayLock(replaySession);
|
|
7609
|
+
try {
|
|
7610
|
+
await drainReplay(replaySession);
|
|
7611
|
+
} finally {
|
|
7612
|
+
if (replaySession.session.hasOtherTabs()) replayLockReleaseTimer = setTimeout(releaseHeldReplayLock, REPLAY_HANDOFF_SETTLE_MS);
|
|
7613
|
+
else releaseHeldReplayLock();
|
|
7614
|
+
}
|
|
7385
7615
|
} finally {
|
|
7386
7616
|
replayScheduled = false;
|
|
7387
7617
|
if (getSortedEntries()[0]?.syncState === "needs-confirmation") scheduleReplayRetry();
|
|
7618
|
+
if (!isActiveSessionState(replaySession)) ensureReplayScheduled();
|
|
7388
7619
|
}
|
|
7389
7620
|
});
|
|
7390
7621
|
}
|
|
7391
|
-
|
|
7622
|
+
/**
|
|
7623
|
+
* Leadership is decided from tab presence messages, so for a moment two tabs
|
|
7624
|
+
* can both consider themselves the leader (e.g. while it moves to the tab
|
|
7625
|
+
* that just got focus). This cross-tab lock makes sure only one of them
|
|
7626
|
+
* replays this store's queue at a time.
|
|
7627
|
+
*/
|
|
7628
|
+
async function acquireReplayLock(current) {
|
|
7629
|
+
const lockManager = getNavigatorLockManager();
|
|
7630
|
+
if (lockManager === null) {
|
|
7631
|
+
if (current.session.hasOtherTabs()) warnIfNavigatorLockUnavailable(REPLAY_LOCK_UNAVAILABLE_WARNING);
|
|
7632
|
+
return;
|
|
7633
|
+
}
|
|
7634
|
+
if (replayLockReleaseTimer !== null) {
|
|
7635
|
+
clearTimeout(replayLockReleaseTimer);
|
|
7636
|
+
replayLockReleaseTimer = null;
|
|
7637
|
+
}
|
|
7638
|
+
const lockName = `tsdf:offline-replay:${current.sessionKey}:${storeName}`;
|
|
7639
|
+
if (heldReplayLockName === lockName) return;
|
|
7640
|
+
releaseHeldReplayLock();
|
|
7641
|
+
if (await requestReplayLock(lockManager, lockName, true)) return;
|
|
7642
|
+
await requestReplayLock(lockManager, lockName, false);
|
|
7643
|
+
await new Promise((resolve) => {
|
|
7644
|
+
setTimeout(resolve, REPLAY_HANDOFF_SETTLE_MS);
|
|
7645
|
+
});
|
|
7646
|
+
}
|
|
7647
|
+
/**
|
|
7648
|
+
* Resolves `true` once this tab holds the lock (until
|
|
7649
|
+
* `releaseHeldReplayLock`), or `false` when `ifAvailable` is set and another
|
|
7650
|
+
* tab holds it.
|
|
7651
|
+
*/
|
|
7652
|
+
function requestReplayLock(lockManager, lockName, ifAvailable) {
|
|
7653
|
+
return new Promise((onSettled) => {
|
|
7654
|
+
lockManager.request(lockName, { ifAvailable }, (lock) => {
|
|
7655
|
+
if (lock === null) {
|
|
7656
|
+
onSettled(false);
|
|
7657
|
+
return;
|
|
7658
|
+
}
|
|
7659
|
+
return new Promise((release) => {
|
|
7660
|
+
heldReplayLockName = lockName;
|
|
7661
|
+
releaseReplayLock = release;
|
|
7662
|
+
onSettled(true);
|
|
7663
|
+
});
|
|
7664
|
+
}).catch(() => {
|
|
7665
|
+
onSettled(true);
|
|
7666
|
+
});
|
|
7667
|
+
});
|
|
7668
|
+
}
|
|
7669
|
+
function releaseHeldReplayLock() {
|
|
7670
|
+
if (replayLockReleaseTimer !== null) {
|
|
7671
|
+
clearTimeout(replayLockReleaseTimer);
|
|
7672
|
+
replayLockReleaseTimer = null;
|
|
7673
|
+
}
|
|
7674
|
+
releaseReplayLock?.();
|
|
7675
|
+
releaseReplayLock = null;
|
|
7676
|
+
heldReplayLockName = null;
|
|
7677
|
+
}
|
|
7678
|
+
async function drainReplay(replaySession) {
|
|
7392
7679
|
while (true) {
|
|
7393
7680
|
const current = ensureActiveSession();
|
|
7394
7681
|
if (!current) return;
|
|
7682
|
+
if (current.sessionKey !== replaySession.sessionKey) return;
|
|
7395
7683
|
if (current.session.getStatus().isOfflineMode || current.session.isReplayBlocked() || !current.session.isLeader()) return;
|
|
7396
7684
|
const nextEntry = getSortedEntries()[0];
|
|
7397
7685
|
if (!nextEntry) return;
|
|
@@ -7623,11 +7911,11 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7623
7911
|
}) : null
|
|
7624
7912
|
};
|
|
7625
7913
|
});
|
|
7626
|
-
for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
|
|
7627
7914
|
for (const nextEntry of nextEntries) {
|
|
7628
7915
|
if (!nextEntry.entry) continue;
|
|
7629
7916
|
await persistEntry(nextEntry.entry, current, true);
|
|
7630
7917
|
}
|
|
7918
|
+
for (const retryResolution of resolutionsToRetry) await removeResolution(retryResolution.id, current, true);
|
|
7631
7919
|
storeAdapter.captureQueuedMutationOverlays?.({
|
|
7632
7920
|
sessionKey: current.sessionKey,
|
|
7633
7921
|
entityRefs: nextEntries.flatMap((nextEntry) => {
|
|
@@ -7648,14 +7936,13 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
|
|
|
7648
7936
|
return;
|
|
7649
7937
|
}
|
|
7650
7938
|
if (action === "requeue") {
|
|
7651
|
-
|
|
7939
|
+
await queuePreparedMutations(prepareMutationWithSession(current, {
|
|
7652
7940
|
operation: operationName,
|
|
7653
7941
|
input: resolutionAction?.input,
|
|
7654
7942
|
tempIds: resolutionRecord.tempIds,
|
|
7655
7943
|
entityRefs: resolutionRecord.entityRefs
|
|
7656
|
-
});
|
|
7657
|
-
await removeResolution(resolutionId, current
|
|
7658
|
-
await queuePreparedMutations(preparedMutation);
|
|
7944
|
+
}), resolutionId);
|
|
7945
|
+
await removeResolution(resolutionId, current);
|
|
7659
7946
|
return;
|
|
7660
7947
|
}
|
|
7661
7948
|
if (action === "commit") {
|
|
@@ -9976,6 +10263,12 @@ function createCollectionStore(storeOptions) {
|
|
|
9976
10263
|
finalPayload
|
|
9977
10264
|
});
|
|
9978
10265
|
},
|
|
10266
|
+
applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
|
|
10267
|
+
storeEvents.emit("tempEntityReconciled", {
|
|
10268
|
+
tempId: __LEGIT_CAST__(tempId),
|
|
10269
|
+
finalPayload: __LEGIT_CAST__(finalPayload)
|
|
10270
|
+
});
|
|
10271
|
+
},
|
|
9979
10272
|
captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
|
|
9980
10273
|
if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
|
|
9981
10274
|
captureOfflineOverlays(entityRefs.flatMap((ref) => {
|
|
@@ -17545,34 +17838,10 @@ function createListQueryStore(storeOptions) {
|
|
|
17545
17838
|
deleteItemState(__LEGIT_CAST__(tempId));
|
|
17546
17839
|
},
|
|
17547
17840
|
reconcileTempEntity: ({ tempId, reconciliation }) => {
|
|
17548
|
-
|
|
17549
|
-
|
|
17550
|
-
|
|
17551
|
-
|
|
17552
|
-
if (finalData === void 0) return;
|
|
17553
|
-
const finalPayload = __LEGIT_CAST__(reconciliation.finalPayload);
|
|
17554
|
-
const finalItemKey = getItemKey(finalPayload);
|
|
17555
|
-
const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
|
|
17556
|
-
queryKey,
|
|
17557
|
-
index: query.items.indexOf(tempItemKey)
|
|
17558
|
-
})).filter(({ index }) => index !== -1);
|
|
17559
|
-
deleteItemState(tempPayload);
|
|
17560
|
-
addItemToState(finalPayload, finalData);
|
|
17561
|
-
storeEvents.emit("tempEntityReconciled", {
|
|
17562
|
-
tempId: tempPayload,
|
|
17563
|
-
finalPayload
|
|
17564
|
-
});
|
|
17565
|
-
if (queryMemberships.length === 0) return;
|
|
17566
|
-
store.produceState((draft) => {
|
|
17567
|
-
for (const { queryKey, index } of queryMemberships) {
|
|
17568
|
-
const query = notNullish(draft.queries[queryKey]);
|
|
17569
|
-
const existingIndex = query.items.indexOf(finalItemKey);
|
|
17570
|
-
if (existingIndex !== -1) query.items.splice(existingIndex, 1);
|
|
17571
|
-
query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
|
|
17572
|
-
}
|
|
17573
|
-
}, { action: "offline-reconcile-temp-item" });
|
|
17574
|
-
touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
|
|
17575
|
-
for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
|
|
17841
|
+
reconcileOfflineTempItem(tempId, reconciliation.finalPayload, reconciliation.finalData);
|
|
17842
|
+
},
|
|
17843
|
+
applyTempReconciliationFromAnotherTab: (tempId, finalPayload) => {
|
|
17844
|
+
if (!runWithoutBroadcast(() => reconcileOfflineTempItem(tempId, finalPayload, void 0))) emitTempItemReconciled(tempId, finalPayload);
|
|
17576
17845
|
},
|
|
17577
17846
|
captureQueuedMutationOverlays: ({ entityRefs, sessionKey }) => {
|
|
17578
17847
|
if (offlineOverlaySessionKey !== sessionKey) clearOfflineOverlays(sessionKey);
|
|
@@ -17669,6 +17938,44 @@ function createListQueryStore(storeOptions) {
|
|
|
17669
17938
|
}
|
|
17670
17939
|
for (const itemKey of itemsPendingFullInvalidation.keys()) if (store.state.itemLoadedFields[itemKey] === "*") itemsPendingFullInvalidation.delete(itemKey);
|
|
17671
17940
|
}
|
|
17941
|
+
function emitTempItemReconciled(tempId, finalPayload) {
|
|
17942
|
+
storeEvents.emit("tempEntityReconciled", {
|
|
17943
|
+
tempId: __LEGIT_CAST__(tempId),
|
|
17944
|
+
finalPayload: __LEGIT_CAST__(finalPayload)
|
|
17945
|
+
});
|
|
17946
|
+
}
|
|
17947
|
+
/**
|
|
17948
|
+
* Replaces an offline temp item with its final one, in place in every query
|
|
17949
|
+
* that lists it. Returns `false` when there is no data for the final item.
|
|
17950
|
+
*/
|
|
17951
|
+
function reconcileOfflineTempItem(tempId, finalPayloadValue, finalDataValue) {
|
|
17952
|
+
const tempPayload = __LEGIT_CAST__(tempId);
|
|
17953
|
+
const tempItemKey = getItemKey(tempPayload);
|
|
17954
|
+
const currentItem = getItemState(tempPayload);
|
|
17955
|
+
const finalData = finalDataValue !== void 0 ? __LEGIT_CAST__(finalDataValue) : currentItem ?? void 0;
|
|
17956
|
+
if (finalData === void 0) return false;
|
|
17957
|
+
const finalPayload = __LEGIT_CAST__(finalPayloadValue);
|
|
17958
|
+
const finalItemKey = getItemKey(finalPayload);
|
|
17959
|
+
const queryMemberships = Object.entries(store.state.queries).map(([queryKey, query]) => ({
|
|
17960
|
+
queryKey,
|
|
17961
|
+
index: query.items.indexOf(tempItemKey)
|
|
17962
|
+
})).filter(({ index }) => index !== -1);
|
|
17963
|
+
deleteItemState(tempPayload);
|
|
17964
|
+
addItemToState(finalPayload, finalData);
|
|
17965
|
+
emitTempItemReconciled(tempId, finalPayloadValue);
|
|
17966
|
+
if (queryMemberships.length === 0) return true;
|
|
17967
|
+
store.produceState((draft) => {
|
|
17968
|
+
for (const { queryKey, index } of queryMemberships) {
|
|
17969
|
+
const query = notNullish(draft.queries[queryKey]);
|
|
17970
|
+
const existingIndex = query.items.indexOf(finalItemKey);
|
|
17971
|
+
if (existingIndex !== -1) query.items.splice(existingIndex, 1);
|
|
17972
|
+
query.items.splice(Math.min(index, query.items.length), 0, finalItemKey);
|
|
17973
|
+
}
|
|
17974
|
+
}, { action: "offline-reconcile-temp-item" });
|
|
17975
|
+
touchQueries(queryMemberships.map(({ queryKey }) => queryKey));
|
|
17976
|
+
for (const { queryKey } of queryMemberships) publishQuerySnapshot(queryKey);
|
|
17977
|
+
return true;
|
|
17978
|
+
}
|
|
17672
17979
|
function cleanupItemStateMetadata(itemKey) {
|
|
17673
17980
|
itemPendingInvalidationFields.delete(itemKey);
|
|
17674
17981
|
itemsPendingFullInvalidation.delete(itemKey);
|
|
@@ -18259,7 +18566,8 @@ const storedUploadMetadataRecordSchema = rc_object({
|
|
|
18259
18566
|
e: lastErrorSchema.optionalKey(),
|
|
18260
18567
|
g: rc_number.optionalKey(),
|
|
18261
18568
|
l: rc_number,
|
|
18262
|
-
d: validPayloadSchema.optionalKey()
|
|
18569
|
+
d: validPayloadSchema.optionalKey(),
|
|
18570
|
+
s: rc_string.optionalKey()
|
|
18263
18571
|
});
|
|
18264
18572
|
function serializeStoredUploadMetadataRecord(record) {
|
|
18265
18573
|
return JSON.stringify({
|
|
@@ -18277,7 +18585,8 @@ function serializeStoredUploadMetadataRecord(record) {
|
|
|
18277
18585
|
...record.lastError !== void 0 ? { e: record.lastError } : {},
|
|
18278
18586
|
...record.lastOnlineSessionStartedAt !== void 0 ? { g: record.lastOnlineSessionStartedAt } : {},
|
|
18279
18587
|
l: record.lastModified,
|
|
18280
|
-
...record.metadata !== void 0 ? { d: record.metadata } : {}
|
|
18588
|
+
...record.metadata !== void 0 ? { d: record.metadata } : {},
|
|
18589
|
+
...record.storeName !== void 0 ? { s: record.storeName } : {}
|
|
18281
18590
|
});
|
|
18282
18591
|
}
|
|
18283
18592
|
function parseStoredUploadMetadataRecord(raw) {
|
|
@@ -18298,7 +18607,8 @@ function parseStoredUploadMetadataRecord(raw) {
|
|
|
18298
18607
|
...compactRecord.e !== void 0 ? { lastError: compactRecord.e } : {},
|
|
18299
18608
|
...compactRecord.g !== void 0 ? { lastOnlineSessionStartedAt: compactRecord.g } : {},
|
|
18300
18609
|
lastModified: compactRecord.l,
|
|
18301
|
-
...compactRecord.d !== void 0 ? { metadata: compactRecord.d } : {}
|
|
18610
|
+
...compactRecord.d !== void 0 ? { metadata: compactRecord.d } : {},
|
|
18611
|
+
...compactRecord.s !== void 0 ? { storeName: compactRecord.s } : {}
|
|
18302
18612
|
};
|
|
18303
18613
|
}
|
|
18304
18614
|
var OpfsOfflineUploadDriver = class {
|
package/dist/opfs-storage.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as opfsPersistentStorage } from "./opfsPersistentStorage-
|
|
1
|
+
import { t as opfsPersistentStorage } from "./opfsPersistentStorage-HRMP5gzd.js";
|
|
2
2
|
export { opfsPersistentStorage };
|
|
@@ -463,6 +463,12 @@ type OfflineStoredUploadRecord<TResolvedRef extends ValidPayload = ValidPayload>
|
|
|
463
463
|
/** Staged file blob restored from the upload adapter. */file: File; /** Last online session start time seen before the upload was stored. */
|
|
464
464
|
lastOnlineSessionStartedAt?: number; /** File last-modified timestamp. */
|
|
465
465
|
lastModified: number;
|
|
466
|
+
/**
|
|
467
|
+
* Store whose queued mutation attached this file, set on uploads with
|
|
468
|
+
* `source: 'mutation'`. Custom adapters must persist it: the file is removed
|
|
469
|
+
* once that store's queue no longer uses it.
|
|
470
|
+
*/
|
|
471
|
+
storeName?: string;
|
|
466
472
|
};
|
|
467
473
|
/** Storage backend contract for session-scoped offline upload files. */
|
|
468
474
|
type OfflineUploadAdapter = {
|
package/docs/offline.md
CHANGED
|
@@ -203,14 +203,14 @@ The behavior is the same as calling the owning store's `resolveOfflineResolution
|
|
|
203
203
|
|
|
204
204
|
Failures are returned as a `Result` instead of thrown. `result.error` is an `OfflineResolutionActionError` with the `resolutionId`, the owning `storeName` (when known), and a `code`:
|
|
205
205
|
|
|
206
|
-
| `code` | Meaning
|
|
207
|
-
| ------------------------ |
|
|
208
|
-
| `resolution-not-found` | No resolution with this id in the active session, e.g. it was already resolved
|
|
209
|
-
| `store-not-registered` | The owning store was not created with this manager (yet). Resolutions are shared by the whole session, including other tabs, so a record can be listed before its store exists here.
|
|
210
|
-
| `retry-not-supported` | `retry` was requested for a `conflict` record. Conflicts are resolved with `discard`, or with `requeue` / `commit` on the store API.
|
|
211
|
-
| `resolution-blocked` | The record is blocked by parent resolutions (`blockedByResolutionIds`). Resolve the parents first.
|
|
212
|
-
| `offline-not-configured` | The manager was created without `offlineSession`.
|
|
213
|
-
| `action-failed` | The owning store failed while applying the action. The original error is in `error.cause`.
|
|
206
|
+
| `code` | Meaning |
|
|
207
|
+
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
208
|
+
| `resolution-not-found` | No resolution with this id in the active session, e.g. it was already resolved (possibly from another tab) or the session is logged out. |
|
|
209
|
+
| `store-not-registered` | The owning store was not created with this manager (yet). Resolutions are shared by the whole session, including other tabs, so a record can be listed before its store exists here. |
|
|
210
|
+
| `retry-not-supported` | `retry` was requested for a `conflict` record. Conflicts are resolved with `discard`, or with `requeue` / `commit` on the store API. |
|
|
211
|
+
| `resolution-blocked` | The record is blocked by parent resolutions (`blockedByResolutionIds`). Resolve the parents first. |
|
|
212
|
+
| `offline-not-configured` | The manager was created without `offlineSession`. |
|
|
213
|
+
| `action-failed` | The owning store failed while applying the action. The original error is in `error.cause`. |
|
|
214
214
|
|
|
215
215
|
## Reading Offline State
|
|
216
216
|
|
|
@@ -243,6 +243,24 @@ Each store also exposes scoped APIs:
|
|
|
243
243
|
|
|
244
244
|
List-query stores additionally expose `usePendingOfflineItems(...)`, which returns pending creates/updates and pending deletes without mounting or fetching a query.
|
|
245
245
|
|
|
246
|
+
## Multiple Tabs
|
|
247
|
+
|
|
248
|
+
Tabs of the same session share one offline queue. Every tab can queue mutations and every tab shows the same pending state, but only one tab sends the queued work:
|
|
249
|
+
|
|
250
|
+
- The **leading tab** replays the queue: the visible tab, or the one that was visible most recently. `useOfflineStatus().isLeader` tells whether the current tab leads.
|
|
251
|
+
- A mutation queued in any other tab is sent by the leading tab after the connection recovers, in the order the mutations were queued across tabs. No reload or tab switch is needed.
|
|
252
|
+
- Every queued mutation is sent once. A cross-tab lock (Web Locks API) keeps two tabs from replaying a store's queue at the same time, and a tab drops an entry as soon as another tab reports it as sent, so it does not send it again when it leads later. Where the Web Locks API is unavailable (pages served over plain `http` other than `localhost`), this guarantee does not hold and TSDF logs a warning. It also only holds between tabs running the same app version (`getAppVersion`) and the same TSDF release: tabs on different versions do not see each other's messages, so after a deploy an old tab and a new tab can both send the same queued mutation.
|
|
253
|
+
- When the leading tab sends a temp-entity creation queued in another tab, every tab with the store emits `tempEntityReconciled`, so a view that follows the temp id can switch to the final one in any tab.
|
|
254
|
+
- When the leading tab is closed or hidden, a visible tab takes over. When the previous tab was replaying or just did, the new one first waits for the mutation that tab is sending to finish, then up to a second more, so it learns what that tab already sent before it starts.
|
|
255
|
+
|
|
256
|
+
Things to keep in mind:
|
|
257
|
+
|
|
258
|
+
- A tab can only replay the operations of stores it has created. Create the stores of a session in every tab (the usual module-level setup) so the leading tab can replay all of them.
|
|
259
|
+
- `accumulation` only merges into mutations queued in the same tab. Mutations queued in different tabs are sent as separate requests.
|
|
260
|
+
- Leadership follows visibility. If every remaining tab is hidden, queued work waits until one of them becomes visible.
|
|
261
|
+
- While offline, each tab shows its own optimistic changes. Tabs converge once the queue is replayed and the data is fetched again.
|
|
262
|
+
- Tabs coordinate through browser messages, which cannot give a strict guarantee when a tab is closed or frozen in the middle of a hand-off. For mutations that must never run twice (for example payments), also make the server endpoint idempotent.
|
|
263
|
+
|
|
246
264
|
## Runtime Controls
|
|
247
265
|
|
|
248
266
|
The store manager owns runtime controls for the shared session:
|
|
@@ -312,4 +330,4 @@ await storeManager.saveOfflineUpload({
|
|
|
312
330
|
- It is persisted with the upload record, so it survives reloads, is passed to the `upload` transport both on replay and on `resolveOfflineUpload(s)`, and is exposed as `metadata` on the `OfflineUpload` entries returned by `getOfflineUploads()` / `useOfflineUploads()`.
|
|
313
331
|
- Because it is read back from storage, it is typed as an unvalidated `ValidPayload`: parse it with a schema before using it, as above. Uploads staged without metadata reach the transport with `metadata: undefined`, so handle that case explicitly. This includes the ones persisted by older versions and files attached directly to a mutation with its `upload` option, which can't carry metadata.
|
|
314
332
|
- `saveOfflineUpload` stores exactly the metadata it receives. `replaceOfflineUpload` keeps the metadata already saved for that id unless new `metadata` is passed. Both fail while that upload is queued or being sent.
|
|
315
|
-
- Custom `OfflineUploadAdapter` implementations must persist and restore the record's `metadata`
|
|
333
|
+
- Custom `OfflineUploadAdapter` implementations must persist and restore the record's `metadata` and `storeName` fields together with the rest of the record. `storeName` marks which store queued a file attached to a mutation. That file is removed once nothing in that store's queue uses it, and only while that store is created in the tab, so a store created later (for example on a code-split screen) still finds its files.
|