@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 62.3 kB
Source Map (JSON)
{"version":3,"file":"sync.cjs","names":["SyncRowReusedWithoutPreviousValueError","LIVE_QUERY_INTERNAL","DuplicateKeySyncError","CollectionReloadCrashedError","CollectionReloadDuringSyncEntryError","createDeferred","automaticRowMetadataWrite","NoPendingSyncTransactionCommitError","SyncTransactionAlreadyCommittedError","withAcceptedReceipt","CollectionConfigurationError","codedMessage","LoadSubsetOperationAbortedError","NoPendingSyncTransactionWriteError","SyncTransactionAlreadyCommittedWriteError","truncatesSourceKey","isFailedStatus","CollectionIsInErrorStateError","SyncCleanupError","isPromiseLike","CollectionPreloadAbortedError","pendingLoadSubsetPromises","loadSubsetOperations","syncStartDeferred","syncStartRequested","deferredLoadSubsets","syncCallbackEpoch","syncEntryActive","loadSubsetDepth","_events","checkReusedRow","writtenRows","createDuplicateKeyError","getActivePendingSyncTransaction","enterSync","getWritableSyncTransaction","createSyncMetadataApi","registerPendingSyncEntryCleanup","completePendingSyncEntryCleanup","callLoadSubset","writeExplicitRowMetadata","rejectPreload","getPreloadError","activeLoadSubsetOperation","waitForLoadSubsetOperation","completeLoadSubsetOperation","settleLoadSubsetOperation","emitLoadingSubsetChange","wrapCleanupError","invokeCleanup","pendingSyncEntryCleanup","abortLoadSubsetWork"],"sources":["../../../src/collection/sync.ts"],"sourcesContent":["import {\n CollectionConfigurationError,\n CollectionIsInErrorStateError,\n CollectionPreloadAbortedError,\n CollectionReloadCrashedError,\n CollectionReloadDuringSyncEntryError,\n DuplicateKeySyncError,\n LoadSubsetOperationAbortedError,\n NoPendingSyncTransactionCommitError,\n NoPendingSyncTransactionWriteError,\n SyncCleanupError,\n SyncRowReusedWithoutPreviousValueError,\n SyncTransactionAlreadyCommittedError,\n SyncTransactionAlreadyCommittedWriteError,\n} from '../errors'\nimport { createDeferred } from '../deferred'\nimport { codedMessage, devBuild } from '../error-message'\nimport { withAcceptedReceipt } from '../sync-receipt'\nimport { assertCollectionKey } from '../utils'\nimport { isPromiseLike } from '../utils/type-guards'\nimport { reportUncaught } from '../utils/callbacks'\nimport { LIVE_QUERY_INTERNAL } from '../query/live/internal.js'\nimport { isFailedStatus } from '../live-query-primitives.js'\nimport { automaticRowMetadataWrite, truncatesSourceKey } from './state'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type {\n ChangeMessageOrDeleteKeyMessage,\n CleanupFn,\n CollectionConfig,\n LoadSubsetFn,\n LoadSubsetOptions,\n LoadSubsetRequestResult,\n OptimisticChangeMessage,\n SyncConfigRes,\n SyncMetadataApi,\n} from '../types'\nimport type { CollectionImpl } from './index.js'\nimport type { CollectionStateManager, PendingMetadataWrite } from './state'\nimport type { CollectionLifecycleManager } from './lifecycle'\nimport type { CollectionEventsManager } from './events.js'\nimport type { LiveQueryCollectionUtils } from '../query/live/collection-config-builder.js'\nimport type { Deferred } from '../deferred'\n\n/**\n * Internal marker on a sync write: an update that names the whole row, as an\n * insert does. The persisted wrapper hands an insert it already judged this\n * way. It is not part of the public sync API.\n *\n * @internal\n */\nexport const syncWriteNamesWholeRow: unique symbol = Symbol()\n\ntype DeferredLoadSubset = {\n options: LoadSubsetOptions\n deferred: Deferred<void>\n}\n\ntype LoadSubsetOperation = {\n pending: Set<Promise<unknown>>\n waiting: boolean\n completed: boolean\n hasError: boolean\n error?: unknown\n deferred?: Deferred<void>\n}\n\nfunction shallowEqual(\n left: Record<string, unknown>,\n right: Record<string, unknown>,\n): boolean {\n const keys = Object.keys(left)\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => Object.is(left[key], right[key]))\n )\n}\n\nexport class CollectionSyncManager<\n TOutput extends object = Record<string, unknown>,\n TKey extends string | number = string | number,\n TSchema extends StandardSchemaV1 = StandardSchemaV1,\n TInput extends object = TOutput,\n> {\n private collection!: CollectionImpl<TOutput, TKey, any, TSchema, TInput>\n private state!: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n private lifecycle!: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n private _events!: CollectionEventsManager\n private config!: CollectionConfig<TOutput, TKey, TSchema, any>\n private id: string\n private syncMode: `eager` | `on-demand`\n // Development only: each written row object's fields when it was written.\n private writtenRows: WeakMap<object, Record<string, unknown>> | undefined\n\n public preloadPromise: Promise<void> | null = null\n private rejectPreload?: (error: unknown) => void\n public syncCleanupFn: CleanupFn | null = null\n public syncLoadSubsetFn: LoadSubsetFn | null = null\n public syncUnloadSubsetFn: ((options: LoadSubsetOptions) => void) | null =\n null\n\n private pendingLoadSubsetPromises: Set<Promise<unknown>> = new Set()\n private activeLoadSubsetOperation: LoadSubsetOperation | undefined\n private loadSubsetOperations = new Set<LoadSubsetOperation>()\n private syncStartDeferred = false\n private syncStartRequested = false\n private deferredLoadSubsets: Array<DeferredLoadSubset> = []\n // Fences callbacks retained across reentrant sync entry and cleanup. This\n // changes at both boundaries; syncRunGeneration changes at cleanup and when\n // a reload retires a run.\n private syncCallbackEpoch = 0\n private syncRunGeneration = 0\n private syncEntryActive = false\n // A loadSubset call of the adapter is running; a reload from it would\n // retire the run under the call.\n private loadSubsetDepth = 0\n // A reload's new sync run has not begun its first transaction yet.\n private pendingSyncEntryCleanup:\n | {\n tasks: Array<Promise<void>>\n failure?: { error: unknown }\n onSettled?: (failure?: { error: unknown }) => void\n completion?: Deferred<void>\n }\n | undefined\n\n /**\n * Creates a new CollectionSyncManager instance\n */\n constructor(\n config: CollectionConfig<TOutput, TKey, TSchema, any>,\n id: string,\n ) {\n this.config = config\n this.id = id\n this.syncMode = config.syncMode ?? `eager`\n }\n\n setDeps(deps: {\n collection: CollectionImpl<TOutput, TKey, any, TSchema, TInput>\n state: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n lifecycle: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n events: CollectionEventsManager\n }) {\n this.collection = deps.collection\n this.state = deps.state\n this.lifecycle = deps.lifecycle\n this._events = deps.events\n }\n\n /**\n * Core keeps the object a source writes as the stored row. A source that\n * changes that object in place and writes it again has already\n * overwritten the previous value core would publish, unless it passes\n * `previousValue`. Rewriting an unchanged object stays valid.\n */\n private checkReusedRow(\n key: TKey,\n type: string,\n message: { value: TOutput; previousValue?: TOutput },\n ): void {\n const value = message.value as Record<string, unknown>\n const writtenRows = (this.writtenRows ??= new WeakMap())\n try {\n const written = writtenRows.get(value)\n if (\n written &&\n type === `update` &&\n // A write that names its previous value declares the reuse.\n !(`previousValue` in message) &&\n !shallowEqual(written, value)\n ) {\n throw new SyncRowReusedWithoutPreviousValueError(key)\n }\n writtenRows.set(value, { ...value })\n } catch (error) {\n if (error instanceof SyncRowReusedWithoutPreviousValueError) throw error\n // A row that cannot be read reports its failure where it is applied.\n writtenRows.delete(value)\n }\n }\n\n private createDuplicateKeyError(key: TKey): DuplicateKeySyncError {\n const utils = this.config.utils as\n Partial<LiveQueryCollectionUtils> | undefined\n const internal = utils?.[LIVE_QUERY_INTERNAL]\n return new DuplicateKeySyncError(key, this.id, {\n hasCustomGetKey: internal?.hasCustomGetKey ?? false,\n hasJoins: internal?.hasJoins ?? false,\n hasDistinct: internal?.hasDistinct ?? false,\n })\n }\n\n /** Mark the active sync transaction as changing collection layout. */\n public markLayoutChange(): void {\n this.getActivePendingSyncTransaction().layoutChanged = true\n }\n\n /**\n * Start the sync process for this collection\n * This is called when the collection is first accessed or preloaded\n */\n public startSync(): void {\n this.lifecycle.assertCanStartSync()\n if (\n this.lifecycle.status !== `idle` &&\n this.lifecycle.status !== `cleaned-up`\n ) {\n return // Already started or in progress\n }\n\n if (this.syncStartDeferred) {\n this.syncStartRequested = true\n return\n }\n\n const syncCallbackEpoch = ++this.syncCallbackEpoch\n this.lifecycle.setStatus(`loading`)\n if (syncCallbackEpoch !== this.syncCallbackEpoch) return\n const readyFailure = this.enterSync(syncCallbackEpoch)\n if (readyFailure) throw readyFailure.error\n }\n\n /**\n * Start a new sync run while everything visible stays: the rows, the\n * status, and the node's problems. The new run replaces the rows only with\n * a snapshot or its own truncate, and every other write applies on the\n * kept rows. The reload completes when a replacement applies, or at the\n * run's `markReady()`. A reload in flight returns its promise; a crashed\n * Collection cannot reload.\n */\n public reload(): Promise<void> {\n const status = this.lifecycle.status\n if (status === `crashed`) {\n return Promise.reject(new CollectionReloadCrashedError(this.id))\n }\n try {\n this.lifecycle.assertCanStartSync()\n } catch (error) {\n return Promise.reject(error)\n }\n if (this.lifecycle.reloading) return this.lifecycle.beginReload()\n if (status === `idle` || status === `cleaned-up`) return this.preload()\n if (this.syncEntryActive || this.loadSubsetDepth > 0) {\n return Promise.reject(new CollectionReloadDuringSyncEntryError(this.id))\n }\n // Listeners run while the reload announces itself, retires the run, and\n // detaches subscription demand. A cleanup one of them runs ends the\n // reload with its run, so the epoch is set before any of them, and it is\n // checked once they have all run.\n const syncCallbackEpoch = ++this.syncCallbackEpoch\n const reload = this.lifecycle.beginReload()\n // A retired run whose cleanup fails broke the adapter contract.\n void this.retireSyncRun().catch((error: unknown) =>\n this.lifecycle.crash(error),\n )\n // Subscriptions detach demand from the retired run and replay on-demand\n // demand through the new run's loader.\n this.lifecycle.retireSubscriptionDemand()\n if (syncCallbackEpoch !== this.syncCallbackEpoch) return reload\n try {\n // A ready callback that throws reaches no caller: the reload settles\n // with the status, which stays ready, so the throw is reported.\n const readyFailure = this.enterSync(syncCallbackEpoch)\n if (readyFailure) reportUncaught(readyFailure.error)\n } catch (error) {\n this.lifecycle.abandonReload(error)\n }\n return reload\n }\n\n /**\n * Run the sync function. A sync function that throws crashes the run and\n * rethrows; a ready callback that throws while it runs is returned.\n */\n private enterSync(syncCallbackEpoch: number): { error: unknown } | undefined {\n const isCurrentSync = () => syncCallbackEpoch === this.syncCallbackEpoch\n let loadedSubsetsInvalidationQueued = false\n const finishReadyFailures = this.lifecycle.deferReadyFailures()\n let readyFailure: { error: unknown } | undefined\n\n this.syncEntryActive = true\n try {\n const syncRes = normalizeSyncFnResult(\n this.config.sync.sync({\n collection: this.collection,\n begin: (options) => {\n if (!isCurrentSync()) return\n const applied = createDeferred<void>()\n // A source may ignore a stream receipt. Keep cancellation from\n // becoming an unhandled rejection while preserving the original\n // promise's rejection for callers that do await it.\n void applied.promise.catch(() => undefined)\n // A snapshot carries every row, so its commit replaces them, as a\n // truncate that does not mark ready.\n const snapshot = options?.snapshot === true\n this.state.pendingSyncedTransactions.push({\n committed: false,\n applicationStarted: false,\n layoutChanged: false,\n operations: [],\n rowMetadataWrites: new Map(),\n explicitRowMetadataWrites: new Map(),\n collectionMetadataWrites: new Map(),\n applied,\n duplicateKeyError: (key) => this.createDuplicateKeyError(key),\n truncate: snapshot,\n truncateMarkReady: false,\n })\n if (snapshot) this.state.refreshPendingSyncedProjection()\n },\n write: (\n messageWithOptionalKey: ChangeMessageOrDeleteKeyMessage<\n TOutput,\n TKey\n >,\n ) => {\n if (!isCurrentSync()) return\n const pendingTransaction = this.getWritableSyncTransaction()\n if (!pendingTransaction) return\n\n const key =\n `key` in messageWithOptionalKey\n ? messageWithOptionalKey.key\n : this.config.getKey(messageWithOptionalKey.value)\n // Ordered Collection state needs keys of the declared key type.\n assertCollectionKey(key, messageWithOptionalKey)\n\n let messageType = messageWithOptionalKey.type\n\n // Check if an item with this key already exists when inserting.\n // During a reload, as at any time, the rows the Collection holds\n // are the baseline: an insert of one throws.\n if (messageWithOptionalKey.type === `insert`) {\n const disposition = this.state.classifyPendingSyncedInsert(\n key,\n messageWithOptionalKey.value,\n )\n if (disposition === `duplicate`)\n throw this.createDuplicateKeyError(key)\n messageType = disposition\n }\n\n if (\n `value` in messageWithOptionalKey &&\n devBuild() &&\n process.env.NODE_ENV !== `production`\n ) {\n this.checkReusedRow(key, messageType, messageWithOptionalKey)\n }\n\n // An insert names the whole row, so it replaces the row even as\n // an update. A wrapping sync that judged its insert already marks\n // it as such an update: its metadata then changes only through\n // the wrapper's own writes.\n const message = {\n ...messageWithOptionalKey,\n type: messageType,\n key,\n originalSyncType:\n messageWithOptionalKey.type === `insert` ||\n (\n messageWithOptionalKey as {\n [syncWriteNamesWholeRow]?: true\n }\n )[syncWriteNamesWholeRow]\n ? (`insert` as const)\n : undefined,\n } as OptimisticChangeMessage<TOutput, TKey> & {\n originalSyncType?: `insert`\n }\n pendingTransaction.operations.push(message)\n this.state.stagePendingSyncOperation(\n message,\n pendingTransaction.preserveHydrationSeedKeys?.has(key),\n )\n\n const metadataWrite = automaticRowMetadataWrite(message)\n if (metadataWrite) {\n pendingTransaction.rowMetadataWrites.set(key, metadataWrite)\n }\n },\n commit: (signal?: AbortSignal) => {\n if (!isCurrentSync()) return true\n const pendingTransaction =\n this.state.pendingSyncedTransactions.at(-1)\n if (!pendingTransaction) {\n throw new NoPendingSyncTransactionCommitError()\n }\n if (pendingTransaction.committed) {\n throw new SyncTransactionAlreadyCommittedError()\n }\n\n if (\n signal?.aborted ||\n pendingTransaction.invalidationError !== undefined\n ) {\n this.state.cancelPendingSyncedTransaction(\n pendingTransaction,\n signal?.aborted\n ? undefined\n : pendingTransaction.invalidationError,\n )\n return pendingTransaction.applied.promise\n }\n\n pendingTransaction.committed = true\n // An accepted transaction always applies in commit order. Core\n // accepts it now; the receipt resolves when it is visible. One\n // held by a persisting optimistic transaction becomes visible when\n // that transaction settles.\n this.state.acceptSyncTransaction(pendingTransaction)\n if (!pendingTransaction.applied.isPending()) return true\n return withAcceptedReceipt(pendingTransaction.applied.promise, true)\n },\n markReady: () => {\n // Readiness counts accepted rows. Rows a persisting optimistic\n // transaction holds still publish with the drop of its state.\n if (isCurrentSync()) this.lifecycle.markReady()\n },\n fail: (error: unknown) => {\n if (isCurrentSync()) this.lifecycle.fail(error)\n },\n reportError: (error: unknown) => {\n if (isCurrentSync()) this.lifecycle.reportError(error)\n },\n reportHealthy: (error?: unknown) => {\n if (isCurrentSync()) this.lifecycle.reportHealthy(error)\n },\n truncate: (options) => {\n if (!isCurrentSync()) return\n const pendingTransaction = this.getWritableSyncTransaction()\n if (!pendingTransaction) return\n\n // Clear all operations from the current transaction\n pendingTransaction.operations = []\n pendingTransaction.rowMetadataWrites.clear()\n pendingTransaction.explicitRowMetadataWrites.clear()\n // Intentionally preserve collectionMetadataWrites across truncate.\n // Collection-scoped metadata (for example persisted resume/reset\n // state) can be staged before truncate and should commit atomically\n // with the truncate transaction.\n\n // Mark the transaction as a truncate operation. During commit, this triggers:\n // - Delete events for all previously synced keys (excluding optimistic-deleted keys)\n // - Clearing of syncedData/syncedMetadata\n // - Subsequent synced ops applied on the fresh base\n // - Finally, optimistic mutations re-applied on top (single batch)\n pendingTransaction.truncate = true\n pendingTransaction.truncateMarkReady = options?.markReady ?? true\n this.state.refreshPendingSyncedProjection()\n },\n invalidateLoadedSubsets: () => {\n if (!isCurrentSync() || loadedSubsetsInvalidationQueued) return\n // One revalidation per turn, after the refetch's rows apply.\n loadedSubsetsInvalidationQueued = true\n queueMicrotask(() => {\n loadedSubsetsInvalidationQueued = false\n if (!isCurrentSync()) return\n this._events.emit(`loadedSubsets:invalidated`, {\n type: `loadedSubsets:invalidated`,\n collection: this.collection,\n })\n })\n },\n metadata: this.createSyncMetadataApi(isCurrentSync),\n }),\n )\n this.syncEntryActive = false\n readyFailure = finishReadyFailures()\n\n if (!isCurrentSync()) {\n if (syncRes?.cleanup) {\n this.registerPendingSyncEntryCleanup(syncRes.cleanup)\n }\n this.completePendingSyncEntryCleanup()\n return readyFailure\n }\n\n // Store cleanup function if provided\n this.syncCleanupFn = syncRes?.cleanup ?? null\n\n // Store loadSubset function if provided\n this.syncLoadSubsetFn = syncRes?.loadSubset ?? null\n\n // Store unloadSubset function if provided\n this.syncUnloadSubsetFn = syncRes?.unloadSubset ?? null\n\n // Validate: on-demand mode requires a loadSubset function\n if (this.syncMode === `on-demand` && !this.syncLoadSubsetFn) {\n throw new CollectionConfigurationError(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Collection \"${this.id}\" is configured with syncMode \"on-demand\" but the sync function did not return a loadSubset handler. ` +\n `Either provide a loadSubset handler or use syncMode \"eager\".`\n : codedMessage(210, { id: this.id }),\n )\n }\n\n // Every route into sync passes through here, so it is the one place\n // that sees sync start ahead of the subscriber that would justify it.\n // `addSubscriber` counts itself in before calling us, so a subscription\n // starting sync leaves the timer alone.\n this.lifecycle.startGCTimerIfUnsubscribed()\n } catch (error) {\n this.syncEntryActive = false\n this.completePendingSyncEntryCleanup()\n finishReadyFailures()\n // A throwing sync function is a programming error, even after ready.\n // A run that already called fail() reported its error. Status cannot\n // tell: during a reload it still shows the previous run's.\n if (isCurrentSync() && !this.lifecycle.stoppedThisRun)\n this.lifecycle.crash(error)\n throw error\n }\n return readyFailure\n }\n\n public deferStart(): boolean {\n if (\n this.lifecycle.status !== `idle` &&\n this.lifecycle.status !== `cleaned-up`\n ) {\n return false\n }\n\n this.syncStartDeferred = true\n return true\n }\n\n public resumeStart(): void {\n if (!this.syncStartDeferred) {\n return\n }\n\n this.syncStartDeferred = false\n const shouldStart =\n this.syncStartRequested || this.deferredLoadSubsets.length > 0\n this.syncStartRequested = false\n const deferredLoadSubsets = this.deferredLoadSubsets\n this.deferredLoadSubsets = []\n const syncRunGeneration = this.syncRunGeneration\n\n try {\n if (shouldStart) {\n this.startSync()\n }\n } catch (error) {\n for (const { deferred } of deferredLoadSubsets) {\n deferred.reject(error)\n }\n throw error\n }\n\n for (const { options, deferred } of deferredLoadSubsets) {\n const loadSubset = this.syncLoadSubsetFn\n try {\n if (\n syncRunGeneration !== this.syncRunGeneration ||\n options.signal?.aborted\n ) {\n throw new LoadSubsetOperationAbortedError()\n }\n const result = loadSubset\n ? this.callLoadSubset(loadSubset, options)\n : true\n if (result instanceof Promise) {\n void result.then(\n (sourceResult) => deferred.resolve(sourceResult),\n (error: unknown) => deferred.reject(error),\n )\n } else {\n deferred.resolve(undefined)\n }\n } catch (error) {\n deferred.reject(error)\n }\n }\n }\n\n private getActivePendingSyncTransaction() {\n const pendingTransaction = this.state.pendingSyncedTransactions.at(-1)\n\n if (!pendingTransaction) {\n throw new NoPendingSyncTransactionWriteError()\n }\n if (pendingTransaction.committed) {\n throw new SyncTransactionAlreadyCommittedWriteError()\n }\n\n return pendingTransaction\n }\n\n /**\n * The open transaction that takes a row write or truncate. A replay can\n * invalidate an open transaction between writes. Its commit receipt owns\n * that failure; later writes, a truncate included, cannot revive it, so\n * they are ignored. Its metadata writes need no check: no read includes an\n * invalid transaction, and it never applies.\n */\n private getWritableSyncTransaction() {\n const pendingTransaction = this.getActivePendingSyncTransaction()\n return pendingTransaction.invalidationError === undefined\n ? pendingTransaction\n : undefined\n }\n\n /** Record an explicit row metadata write and its place among the operations. */\n private writeExplicitRowMetadata(\n key: TKey,\n write: PendingMetadataWrite,\n ): void {\n const pendingTransaction = this.getActivePendingSyncTransaction()\n pendingTransaction.explicitRowMetadataWrites.set(key, {\n position: pendingTransaction.operations.length,\n write,\n })\n pendingTransaction.rowMetadataWrites.set(key, write)\n }\n\n private createSyncMetadataApi(\n isCurrentSync: () => boolean,\n ): SyncMetadataApi<TKey> {\n return {\n persistence: null,\n row: {\n get: (key) => {\n if (!isCurrentSync()) return undefined\n // A source reads its own session: every accepted or open sync\n // transaction that no invalidation ended, newest first, then\n // applied state. A truncate hides older row metadata, except a\n // wrapping sync's storage read, which keeps it, and a schema reset's\n // kept seeds (decision 20). The wrapper reads its own open reset.\n const pending = this.state.pendingSyncedTransactions\n for (let index = pending.length - 1; index >= 0; index--) {\n const transaction = pending[index]!\n if (transaction.invalidationError !== undefined) continue\n const write = transaction.rowMetadataWrites.get(key)\n if (write) return write.type === `delete` ? undefined : write.value\n if (truncatesSourceKey(transaction, key)) return undefined\n }\n return this.state.syncedMetadata.get(key)\n },\n set: (key, metadata) => {\n if (isCurrentSync())\n this.writeExplicitRowMetadata(key, { type: `set`, value: metadata })\n },\n delete: (key) => {\n if (isCurrentSync())\n this.writeExplicitRowMetadata(key, { type: `delete` })\n },\n },\n collection: {\n get: (key) => {\n if (!isCurrentSync()) return undefined\n // Newest first, like row metadata. A truncate keeps collection\n // metadata.\n const pending = this.state.pendingSyncedTransactions\n for (let index = pending.length - 1; index >= 0; index--) {\n const transaction = pending[index]!\n if (transaction.invalidationError !== undefined) continue\n const write = transaction.collectionMetadataWrites.get(key)\n if (write) return write.type === `delete` ? undefined : write.value\n }\n return this.state.syncedCollectionMetadata.get(key)\n },\n set: (key, value) => {\n if (!isCurrentSync()) return\n this.getActivePendingSyncTransaction().collectionMetadataWrites.set(\n key,\n { type: `set`, value },\n )\n },\n delete: (key) => {\n if (!isCurrentSync()) return\n this.getActivePendingSyncTransaction().collectionMetadataWrites.set(\n key,\n { type: `delete` },\n )\n },\n list: (prefix) => {\n if (!isCurrentSync()) return []\n // Every pending transaction applies over applied state, oldest\n // first, so the newest write for each key wins.\n const merged = new Map(this.state.syncedCollectionMetadata)\n for (const transaction of this.state.pendingSyncedTransactions) {\n if (transaction.invalidationError !== undefined) continue\n for (const [key, write] of transaction.collectionMetadataWrites) {\n if (write.type === `delete`) merged.delete(key)\n else merged.set(key, write.value)\n }\n }\n\n return Array.from(merged.entries())\n .filter(([key]) => (prefix ? key.startsWith(prefix) : true))\n .map(([key, value]) => ({\n key,\n value,\n }))\n },\n },\n }\n }\n\n /** Whether a caller is still waiting for the initial sync to finish. */\n public get hasPendingPreload(): boolean {\n return this.rejectPreload !== undefined\n }\n\n /**\n * Preload the collection data by starting sync if not already started\n * Multiple concurrent calls will share the same promise\n */\n public preload(): Promise<void> {\n try {\n this.lifecycle.assertCanStartSync()\n // A direct reader owns this demand even if an earlier render left a\n // sync start deferred. Its preload must be able to start the source.\n if (this.syncStartDeferred) this.resumeStart()\n } catch (error) {\n return Promise.reject(error)\n }\n // Warm preloads need the same handoff time as a load that just finished,\n // including when the previous GC deadline already queued idle cleanup.\n if (this.lifecycle.status === `ready`) {\n this.lifecycle.cancelGCTimer()\n this.lifecycle.startGCTimerIfUnsubscribed()\n }\n if (this.preloadPromise) {\n return this.preloadPromise\n }\n\n // Warn when calling preload on an on-demand collection\n if (\n devBuild() &&\n process.env.NODE_ENV !== `production` &&\n this.syncMode === `on-demand`\n ) {\n console.warn(\n `${this.id ? `[${this.id}] ` : ``}Calling .preload() on a collection with syncMode \"on-demand\" is a no-op. ` +\n `In on-demand mode, data is only loaded when queries request it. ` +\n `Instead, create a live query and call .preload() on that to load the specific data you need. ` +\n `See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`,\n )\n }\n\n const attempt = new Promise<void>((resolve, reject) => {\n if (this.lifecycle.status === `ready`) {\n resolve()\n return\n }\n\n if (isFailedStatus(this.lifecycle.status)) {\n reject(this.getPreloadError())\n return\n }\n\n let settled = false\n const syncStartState = { active: false, ready: false }\n let unsubscribeError = () => {}\n let unsubscribeReady = () => {}\n const finishPreload = () => {\n settled = true\n unsubscribeError()\n unsubscribeReady()\n if (this.rejectPreload === rejectError) this.rejectPreload = undefined\n this.lifecycle.startGCTimerIfUnsubscribed()\n }\n const resolveReady = () => {\n if (syncStartState.active) {\n syncStartState.ready = true\n return\n }\n if (settled) return\n finishPreload()\n resolve()\n }\n const rejectError = (error: unknown) => {\n if (settled) return\n finishPreload()\n reject(error)\n }\n\n // Register callback BEFORE starting sync to avoid race condition\n this.rejectPreload = rejectError\n // An awaited preload owns this sync run until it settles, including\n // when GC has already queued the destructive idle callback.\n this.lifecycle.cancelGCTimer()\n unsubscribeReady = this.lifecycle.onFirstReady(resolveReady)\n const onFailure = () => {\n if (syncStartState.active) {\n return\n }\n rejectError(this.getPreloadError())\n }\n const unsubscribeFailed = this.collection.on(`status:error`, onFailure)\n const unsubscribeCrashed = this.collection.on(`status:crashed`, onFailure)\n unsubscribeError = () => {\n unsubscribeFailed()\n unsubscribeCrashed()\n }\n\n // Start sync if collection hasn't started yet or was cleaned up\n if (\n this.lifecycle.status === `idle` ||\n this.lifecycle.status === `cleaned-up`\n ) {\n syncStartState.active = true\n let startFailure: { error: unknown } | undefined\n try {\n this.startSync()\n } catch (error) {\n startFailure = { error }\n } finally {\n syncStartState.active = false\n }\n if (isFailedStatus(this.collection.status)) {\n rejectError(this.getPreloadError())\n } else if (syncStartState.ready) {\n // A first-ready listener can throw after readiness is established.\n // That failure still escapes direct startSync(). Preload follows the\n // final collection state after synchronous adapter entry, so it\n // reports the throw, which reaches no caller (the Collection stays\n // ready).\n if (startFailure) reportUncaught(startFailure.error)\n resolveReady()\n } else if (startFailure) {\n rejectError(startFailure.error)\n }\n }\n })\n\n this.preloadPromise = attempt\n void attempt.then(undefined, () => {\n if (this.preloadPromise === attempt) {\n this.preloadPromise = null\n }\n })\n return attempt\n }\n\n private getPreloadError(): unknown {\n const syncError = this.lifecycle.getSyncError()\n return syncError === undefined\n ? new CollectionIsInErrorStateError()\n : syncError\n }\n\n /**\n * Gets whether the collection is currently loading more data\n */\n public get isLoadingSubset(): boolean {\n return this.pendingLoadSubsetPromises.size > 0\n }\n\n /** @internal Observe subset requests caused by one imperative operation. */\n public beginLoadSubsetOperation(): {\n wait: () => true | Promise<void>\n cancel: () => void\n } {\n const previousOperation = this.activeLoadSubsetOperation\n const operation: LoadSubsetOperation = {\n pending: new Set(),\n waiting: false,\n completed: false,\n hasError: false,\n }\n // A new imperative operation owns future requests. Older operations keep\n // waiting for the promises they already acquired, but cannot absorb work\n // caused by a superseding physical window.\n this.activeLoadSubsetOperation = operation\n this.loadSubsetOperations.add(operation)\n return {\n wait: () => this.waitForLoadSubsetOperation(operation),\n cancel: () => {\n operation.completed = true\n this.loadSubsetOperations.delete(operation)\n if (this.activeLoadSubsetOperation === operation) {\n this.activeLoadSubsetOperation = previousOperation?.completed\n ? undefined\n : previousOperation\n }\n },\n }\n }\n\n private waitForLoadSubsetOperation(\n operation: LoadSubsetOperation,\n ): true | Promise<void> {\n operation.waiting = true\n if (operation.pending.size === 0) {\n this.completeLoadSubsetOperation(operation)\n return operation.hasError ? Promise.reject(operation.error) : true\n }\n operation.deferred = createDeferred<void>()\n return operation.deferred.promise\n }\n\n private settleLoadSubsetOperation(\n operation: LoadSubsetOperation,\n promise: Promise<unknown>,\n outcome: { ok: true } | { ok: false; error: unknown },\n ): void {\n if (operation.completed) return\n operation.pending.delete(promise)\n if (!outcome.ok && !operation.hasError) {\n operation.hasError = true\n operation.error = outcome.error\n }\n if (!operation.waiting || operation.pending.size > 0) return\n\n // A resolved request can synchronously publish source rows that register\n // follow-up loads. Let those registrations join this operation before it\n // is considered complete.\n queueMicrotask(() => {\n if (operation.completed || operation.pending.size > 0) return\n this.completeLoadSubsetOperation(operation)\n if (operation.hasError) {\n operation.deferred!.reject(operation.error)\n } else {\n operation.deferred!.resolve()\n }\n })\n }\n\n private completeLoadSubsetOperation(operation: LoadSubsetOperation): void {\n operation.completed = true\n this.loadSubsetOperations.delete(operation)\n if (this.activeLoadSubsetOperation === operation) {\n this.activeLoadSubsetOperation = undefined\n }\n }\n\n private emitLoadingSubsetChange(isLoadingSubset: boolean): void {\n this._events.emit(`loadingSubset:change`, {\n type: `loadingSubset:change`,\n collection: this.collection,\n isLoadingSubset,\n previousIsLoadingSubset: !isLoadingSubset,\n loadingSubsetTransition: isLoadingSubset ? `start` : `end`,\n })\n }\n\n /** @internal Attach a relevant existing request to the active operation. */\n public trackLoadSubsetOperationPromise(promise: Promise<unknown>): void {\n const operation = this.activeLoadSubsetOperation\n if (!operation || operation.pending.has(promise)) return\n\n operation.pending.add(promise)\n void promise.then(\n () => this.settleLoadSubsetOperation(operation, promise, { ok: true }),\n (error) =>\n this.settleLoadSubsetOperation(operation, promise, {\n ok: false,\n error,\n }),\n )\n }\n\n /**\n * Tracks a load promise for isLoadingSubset state.\n * @internal This is for internal coordination (e.g., live-query glue code), not for general use.\n */\n public trackLoadPromise(promise: Promise<unknown>): void {\n const syncRunGeneration = this.syncRunGeneration\n const loadingStarting = !this.isLoadingSubset\n this.pendingLoadSubsetPromises.add(promise)\n this.trackLoadSubsetOperationPromise(promise)\n\n if (loadingStarting) {\n this.emitLoadingSubsetChange(true)\n }\n\n const finish = () => {\n if (syncRunGeneration !== this.syncRunGeneration) return\n\n const loadingEnding =\n this.pendingLoadSubsetPromises.size === 1 &&\n this.pendingLoadSubsetPromises.has(promise)\n this.pendingLoadSubsetPromises.delete(promise)\n\n if (loadingEnding) {\n this.emitLoadingSubsetChange(false)\n }\n }\n void promise.then(finish, finish)\n }\n\n /** @internal Generation fence for subscription-owned async work. */\n public getSyncRunGeneration(): number {\n return this.syncRunGeneration\n }\n\n /**\n * Requests the sync layer to load more data.\n * @param options Options to control what data is being loaded\n * @returns If data loading is asynchronous, this method returns a promise that resolves when the data is loaded.\n * Returns true if no sync function is configured, if syncMode is 'eager', or if there is no work to do.\n */\n public loadSubset(options: LoadSubsetOptions): LoadSubsetRequestResult {\n if (options.signal?.aborted) {\n return Promise.reject(new LoadSubsetOperationAbortedError())\n }\n\n // Bypass loadSubset when syncMode is 'eager'\n if (this.syncMode === `eager`) {\n return true\n }\n\n if (this.syncStartDeferred) {\n this.syncStartRequested = true\n const deferred = createDeferred<void>()\n this.deferredLoadSubsets.push({ options, deferred })\n this.trackLoadPromise(deferred.promise)\n return deferred.promise\n }\n\n if (this.syncLoadSubsetFn) {\n const result = this.callLoadSubset(this.syncLoadSubsetFn, options)\n // If the result is a promise, track it\n if (result instanceof Promise) {\n this.trackLoadPromise(result)\n return result\n }\n }\n\n return true\n }\n\n /**\n * Run the adapter's loadSubset; a reload from inside it rejects. A\n * synchronous throw is a rejection: the load failed.\n */\n private callLoadSubset(\n loadSubset: NonNullable<typeof this.syncLoadSubsetFn>,\n options: LoadSubsetOptions,\n ): LoadSubsetRequestResult {\n this.loadSubsetDepth++\n try {\n return loadSubset(options)\n } catch (error) {\n return Promise.reject(error)\n } finally {\n this.loadSubsetDepth--\n }\n }\n\n /**\n * Notifies the sync layer that a subset is no longer needed.\n * @param options Options that identify what data is being unloaded\n */\n public unloadSubset(options: LoadSubsetOptions): void {\n // Eager loading bypasses subset acquisition, so there is no lease to release.\n if (this.syncMode === `eager`) return\n\n if (this.syncStartDeferred) {\n this.deferredLoadSubsets = this.deferredLoadSubsets.filter((request) => {\n if (request.options !== options) {\n return true\n }\n\n request.deferred.reject(new LoadSubsetOperationAbortedError())\n return false\n })\n return\n }\n\n if (this.syncUnloadSubsetFn) {\n this.syncUnloadSubsetFn(options)\n }\n }\n\n private wrapCleanupError(error: unknown): SyncCleanupError {\n const wrappedError = new SyncCleanupError(this.id, error as Error | string)\n wrappedError.cause = error\n if (error instanceof Error) wrappedError.stack = error.stack\n return wrappedError\n }\n\n private invokeCleanup(cleanup: CleanupFn | null): true | Promise<void> {\n if (!cleanup) return true\n\n try {\n const result = cleanup()\n if (!isPromiseLike(result)) return true\n return Promise.resolve(result).then(\n () => undefined,\n (error: unknown) => {\n throw this.wrapCleanupError(error)\n },\n )\n } catch (error) {\n throw this.wrapCleanupError(error)\n }\n }\n\n private registerPendingSyncEntryCleanup(cleanup: CleanupFn): void {\n const pending = this.pendingSyncEntryCleanup\n if (!pending) return\n\n try {\n const result = this.invokeCleanup(cleanup)\n if (result !== true) {\n pending.tasks.push(result)\n void result.catch(() => undefined)\n }\n } catch (error) {\n pending.failure ??= { error }\n }\n }\n\n private completePendingSyncEntryCleanup(): void {\n const pending = this.pendingSyncEntryCleanup\n if (!pending) return\n this.pendingSyncEntryCleanup = undefined\n\n const settle = (failure?: { error: unknown }) => {\n const outcome = pending.failure ?? failure\n pending.onSettled?.(outcome)\n if (outcome) pending.completion?.reject(outcome.error)\n else pending.completion?.resolve()\n }\n\n if (pending.tasks.length === 0) {\n settle()\n return\n }\n\n void Promise.allSettled(pending.tasks).then((outcomes) => {\n const rejected = outcomes.find(\n (outcome): outcome is PromiseRejectedResult =>\n outcome.status === `rejected`,\n )\n settle(rejected ? { error: rejected.reason } : undefined)\n })\n }\n\n /**\n * Retire the current adapter run for a reload: its callbacks, loaders, and\n * resources, but not the visible state, the status, or a waiting preload.\n */\n private retireSyncRun(): Promise<void> {\n this.syncRunGeneration++\n this.state.discardOpenSyncTransactions()\n const cleanup = this.syncCleanupFn\n this.syncCleanupFn = null\n this.syncLoadSubsetFn = null\n this.syncUnloadSubsetFn = null\n this.abortLoadSubsetWork()\n try {\n const result = this.invokeCleanup(cleanup)\n return result === true ? Promise.resolve() : result\n } catch (error) {\n return Promise.reject(error)\n }\n }\n\n private abortLoadSubsetWork(): void {\n const wasLoadingSubset = this.pendingLoadSubsetPromises.size > 0\n this.pendingLoadSubsetPromises.clear()\n if (wasLoadingSubset) {\n this.emitLoadingSubsetChange(false)\n }\n this.activeLoadSubsetOperation = undefined\n for (const operation of this.loadSubsetOperations) {\n if (!operation.completed) {\n operation.completed = true\n operation.pending.clear()\n operation.hasError = true\n operation.error = new LoadSubsetOperationAbortedError()\n operation.deferred?.reject(operation.error)\n }\n }\n this.loadSubsetOperations.clear()\n const deferredLoadSubsets = this.deferredLoadSubsets\n this.deferredLoadSubsets = []\n for (const request of deferredLoadSubsets) {\n request.deferred.reject(new LoadSubsetOperationAbortedError())\n }\n }\n\n public cleanup(): true | Promise<void>\n public cleanup(onSettled: (failure?: { error: unknown }) => void): boolean\n public cleanup(\n onSettled?: (failure?: { error: unknown }) => void,\n ): boolean | Promise<void> {\n // Invalidate callbacks retained by asynchronous work from this sync run\n // before invoking adapter cleanup or allowing a new sync run to start.\n ++this.syncCallbackEpoch\n this.syncRunGeneration++\n this.rejectPreload?.(new CollectionPreloadAbortedError())\n const cleanup = this.syncCleanupFn\n this.syncCleanupFn = null\n this.syncLoadSubsetFn = null\n this.syncUnloadSubsetFn = null\n\n let cleanupResult: true | Promise<void> = true\n let cleanupFailure: { error: unknown } | undefined\n try {\n cleanupResult = this.invokeCleanup(cleanup)\n } catch (error) {\n cleanupFailure = { error }\n }\n\n this.preloadPromise = null\n this.syncStartDeferred = false\n this.syncStartRequested = false\n this.abortLoadSubsetWork()\n\n if (this.syncEntryActive) {\n const completion = onSettled ? undefined : createDeferred<void>()\n const pending = {\n tasks: [] as Array<Promise<void>>,\n failure: cleanupFailure,\n onSettled,\n completion,\n }\n if (cleanupResult !== true) {\n pending.tasks.push(cleanupResult)\n void cleanupResult.catch(() => undefined)\n }\n this.pendingSyncEntryCleanup = pending\n return onSettled ? false : completion!.promise\n }\n\n if (cleanupFailure) throw cleanupFailure.error\n if (cleanupResult === true) return true\n\n if (!onSettled) return cleanupResult\n void cleanupResult.then(\n () => onSettled(),\n (error: unknown) => onSettled({ error }),\n )\n return false\n }\n}\n\nfunction normalizeSyncFnResult(result: void | CleanupFn | SyncConfigRes) {\n if (typeof result === `function`) {\n return { cleanup: result }\n }\n\n if (typeof result === `object`) {\n return result\n }\n\n return undefined\n}\n"],"mappings":";;;;;;;;;;AAkDA,IAAa,yBAAwC,uBAAO;AAgB5D,SAAS,aACP,MACA,OACS;CACT,MAAM,OAAO,OAAO,KAAK,IAAI;CAC7B,OACE,KAAK,WAAW,OAAO,KAAK,KAAK,CAAA,CAAE,UACnC,KAAK,OAAO,QAAQ,OAAO,GAAG,KAAK,MAAM,MAAM,IAAI,CAAC;AAExD;AAEA,IAAa,wBAAb,MAKE;;;;CA8CA,YACE,QACA,IACA;EAtC4C,KAAA,iBAAA;EAEL,KAAA,gBAAA;EACM,KAAA,mBAAA;EAE7C,KAAA,qBAAA;EAEyD,KAAAqB,qBAAA,IAAI,IAAI;EAEpC,KAAAC,qBAAA,IAAI,IAAyB;EAChC,KAAAC,KAAA;EACC,KAAAC,KAAA;EAC4B,KAAAC,KAAA,CAAC;EAI9B,KAAAC,KAAA;EACA,KAAA,oBAAA;EACF,KAAAC,KAAA;EAGA,KAAAC,KAAA;EAkBxB,KAAK,SAAS;EACd,KAAK,KAAK;EACV,KAAK,WAAW,OAAO,YAAY;CACrC;CAEA,QAAQ,MAKL;EACD,KAAK,aAAa,KAAK;EACvB,KAAK,QAAQ,KAAK;EAClB,KAAK,YAAY,KAAK;EACtB,KAAKC,KAAU,KAAK;CACtB;;;;;;;CAQAC,GACE,KACA,MACA,SACM;EACN,MAAM,QAAQ,QAAQ;EACtB,MAAM,cAAe,KAAKC,uBAAgB,IAAI,QAAQ;EACtD,IAAI;GACF,MAAM,UAAU,YAAY,IAAI,KAAK;GACrC,IACE,WACA,SAAS,YAET,EAAE,mBAAmB,YAC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