@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 99.6 kB
Source Map (JSON)
{"version":3,"file":"subscription.cjs","names":["createDeferred","EventEmitter","createFilteredCallback","LoadSubsetOperationAbortedError","isFailedStatus","sameRowValue","normalizeError","and","codedMessage","buildCursor","createFilterFunctionFromExpression","eq","Value","compileExpression","PropRef","getPropRefPropertyPath","buildCursorCurrent","_status","_lastError","skipFiltering","subsetDemands","requestedSubsetWhere","sentKeys","publishedRows","stalePublishedRows","statusRevision","pendingLoadSubsetParticipants","loadSubsetPromiseErrors","truncateReplacementPending","defersAcquisition","filteredCallback","sourceListenerCleanups","handleTruncate","handleCollectionCleanup","truncateReplayState","restartDetachedDemands","replaysDemand","discardTruncateReplay","setReadyIfIdle","isSyncRunGenerationCurrent","createTruncateReplayState","startTruncateReplayAttempt","resetSnapshotTracking","retireStaleTruncateReplay","startTruncateReplayDemand","isDemandActive","createSubsetAcquisitionRecord","observeLoadSubsetResult","trackTruncateReplayParticipant","settleTruncateReplay","checkTruncateReplayComplete","normalizeLoadSubsetPromiseError","removeTruncateReplayParticipant","abandonTruncateReplay","awaitsSiblingReplays","flushTruncateReplay","publishReplayRows","createStateDiff","restorePublishedSnapshotTracking","bufferPrivately","isBufferingForTruncate","recordLoadSubsetError","stopDemandStatusParticipants","startSubsetDemand","filterAndFlipChanges","publishSnapshot","releaseDemand","reconcileStalePublishedChanges","requestedWhere","releaseDemands","retireEmptyReplay"],"sources":["../../../src/collection/subscription.ts"],"sourcesContent":["import { ensureIndexForExpression } from '../indexes/auto-index.js'\nimport { and, eq } from '../query/builder/functions.js'\nimport { PropRef, Value, getPropRefPropertyPath } from '../query/ir.js'\nimport { EventEmitter } from '../event-emitter.js'\nimport { compileExpression } from '../query/compiler/evaluators.js'\nimport { buildCursor, buildCursorCurrent } from '../utils/cursor.js'\nimport { sameRowValue } from '../utils.js'\nimport { normalizeError } from '../utils/error.js'\nimport { reportUncaught, runAllCallbacks } from '../utils/callbacks.js'\nimport { createDeferred } from '../deferred.js'\nimport { LoadSubsetOperationAbortedError } from '../errors.js'\nimport { isFailedStatus } from '../live-query-primitives.js'\nimport { codedMessage, devBuild } from '../error-message.js'\nimport {\n createFilterFunctionFromExpression,\n createFilteredCallback,\n} from './change-events.js'\nimport type { BasicExpression, OrderBy } from '../query/ir.js'\nimport type { IndexReader } from '../indexes/base-index.js'\nimport type {\n ChangeMessage,\n CollectionDependent,\n LoadSubsetOptions,\n LoadSubsetRequestResult,\n SubscribeChangesOptions,\n Subscription,\n SubscriptionEvents,\n SubscriptionLoadSubsetErrorEvent,\n SubscriptionStatus,\n SubscriptionUnsubscribedEvent,\n} from '../types.js'\nimport type { CollectionImpl } from './index.js'\nimport type { Deferred } from '../deferred.js'\n\ntype RequestSnapshotOptions = {\n refetch?: boolean\n where?: BasicExpression<boolean>\n signal?: AbortSignal\n optimizedOnly?: boolean\n trackLoadSubsetPromise?: boolean\n /** Optional orderBy to pass to loadSubset for backend optimization */\n orderBy?: OrderBy\n /** Optional limit to pass to loadSubset for backend optimization */\n limit?: number\n /** Read only the first `limit` local rows: the source holds every row and an index serves the order. */\n boundedPrefix?: boolean\n /** Callback that receives the normalized loadSubset result for internal tracking */\n onLoadSubsetResult?: SubsetResultObserver\n /** Called when the local snapshot must fall back from an index to a scan. */\n onUnoptimized?: () => void\n}\n\ntype RequestLimitedSnapshotOptions = {\n refetch?: boolean\n orderBy: OrderBy\n limit: number\n /** A single cursor value; composite cursor inputs are rejected. */\n minValues?: Array<unknown>\n /** Row offset for offset-based pagination (passed to sync layer) */\n offset?: number\n /** Whether to track the loadSubset promise on this subscription (default: true) */\n trackLoadSubsetPromise?: boolean\n /** Callback that receives the normalized loadSubset result for internal tracking */\n onLoadSubsetResult?: SubsetResultObserver\n}\n\nexport type ReleaseLoadSubset = (primaryFailure?: { error: unknown }) => void\n\ntype SubsetResultObserver = (\n result: LoadSubsetRequestResult,\n options: LoadSubsetOptions,\n release: ReleaseLoadSubset,\n) => void\n\ntype CollectionSubscriptionOptions = {\n includeInitialState?: boolean\n /** Pre-compiled expression for filtering changes */\n whereExpression?: BasicExpression<boolean>\n /** Callback to call when the subscription is unsubscribed */\n onUnsubscribe?: (event: SubscriptionUnsubscribedEvent) => void\n /** Callback for subset-load failures scoped to this subscription. */\n onLoadSubsetError?: (event: SubscriptionLoadSubsetErrorEvent) => void\n truncateReplayPublication?: TruncateReplayPublicationControl\n /**\n * Whether this subscription defers provider work: it starts no idle source\n * sync run and no acquisition attempt until its acquisition resumes. A\n * live-query Collection defers its source subscriptions until it has a\n * subscriber or a preload in its current sync run.\n */\n deferAcquisition?: boolean\n /** Start sync, then return the ownership notification for a live resumption. */\n onResumeAcquisition?: () => () => void\n /** The live query or Effect this subscription reads for. */\n owner?: CollectionDependent\n /** The subscriber drops its rows when the Collection is cleaned up. */\n discardsRowsOnCleanup?: boolean\n}\n\ntype TruncateReplayPublicationControl = NonNullable<\n SubscribeChangesOptions[`truncateReplayPublication`]\n>\n\ntype TruncatePublicationState = {\n loadedInitialState: boolean\n snapshotSent: boolean\n}\n\n/** Internal record spanning a tentative attempt and any accepted acquisition. */\ntype SubsetAcquisitionRecord = {\n options: LoadSubsetOptions\n syncRunGeneration: number\n abortController?: AbortController\n removeRequestAbortListener?: () => void\n releaseAttempted?: true\n // The replay attempt that started this acquisition.\n attempt?: TruncateReplayAttempt\n}\n\ntype SubsetDemand = {\n requestOptions: LoadSubsetOptions\n acquisition: SubsetAcquisitionRecord\n acquisitionState: `starting` | `active` | `detached`\n initialResult?: Deferred<void>\n // A parked demand's wait in an open replay. An acquisition that replays\n // it replaces the wait, which settles only with that replay.\n parkedParticipant?: TruncateReplayParticipant\n // The demands this one replaces for its owner: their replay failures no\n // longer count once it loads (law 10: the latest load decides).\n replaces?: Array<SubsetDemand>\n}\n\ntype TruncateReplayAttempt = {\n pendingCount: number\n setupComplete: boolean\n}\n\ntype TruncateReplayParticipant = {\n demand: SubsetDemand\n attempt: TruncateReplayAttempt\n}\n\ntype TruncateReplayState = {\n syncRunGeneration: number\n publicationState: TruncatePublicationState\n /** Direct subscribers buffer the replacement here; delegated publication has no buffer. */\n privateRows: Map<string | number, object> | undefined\n pending: Set<TruncateReplayParticipant>\n pendingSetups: number\n currentAttempt: TruncateReplayAttempt\n failures: Map<SubsetDemand, Error>\n /**\n * Demands whose load of the current attempt was aborted before it settled:\n * the abort ended it, so it loaded nothing and covers no demand it\n * replaces (law 10).\n */\n unloaded: Set<SubsetDemand>\n /** The current attempt failed, even if its failed demand was released since. */\n failed: boolean\n completion: Deferred<void>\n}\n\nfunction createReplayCompletion(): Deferred<void> {\n const completion = createDeferred<void>()\n void completion.promise.catch(() => {})\n return completion\n}\n\nfunction cancelAcquisition(acquisition: SubsetAcquisitionRecord): void {\n acquisition.abortController?.abort()\n acquisition.removeRequestAbortListener?.()\n}\n\n// An abort before the load settles ends it. Once the load settles, the\n// listener goes, so it keeps nothing alive for the acquisition's lifetime\n// (law 13).\nfunction onAbortBeforeSettled(\n signal: AbortSignal | undefined,\n result: Promise<unknown>,\n onAbort: () => void,\n): void {\n signal?.addEventListener(`abort`, onAbort, { once: true })\n const settled = () => signal?.removeEventListener(`abort`, onAbort)\n void result.then(settled, settled)\n}\n\nexport class CollectionSubscription\n extends EventEmitter<SubscriptionEvents>\n implements Subscription\n{\n private loadedInitialState = false\n\n // Flag to skip filtering in filterAndFlipChanges.\n // This is separate from loadedInitialState because we want to allow\n // requestSnapshot to still work even when filtering is skipped.\n private skipFiltering = false\n\n // Flag to indicate that we have sent at least 1 snapshot.\n // While `snapshotSent` is false we filter out all changes from subscription to the collection.\n private snapshotSent = false\n\n /**\n * Track all loadSubset calls made by this subscription so we can unload them on cleanup.\n * We store the exact LoadSubsetOptions we passed to loadSubset to ensure symmetric unload.\n */\n private subsetDemands: Array<SubsetDemand> = []\n private readonly requestedSubsetWhere = new WeakMap<\n LoadSubsetOptions,\n BasicExpression<boolean>\n >()\n\n // Keep track of keys selected by snapshots or delivered through callbacks.\n // Ordered snapshots skip these keys until a valid reset.\n private sentKeys = new Set<string | number>()\n private publishedRows = new Map<string | number, object>()\n private stalePublishedRows = new Map<string | number, object>()\n\n private filteredCallback: (changes: Array<ChangeMessage<any, any>>) => boolean\n\n private orderByIndex: IndexReader<string | number> | undefined\n\n // Status tracking\n private _status: SubscriptionStatus = `ready`\n private statusRevision = 0\n private _lastError: unknown | undefined\n private pendingLoadSubsetParticipants = new Set<{\n demand: SubsetDemand\n promise: Promise<unknown>\n }>()\n\n // Source listeners retire together on unsubscription.\n private sourceListenerCleanups: Array<() => void>\n\n // One replay state owns the publication baseline, overlapping attempts,\n // and buffered changes until every attempt settles.\n private truncateReplayState: TruncateReplayState | undefined\n private readonly loadSubsetPromiseErrors = new WeakMap<\n Promise<unknown>,\n Error\n >()\n private truncateReplacementPending = false\n private unsubscribed = false\n private defersAcquisition: boolean\n\n /** @internal The live query or Effect this subscription reads for. */\n public get owner(): CollectionSubscriptionOptions[`owner`] {\n return this.options.owner\n }\n\n public get status(): SubscriptionStatus {\n return this._status\n }\n\n public get lastError(): unknown | undefined {\n return this._lastError\n }\n\n constructor(\n private collection: CollectionImpl<any, any, any, any, any>,\n private callback: (changes: Array<ChangeMessage<any, any>>) => void,\n private options: CollectionSubscriptionOptions,\n ) {\n super()\n this.defersAcquisition = options.deferAcquisition === true\n if (options.onUnsubscribe) {\n this.on(`unsubscribed`, options.onUnsubscribe)\n }\n if (options.onLoadSubsetError) {\n this.on(`loadSubset:error`, options.onLoadSubsetError)\n }\n\n // Auto-index for where expressions if enabled\n if (options.whereExpression) {\n ensureIndexForExpression(options.whereExpression, this.collection)\n }\n\n this.callback = (changes) => {\n // Complete both publication records before a callback can reenter.\n for (const change of changes) {\n if (change.type === `delete`) {\n this.publishedRows.delete(change.key)\n this.sentKeys.delete(change.key)\n } else {\n this.publishedRows.set(change.key, change.value)\n this.sentKeys.add(change.key)\n }\n }\n callback(changes)\n }\n\n // Create a filtered callback if where clause is provided\n this.filteredCallback = options.whereExpression\n ? createFilteredCallback(this.callback, options)\n : (changes) => {\n this.callback(changes)\n return true\n }\n\n // A truncate or a snapshot (for example a 409 must-refetch) clears every\n // row, so every one re-requests the loaded subsets, also one that a\n // reload's new run sends after the reload's replay began or settled: the\n // replacement deleted what that replay loaded.\n this.sourceListenerCleanups = [\n this.collection.on(`truncate`, () => this.handleTruncate()),\n this.collection._onCleanupStart(() => this.handleCollectionCleanup()),\n this.collection.on(`status:change`, ({ status }) => {\n if (status !== `loading` && status !== `ready`) return\n const syncRunGeneration = this.collection._sync.getSyncRunGeneration()\n const replayState = this.truncateReplayState\n if (\n this.subsetDemands.some(\n (demand) => demand.acquisitionState === `detached`,\n )\n ) {\n this.setStatus(`loadingSubset`)\n }\n queueMicrotask(() => {\n if (this.truncateReplayState === replayState) {\n this.restartDetachedDemands(syncRunGeneration)\n }\n })\n }),\n ]\n }\n\n /** Whether this subscription still defers provider work. */\n public isDeferringAcquisition(): boolean {\n return this.defersAcquisition\n }\n\n /**\n * Resume deferred acquisition: provider work may now start. This may start\n * an idle source Collection's sync run, then starts acquisition attempts for\n * the on-demand demand that stayed detached while acquisition was deferred.\n */\n public resumeDeferredAcquisition(): void {\n if (!this.defersAcquisition || this.unsubscribed) return\n // Start the source first: if its start throws, this subscription still\n // defers rather than claiming acquisition it never began.\n const notifyResumed = this.options.onResumeAcquisition?.()\n // Startup can synchronously retire this subscription. It then owns no\n // acquisition, including when a status callback unsubscribes during startup.\n if (this.unsubscribed as boolean) return\n this.defersAcquisition = false\n notifyResumed?.()\n if (this.collection.status !== `idle`) {\n this.restartDetachedDemands(this.collection._sync.getSyncRunGeneration())\n }\n }\n\n /**\n * @internal A reload retired the sync run. Its demand detaches from the\n * retired run, and on-demand demand replays through the new run at once,\n * as after a truncate, so a consumer of an aborted load follows that\n * replay. The rows stay: the new run's writes apply on them.\n */\n public retireSyncRun(): void {\n const replays = this.replaysDemand() && this.subsetDemands.length > 0\n // The replacement stays pending from the old replay to the new one, so\n // nothing that runs during the detach sees a settled source.\n this.handleCollectionCleanup(true, replays)\n if (replays) this.handleTruncate(true)\n }\n\n /** Whether a truncate acquires this subscription's demand again. */\n private replaysDemand(): boolean {\n // Eager demand is satisfied by source readiness, even when the adapter\n // happens to expose a loader. Deferred demand never acquired, so it\n // acquires the replacement rows when acquisition resumes.\n return (\n this.collection.config.syncMode === `on-demand` && !this.defersAcquisition\n )\n }\n\n /**\n * Detach logical demand from work owned by a discarded sync run. A reload\n * keeps waiting callers for its replay, and the rows.\n */\n private handleCollectionCleanup(\n reload = false,\n holdReplacement = false,\n ): void {\n this.discardTruncateReplay()\n this.truncateReplacementPending = holdReplacement\n // Cleanup discards the rows without publishing deletes, so the published\n // rows go stale. A reload keeps the rows: only rows already stale stay so.\n // A subscriber that drops its rows with the Collection, as a live-query\n // observer's `cleaned-up` view does, holds none: a later write of an\n // equal row is new to it, not a duplicate of its last publication.\n if (!reload) {\n if (this.options.discardsRowsOnCleanup) {\n this.publishedRows = new Map()\n this.sentKeys = new Set()\n this.stalePublishedRows = new Map()\n } else this.stalePublishedRows = new Map(this.publishedRows)\n }\n this.pendingLoadSubsetParticipants.clear()\n\n for (const demand of [...this.subsetDemands]) {\n if (!reload || demand.acquisitionState === `starting`) {\n demand.initialResult?.reject(new LoadSubsetOperationAbortedError())\n }\n cancelAcquisition(demand.acquisition)\n if (demand.acquisitionState === `starting`) {\n const index = this.subsetDemands.indexOf(demand)\n if (index !== -1) this.subsetDemands.splice(index, 1)\n } else {\n demand.acquisitionState = `detached`\n demand.acquisition = {\n options: demand.requestOptions,\n syncRunGeneration: demand.acquisition.syncRunGeneration,\n }\n }\n }\n this.setReadyIfIdle()\n }\n\n /** Acquire detached demand after startup or initial-error recovery. */\n private restartDetachedDemands(syncRunGeneration: number): void {\n if (\n this.unsubscribed ||\n // Deferred demand stays detached until acquisition resumes, even when\n // another consumer starts the source.\n this.defersAcquisition ||\n !this.isSyncRunGenerationCurrent(syncRunGeneration)\n ) {\n return\n }\n if (\n isFailedStatus(this.collection.status) ||\n (this.collection.config.syncMode === `on-demand` &&\n this.collection._sync.syncLoadSubsetFn === null)\n ) {\n this.setReadyIfIdle()\n return\n }\n const demands = this.subsetDemands.filter(\n (demand) =>\n demand.acquisitionState === `detached` &&\n !demand.requestOptions.signal?.aborted,\n )\n if (demands.length === 0) {\n this.setReadyIfIdle()\n return\n }\n // Eager demand is satisfied by the complete ready snapshot, never by a\n // subset acquisition or the partial state of a loading sync run.\n if (\n this.collection.config.syncMode !== `on-demand` &&\n this.collection.status !== `ready`\n ) {\n return\n }\n\n // A replay still open in this sync run keeps its loads and failures: the\n // detached demand joins it (law 9), in its current attempt while that\n // attempt is in flight, and as a new attempt once it failed (law 16).\n const open = this.truncateReplayState\n const joins = open?.syncRunGeneration === syncRunGeneration\n const replayState = joins\n ? open\n : this.createTruncateReplayState(() => {\n const currentRows = this.collection.currentStateAsChanges({\n optimizedOnly: false,\n })\n return new Map(\n // The API returns void for unavailable snapshots, not just undefined.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n (currentRows ?? [])\n .filter((change) => change.type !== `delete`)\n .map((change) => [change.key, change.value]),\n )\n })\n if (joins) {\n open.pendingSetups++\n if (open.failed) {\n if (!open.completion.isPending())\n open.completion = createReplayCompletion()\n open.currentAttempt = { pendingCount: 0, setupComplete: false }\n }\n }\n const attempt = replayState.currentAttempt\n this.truncateReplayState = replayState\n this.setStatus(`loadingSubset`)\n if (this.truncateReplayState !== replayState) return\n this.startTruncateReplayAttempt(replayState, attempt, demands)\n }\n\n /**\n * Handle collection truncate event by resetting state and re-requesting subsets.\n * This is called when the sync layer receives a must-refetch and clears all data.\n *\n * To prevent a flash of missing content, we buffer all changes (deletes from truncate\n * and inserts from refetch) until all loadSubset calls succeed, then emit them together.\n * A failed replay keeps the last published snapshot private until a later\n * authoritative replay succeeds.\n */\n private handleTruncate(retired = false) {\n // A reload's replay, or a snapshot, can start inside the new run's\n // `sync()`, before it returns its loader; the requests below start after\n // it has.\n const demandsToReload = this.replaysDemand() ? [...this.subsetDemands] : []\n\n // Retained rows still need the committed replacement even without demand.\n if (demandsToReload.length === 0 && this.stalePublishedRows.size === 0) {\n this.resetSnapshotTracking()\n return\n }\n\n let replayState = this.truncateReplayState\n if (replayState) {\n if (!replayState.completion.isPending()) {\n replayState.completion = createReplayCompletion()\n }\n // Setup itself holds publication: adapter/status callbacks may reenter\n // before a request returns its promise and joins the pending set.\n replayState.pendingSetups++\n replayState.failures.clear()\n replayState.unloaded.clear()\n replayState.failed = false\n replayState.currentAttempt = { pendingCount: 0, setupComplete: false }\n } else {\n // Every overlapping attempt shares one publication baseline and buffer.\n replayState = this.createTruncateReplayState(\n () => new Map(this.publishedRows),\n )\n this.truncateReplayState = replayState\n }\n const attempt = replayState.currentAttempt\n this.setStatus(`loadingSubset`)\n\n if (this.truncateReplayState !== replayState) return\n\n if (this.options.truncateReplayPublication) {\n this.truncateReplacementPending = true\n this.options.truncateReplayPublication.start(retired)\n }\n\n // A newer replay replaces every prior acquisition for these demands. Abort\n // the old work before it can install rows into the replacement replay.\n for (const demand of demandsToReload) {\n demand.acquisition.abortController?.abort()\n }\n\n // Reset snapshot/pagination tracking for the replacement snapshot. Rows\n // retained from an earlier failed replay stay marked until this attempt\n // either replaces them or proves they are absent.\n this.resetSnapshotTracking()\n\n // Defer the requests so the truncate commit's deletes enter the replay state\n // buffer before a synchronous adapter can publish replacement rows.\n queueMicrotask(() => {\n if (this.truncateReplayState !== replayState) return\n if (!this.isSyncRunGenerationCurrent(replayState.syncRunGeneration)) {\n this.retireStaleTruncateReplay(replayState)\n return\n }\n // A newer truncate that arrived before this attempt began source work\n // already captured the active demands. Starting them now would place the\n // obsolete acquisition outside the newer abort sweep.\n this.startTruncateReplayAttempt(\n replayState,\n attempt,\n replayState.currentAttempt === attempt ? demandsToReload : [],\n )\n })\n }\n\n /** Make tentative replay ownership visible before adapter code can reenter. */\n private startTruncateReplayDemand(\n replayState: TruncateReplayState,\n attempt: TruncateReplayAttempt,\n demand: SubsetDemand,\n ): void {\n const isCurrent = () =>\n this.truncateReplayState === replayState &&\n replayState.currentAttempt === attempt &&\n this.isSyncRunGenerationCurrent(replayState.syncRunGeneration) &&\n this.isDemandActive(demand)\n const waiting = demand.initialResult\n const parked = demand.parkedParticipant\n demand.parkedParticipant = undefined\n if (parked && replayState.pending.delete(parked))\n parked.attempt.pendingCount--\n if (waiting) {\n // A replay discarded by a later reload leaves the caller waiting for\n // that reload's replay; cleanup rejects waiting callers itself.\n void replayState.completion.promise.then(waiting.resolve, (error) => {\n if (!(error instanceof LoadSubsetOperationAbortedError))\n waiting.reject(error)\n })\n }\n\n // Sequential handoff: retire the old acquisition lease while retaining its\n // logical demand. Callback reentry cannot release that lease twice.\n const previous = demand.acquisition\n const hadPreviousAcquisition = demand.acquisitionState === `active`\n demand.acquisitionState = `detached`\n if (hadPreviousAcquisition) this.releaseAcquisition(previous)\n if (!isCurrent() || demand.requestOptions.signal?.aborted) return\n\n const next = this.createSubsetAcquisitionRecord(demand.requestOptions)\n next.attempt = attempt\n demand.acquisition = next\n demand.acquisitionState = `starting`\n const result = this.collection._sync.loadSubset(next.options)\n\n if (!isCurrent()) {\n if (demand.acquisition === next) demand.acquisitionState = `detached`\n this.releaseAcquisition(next)\n return\n }\n\n demand.acquisitionState = `active`\n // Observe first: a failure reports before its settlement can publish the\n // replay, also when a held replacement covers it and it settles last.\n this.observeLoadSubsetResult(\n result,\n demand,\n next.options,\n true,\n () => isCurrent() && !next.options.signal?.aborted,\n )\n this.trackTruncateReplayParticipant(\n replayState,\n attempt,\n demand,\n result,\n next.options.signal,\n )\n }\n\n private settleTruncateReplay(\n replayState: TruncateReplayState,\n pending: { demand: SubsetDemand; attempt: TruncateReplayAttempt },\n ): void {\n try {\n if (this.truncateReplayState !== replayState) return\n if (!this.isSyncRunGenerationCurrent(replayState.syncRunGeneration)) {\n this.retireStaleTruncateReplay(replayState)\n return\n }\n if (replayState.pending.delete(pending)) pending.attempt.pendingCount--\n this.checkTruncateReplayComplete(replayState)\n } catch (error) {\n // Replay settlement runs from a Promise callback, so throwing here would\n // create an unobserved derived rejection. Surface subscriber errors like\n // other async collection events instead.\n reportUncaught(error)\n }\n }\n\n /**\n * Keep every acquisition begun during recovery inside its publication\n * barrier until it settles or aborts. An abort ends the load: the replay\n * no longer waits for it, and its later settlement decides nothing.\n */\n private trackTruncateReplayParticipant(\n replayState: TruncateReplayState,\n attempt: TruncateReplayAttempt,\n demand: SubsetDemand,\n result: LoadSubsetRequestResult,\n signal: AbortSignal | undefined,\n ): TruncateReplayParticipant | undefined {\n if (\n this.truncateReplayState !== replayState ||\n (replayState.currentAttempt !== attempt &&\n attempt.setupComplete &&\n attempt.pendingCount === 0) ||\n !(result instanceof Promise)\n ) {\n return undefined\n }\n\n // An older attempt can still accept returning startup work while setup or\n // another participant retains it. Once drained, it cannot reopen. Shared\n // promises still get one participant per logical acquisition.\n const pending = { demand, attempt }\n attempt.pendingCount++\n replayState.pending.add(pending)\n const settle = () => this.settleTruncateReplay(replayState, pending)\n // After the step that aborted it, as a settlement would be.\n onAbortBeforeSettled(signal, result, () => {\n if (replayState.currentAttempt === attempt)\n replayState.unloaded.add(demand)\n queueMicrotask(settle)\n })\n void result.then(settle, (error: unknown) => {\n if (\n !signal?.aborted &&\n this.truncateReplayState === replayState &&\n replayState.currentAttempt === attempt &&\n this.isSyncRunGenerationCurrent(replayState.syncRunGeneration) &&\n this.subsetDemands.includes(demand)\n ) {\n const normalized = this.normalizeLoadSubsetPromiseError(result, error)\n replayState.failures.set(demand, normalized)\n replayState.failed = true\n }\n settle()\n })\n return pending\n }\n\n /** Stop obsolete logical demand from pinning a replay barrier. */\n private removeTruncateReplayParticipant(demand: SubsetDemand): void {\n const replayState = this.truncateReplayState\n if (!replayState) return\n replayState.failures.delete(demand)\n for (const pending of replayState.pending) {\n if (pending.demand === demand) {\n replayState.pending.delete(pending)\n pending.attempt.pendingCount--\n }\n }\n }\n\n /** Publish only after every overlapping replay attempt has settled. */\n private checkTruncateReplayComplete(replayState: TruncateReplayState): void {\n if (this.truncateReplayState !== replayState) return\n if (replayState.pendingSetups > 0 || replayState.pending.size > 0) return\n\n // A held replacement that loaded decides the demands it replaces.\n const activeFailures: Array<Error> = []\n for (const [demand, error] of replayState.failures) {\n if (\n this.subsetDemands.includes(demand) &&\n !this.subsetDemands.some(\n (replacement) =>\n replacement.replaces?.includes(demand) &&\n !replayState.failures.has(replacement) &&\n !replayState.unloaded.has(replacement),\n )\n )\n activeFailures.push(error)\n }\n try {\n if (activeFailures.length > 0) {\n this.abandonTruncateReplay(replayState, activeFailures)\n } else {\n if (\n this.awaitsSiblingReplays(replayState, () =>\n this.checkTruncateReplayComplete(replayState),\n )\n )\n return\n this.flushTruncateReplay(replayState)\n }\n } finally {\n this.setReadyIfIdle()\n }\n }\n\n /**\n * Keep an incomplete replay private. The source no longer proves a complete\n * state, so only a later successful truncate replay may reopen publication.\n */\n private abandonTruncateReplay(\n replayState: TruncateReplayState,\n failures: Array<Error>,\n ): void {\n if (this.truncateReplayState !== replayState) return\n // A later check of the same failed attempt reports nothing new. The\n // replay's own error is its earliest failure.\n const first = replayState.completion.isPending()\n replayState.completion.reject(failures[0])\n if (first) this.options.truncateReplayPublication?.fail?.(failures)\n // Delegated publication already delivered its rows. Only a private buffer\n // returns the caller's pagination position to the public snapshot; the\n // private rows and their sent-key tracking stay together for a retry.\n if (!replayState.privateRows) return\n const publicationState = replayState.publicationState\n this.loadedInitialState = publicationState.loadedInitialState\n this.snapshotSent = publicationState.snapshotSent\n }\n\n /** Publish the buffered replacement as one batch, or release the delegate. */\n private flushTruncateReplay(replayState: TruncateReplayState): void {\n if (this.truncateReplayState !== replayState) return\n this.truncateReplayState = undefined\n this.truncateReplacementPending = false\n try {\n this.publishReplayRows(replayState.privateRows)\n } finally {\n replayState.completion.resolve()\n this.options.truncateReplayPublication?.succeed()\n }\n }\n\n /** Replace the public snapshot with a replay's private rows in one batch. */\n private publishReplayRows(\n privateRows: Map<string | number, object> | undefined,\n ): void {\n // Retained rows the source never re-delivered leave the replacement.\n for (const key of this.stalePublishedRows.keys()) privateRows?.delete(key)\n this.stalePublishedRows.clear()\n try {\n if (privateRows) {\n // Diff the retained public snapshot against the applied source replacement.\n const replacement = this.createStateDiff(\n this.publishedRows,\n privateRows,\n )\n if (replacement.length > 0) this.filteredCallback(replacement)\n }\n } finally {\n // Restore tracking even when a subscriber rejects the replacement.\n this.restorePublishedSnapshotTracking()\n }\n }\n\n private restorePublishedSnapshotTracking(): void {\n this.sentKeys = new Set(this.publishedRows.keys())\n }\n\n /** Fold changes into the private replacement; false when they publish now. */\n private bufferPrivately(\n changes: ReadonlyArray<ChangeMessage<any, any>>,\n ): boolean {\n const privateRows = this.truncateReplayState?.privateRows\n if (!privateRows) return false\n for (const change of changes) {\n if (change.type === `delete`) privateRows.delete(change.key)\n else privateRows.set(change.key, change.value)\n }\n return true\n }\n\n private createStateDiff(\n baseline: ReadonlyMap<string | number, object>,\n finalRows: ReadonlyMap<string | number, object>,\n ): Array<ChangeMessage<any, any>> {\n const replacement: Array<ChangeMessage<any, any>> = []\n for (const [key, previousValue] of baseline) {\n const value = finalRows.get(key)\n if (value === undefined) {\n replacement.push({\n type: `delete`,\n key,\n value: previousValue,\n })\n } else if (!sameRowValue(value, previousValue)) {\n replacement.push({\n type: `update`,\n key,\n value,\n previousValue,\n })\n }\n }\n for (const [key, value] of finalRows) {\n if (!baseline.has(key)) replacement.push({ type: `insert`, key, value })\n }\n return replacement\n }\n\n private get isBufferingForTruncate(): boolean {\n return this.truncateReplayState !== undefined\n }\n\n private setReadyIfIdle(): void {\n if (\n this.pendingLoadSubsetParticipants.size === 0 &&\n !this.hasTruncateReplayWork\n ) {\n this.setStatus(`ready`)\n }\n }\n\n private isSyncRunGenerationCurrent(syncRunGeneration: number): boolean {\n return syncRunGeneration === this.collection._sync.getSyncRunGeneration()\n }\n\n private retireStaleTruncateReplay(replayState: TruncateReplayState): void {\n if (this.truncateReplayState !== replayState) return\n this.discardTruncateReplay()\n this.stalePublishedRows.clear()\n }\n\n /**\n * A lazy demand that failed outside this subscription's replay, while a\n * replay of another of the graph's subscriptions to this collection still\n * holds publication, fails this subscription's replacement too. It keeps\n * the last publication until every demand load that joins this replay\n * loads, a later replay succeeds, or this subscription's last demand\n * retires. The failed demand's retry joins it, so it cannot publish\n * without that demand's rows.\n */\n failReplacement(error: Error): void {\n if (this.truncateReplayState) return\n const replayState = this.createTruncateReplayState(() => new Map())\n replayState.pendingSetups = 0\n replayState.failed = true\n replayState.completion.reject(error)\n this.truncateReplayState = replayState\n this.truncateReplacementPending = true\n }\n\n /**\n * A graph's subscriptions to one collection share a barrier. While another\n * one's replay still loads, this replay stays open, so demand this one\n * starts meanwhile joins it; it finishes once those replays settle.\n */\n private awaitsSiblingReplays(\n replayState: TruncateReplayState,\n finish: () => void,\n ): boolean {\n const siblings = this.options.truncateReplayPublication?.siblingReplays()\n void siblings?.then(() => {\n if (this.truncateReplayState === replayState) finish()\n })\n return siblings !== undefined\n }\n\n /** Whether this subscription's replay still waits on its own work. */\n public get hasTruncateReplayWork(): boolean {\n const replayState = this.truncateReplayState\n return (\n replayState !== undefined &&\n (replayState.pendingSetups > 0 || replayState.pending.size > 0)\n )\n }\n\n /** Drop the replay without publishing; an unfinished wait rejects as aborted. */\n private discardTruncateReplay(): void {\n const replayState = this.truncateReplayState\n if (replayState?.completion.isPending()) {\n replayState.completion.reject(new LoadSubsetOperationAbortedError())\n }\n this.truncateReplayState = undefined\n this.truncateReplacementPending = false\n }\n\n private resetSnapshotTracking(): void {\n this.snapshotSent = false\n this.loadedInitialState = false\n }\n\n /** One replay state; only direct subscribers buffer a private replacement. */\n private createTruncateReplayState(\n privateRows: () => Map<string | number, object>,\n ): TruncateReplayState {\n return {\n syncRunGeneration: this.collection._sync.getSyncRunGeneration(),\n publicationState: {\n loadedInitialState: this.loadedInitialState,\n snapshotSent: this.snapshotSent,\n },\n privateRows: this.options.truncateReplayPublication\n ? undefined\n : privateRows(),\n pending: new Set(),\n // Setup itself holds publication: adapter/status callbacks may reenter\n // before a request returns its promise and joins the pending set.\n pendingSetups: 1,\n currentAttempt: { pendingCount: 0, setupComplete: false },\n failures: new Map(),\n unloaded: new Set(),\n failed: false,\n completion: createReplayCompletion(),\n }\n }\n\n /** Start one attempt's demands, then release the setup hold on publication. */\n private startTruncateReplayAttempt(\n replayState: TruncateReplayState,\n attempt: TruncateReplayAttempt,\n demands: ReadonlyArray<SubsetDemand>,\n ): void {\n for (const demand of demands) {\n // A demand this attempt already started, as a restart that joined it\n // before its own setup ran, is loading for it: one attempt loads each\n // demand once.\n if (\n !this.subsetDemands.includes(demand) ||\n demand.acquisition.attempt === attempt\n )\n continue\n this.startTruncateReplayDemand(replayState, attempt, demand)\n if (\n this.truncateReplayState !== replayState ||\n replayState.currentAttempt !== attempt\n ) {\n break\n }\n }\n attempt.setupComplete = true\n replayState.pendingSetups--\n this.checkTruncateReplayComplete(replayState)\n }\n\n public get hasPendingTruncateReplacement(): boolean {\n return this.truncateReplacementPending\n }\n\n /** Whether the source accepted sync rows that are not yet visible. */\n public get hasHeldSyncTransaction(): boolean {\n return this.collection._hasHeldSyncTransaction()\n }\n\n public get pendingTruncateReplacement(): Promise<void> | undefined {\n const completion = this.truncateReplayState?.completion\n return completion?.isPending() ? completion.promise : undefined\n }\n\n public get hasFailedTruncateReplacement(): boolean {\n const completion = this.truncateReplayState?.completion\n return (\n this.truncateReplacementPending &&\n completion !== undefined &&\n !completion.isPending()\n )\n }\n\n setOrderByIndex(index: IndexReader<any>) {\n this.orderByIndex = index\n }\n\n /**\n * Set subscription status and emit events if changed\n */\n private setStatus(newStatus: SubscriptionStatus) {\n if (this.unsubscribed) return\n if (this._status === newStatus) {\n return // No change\n }\n\n const previousStatus = this._status\n this._status = newStatus\n const revision = ++this.statusRevision\n\n // Emit status:change event\n this.emitInnerWhile(\n `status:change`,\n {\n type: `status:change`,\n subscription: this,\n previousStatus,\n status: newStatus,\n },\n () => this.statusRevision === revision,\n )\n\n // A listener may synchronously start or release demand. Do not follow that\n // newer transition with a stale specific event.\n if (this.statusRevision !== revision) return\n\n // Emit specific status event\n const eventKey: `status:${SubscriptionStatus}` = `status:${newStatus}`\n this.emitInnerWhile(\n eventKey,\n {\n type: eventKey,\n subscription: this,\n previousStatus,\n status: newStatus,\n } as SubscriptionEvents[typeof eventKey],\n () => this.statusRevision === revision,\n )\n }\n\n /** Observe an asynchronous subset load and restore status on settlement. */\n private observeLoadSubsetResult(\n syncResult: LoadSubsetRequestResult,\n demand: SubsetDemand,\n options: LoadSubsetOptions,\n trackStatus: boolean,\n shouldReportError: () => boolean = () => true,\n ): void {\n if (!(syncResult instanceof Promise)) return\n\n const syncRunGeneration = this.collection._sync.getSyncRunGeneration()\n const participant = { demand, promise: syncResult }\n\n if (trackStatus) {\n this.pendingLoadSubsetParticipants.add(participant)\n this.setStatus(`loadingSubset`)\n }\n\n const finish = () => {\n if (trackStatus) {\n this.pendingLoadSubsetParticipants.delete(participant)\n if (this.isSyncRunGenerationCurrent(syncRunGeneration)) {\n this.setReadyIfIdle()\n }\n }\n }\n // An abort ends the load: after the step that aborted it, it holds\n // readiness no more.\n if (trackStatus)\n onAbortBeforeSettled(options.signal, syncResult, () =>\n queueMicrotask(finish),\n )\n\n void syncResult.then(finish, (error: unknown) => {\n if (\n this.isSyncRunGenerationCurrent(syncRunGeneration) &&\n shouldReportError()\n ) {\n this.recordLoadSubsetError(\n options,\n this.normalizeLoadSubsetPromiseError(syncResult, error),\n )\n }\n finish()\n })\n }\n\n /** Give every logical observer of one transport rejection the same Error. */\n private normalizeLoadSubsetPromiseError(\n promise: Promise<unknown>,\n error: unknown,\n ): Error {\n const existing = this.loadSubsetPromiseErrors.get(promise)\n if (existing) return existing\n const normalized = normalizeError(error)\n this.loadSubsetPromiseErrors.set(promise, normalized)\n return normalized\n }\n\n private stopDemandStatusParticipants(demand: SubsetDemand): void {\n for (const participant of this.pendingLoadSubsetParticipants) {\n if (participant.demand === demand) {\n this.pendingLoadSubsetParticipants.delete(participant)\n }\n }\n this.setReadyIfIdle()\n }\n\n /** Create the record for a fresh, abortable acquisition attempt. */\n private createSubsetAcquisitionRecord(\n requestOptions: LoadSubsetOptions,\n detached = false,\n ): SubsetAcquisitionRecord {\n // Detached demand has no physical work. Eager sync never passes subset\n // options to an adapter. Neither needs an abortable acquisition yet.\n if (detached || this.collection.config.syncMode !== `on-demand`) {\n return {\n options: requestOptions,\n syncRunGeneration: this.collection._sync.getSyncRunGeneration(),\n }\n }\n const abortController = new AbortController()\n const requestSignal = requestOptions.signal\n let removeRequestAbortListener: (() => void) | undefined\n\n if (requestSignal?.aborted) {\n abortController.abort(requestSignal.reason)\n } else if (requestSignal) {\n const abort = () => abortController.abort(requestSignal.reason)\n requestSignal.addEventListener(`abort`, abort, { once: true })\n removeRequestAbortListener = () =>\n requestSignal.removeEventListener(`abort`, abort)\n }\n\n return {\n options: {\n ...requestOptions,\n signal: abortController.signal,\n },\n syncRunGeneration: this.collection._sync.getSyncRunGeneration(),\n abortController,\n removeRequestAbortListener,\n }\n }\n\n /**\n * Retire an acquisition before user code; failed cleanup is not retryable.\n * An `unloadSubset` that throws is an adapter bug: it is reported uncaught\n * and fails no load, replay, or caller.\n */\n private releaseAcquisition(acquisition: SubsetAcquisitionRecord): void {\n if (acquisition.releaseAttempted) return\n acquisition.releaseAttempted = true\n try {\n acquisition.abortController?.abort()\n if (this.isSyncRunGenerationCurrent(acquisition.syncRunGeneration)) {\n this.collection._sync.unloadSubset(acquisition.options)\n }\n } catch (error) {\n reportUncaught(error)\n } finally {\n acquisition.removeRequestAbortListener?.()\n }\n }\n\n /** Start and retain the first acquisition for one logical subset demand. */\n private startSubsetDemand(requestOptions: LoadSubsetOptions): {\n demand: SubsetDemand\n result: LoadSubsetRequestResult\n started: boolean\n } {\n // Law 9: a first demand joins the shared publication barrier when it\n // starts, even if this subscription held no demand at truncate. Waiting\n // until failure loses the hold when the sibling settles first.\n let joinedReplay: TruncateReplayState | undefined\n if (\n !this.truncateReplayState &&\n this.options.truncateReplayPublication?.siblingReplays()\n ) {\n joinedReplay = this.createTruncateReplayState(() => new Map())\n this.truncateReplayState = joinedReplay\n this.truncateReplacementPending = true\n }\n const replayState = this.truncateReplayState\n const replayAttempt = replayState?.currentAttempt\n try {\n const detached =\n this.collection.status === `cleaned-up` ||\n // A deferring subscription starts no acquisition attempt until it resumes.\n (this.defersAcquisition &&\n this.collection.config.syncMode === `on-demand`) ||\n // Ready/error callbacks can run before sync returns its loader. Idle\n // deferred starts still acquire through the sync manager's queue.\n (this.collection.config.syncMode === `on-demand` &&\n (isFailedStatus(this.collection.status) ||\n (this.collection.status !== `idle` &&\n this.collection._sync.syncLoadSubsetFn === null)))\n const acquisition = this.createSubsetAcquisitionRecord(\n requestOptions,\n detached,\n )\n const demand: SubsetDemand = {\n requestOptions,\n acquisition,\n acquisitionState: detached ? `detached` : `starting`,\n }\n // A demand that starts during an open replay joins it, parked or not (law\n // 9: a new demand joins the open replay).\n // Reentrant release must see the exact acquisition before adapter work\n // starts. A load that throws is a rejection: it keeps its owner.\n this.subsetDemands.push(demand)\n if (detached) {\n const initialResult = createDeferred<void>()\n demand.initialResult = initialResult\n const abort = () =>\n initialResult.reject(new LoadSubsetOperationAbortedError())\n requestOptions.signal?.addEventListener(`abort`, abort, { once: true })\n const finish = () => {\n requestOptions.signal?.removeEventListener(`abort`, abort)\n demand.initialResult = undefined\n }\n void initialResult.promise.then(finish, finish)\n if (replayState && replayAttempt)\n demand.parkedParticipant = this.trackTruncateReplayParticipant(\n replayState,\n replayAttempt,\n demand,\n initialResult.promise,\n requestOptions.signal,\n )\n return { demand, result: initialResult.promise, started: false }\n }\n const syncRunGeneration = acquisition.syncRunGeneration\n const result = this.collection._sync.loadSubset(acquisition.options)\n\n if (!this.isSyncRunGenerationCurrent(syncRunGeneration)) {\n const demandIndex = this.subsetDemands.indexOf(demand)\n if (demandIndex !== -1) this.subsetDemands.splice(demandIndex, 1)\n cancelAcquisition(acquisition)\n } else {\n demand.acquisitionState = `active`\n if (!this.subsetDemands.includes(demand)) {\n this.releaseAcquisition(acquisition)\n } else if (replayState && replayAttempt) {\n this.trackTruncateReplayParticipant(\n replayState,\n replayAttempt,\n demand,\n result,\n acquisition.options.signal,\n )\n }\n }\n return { demand, result, started: true }\n } finally {\n // Adapter and status callbacks can reenter before returning a promise.\n // Setup holds the replacement until that tentative work is registered.\n if (joinedReplay && replayAttempt) {\n this.startTruncateReplayAttempt(joinedReplay, replayAttempt, [])\n }\n }\n }\n\n /** Re-check ownership after adapter and event callbacks that may reenter. */\n private isDemandActive(demand: SubsetDemand): boolean {\n return !this.unsubscribed && this.subsetDemands.includes(demand)\n }\n\n private recordLoadSubsetError(\n options: LoadSubsetOptions,\n error: unknown,\n reportAborted = false,\n ): Error {\n const normalized = normalizeError(error)\n // Aborted subset requests are obsolete demand, not load failures. The\n // request may reject after its route has already been released.\n if (options.signal?.aborted && !reportAborted) return normalized\n\n this._lastError = normalized\n this.emitInner(`loadSubset:error`, {\n type: `loadSubset:error`,\n subscription: this,\n options,\n error: normalized,\n })\n return normalized\n }\n\n emitEvents(changes: Array<ChangeMessage<any, any>>): boolean {\n if (this.unsubscribed) return false\n const newChanges = this.filterAndFlipChanges(changes)\n\n // Reconciliation can reduce a source delta to no visible change. Do not\n // wake subscribers for an empty semantic batch.\n if (changes.length > 0 && newChanges.length === 0) return false\n\n // A direct subscriber sees the replacement as one batch, not a flash of\n // missing content. Delegated publication keeps its private D2 contributions.\n if (this.bufferPrivately(newChanges)) return false\n return this.filteredCallback(newChanges)\n }\n\n /** Keep direct snapshot reads private while an authoritative replay is open. */\n private publishSnapshot(changes: Array<ChangeMessage<any, any>>): void {\n if (!this.bufferPrivately(changes)) this.callback(changes)\n }\n\n /**\n * Sends the snapshot to the callback.\n * Returns a boolean indicating if it succeeded.\n * It can only fail if there is no index to fulfill the request\n * and the optimizedOnly option is set to true,\n * or, the entire state was already loaded or the request was cancelled.\n */\n requestSnapshot(opts?: RequestSnapshotOptions): boolean {\n // Cancel before acquiring ownership or publishing a local snapshot.\n if (this.unsubscribed || opts?.signal?.aborted) return false\n if (this.loadedInitialState) {\n // Subscription was deoptimized so we already sent the entire initial state\n return false\n }\n\n const stateOpts: RequestSnapshotOptions = {\n where: this.options.whereExpression,\n optimizedOnly: opts?.optimizedOnly ?? false,\n }\n\n if (opts) {\n if (`where` in opts) {\n const snapshotWhereExp = opts.where\n if (stateOpts.where) {\n // Combine the two where expressions\n const subWhereExp = stateOpts.where\n const combinedWhereExp = and(subWhereExp, snapshotWhereExp)\n stateOpts.where = combinedWhereExp\n } else {\n stateOpts.where = snapshotWhereExp\n }\n }\n // The ordered loader asks for a bounded prefix only when the source\n // holds every row and an index serves its single order term. Any other\n // prefix resends every matching row: an on-demand repair relies on them.\n if (opts.boundedPrefix) {\n stateOpts.orderBy = opts.orderBy\n stateOpts.limit = opts.limit\n }\n } else {\n // No options provided so it's loading the entire initial state\n this.loadedInitialState = true\n }\n\n // Request the sync layer to load more data\n // don't await it, we will load the data into the collection when it comes in\n const loadOptions: LoadSubsetOptions = {\n ...(opts?.refetch ? { refetch: true } : {}),\n where: stateOpts.where,\n signal: opts?.signal,\n subscription: this,\n // Include orderBy and limit if provided so sync layer can optimize the query\n orderBy: opts?.orderBy,\n // A local optimistic row can hide one source row from a bounded prefix.\n limit:\n opts?.limit === undefined\n ? undefined\n : opts.limit + this.collection._optimisticOverlaySize(),\n }\n // The loader can reenter releaseSnapshot before startSubsetDemand returns.\n if (opts?.where) this.requestedSubsetWhere.set(loadOptions, opts.where)\n\n const {\n demand,\n result: syncResult,\n started,\n } = this.startSubsetDemand(loadOptions)\n if (!this.isDemandActive(demand)) return false\n\n // Report the result synchronously, including a wait for an unavailable loader.\n opts?.onLoadSubsetResult?.(\n syncResult,\n demand.acquisition.options,\n (primaryFailure) => this.releaseDemand(demand, primaryFailure),\n )\n if (!this.isDemandActive(demand)) return false\n\n if (started) {\n this.observeLoadSubsetResult(\n syncResult,\n demand,\n demand.acquisition.options,\n opts?.trackLoadSubsetPromise ?? true,\n )\n }\n if (!this.isDemandActive(demand)) return false\n\n // Also load data immediately from the collection\n let snapshot: Array<ChangeMessage<any, any>> | void\n if (opts?.onUnoptimized) {\n snapshot = this.collection.currentStateAsChanges({\n ...stateOpts,\n optimizedOnly: true,\n })\n if (snapshot === undefined) {\n opts.onUnoptimized()\n // The callback can retire this demand before the fallback read.\n if (!this.isDemandActive(demand)) return false\n snapshot = this.collection.currentStateAsChanges({\n ...stateOpts,\n optimizedOnly: false,\n })\n }\n } else {\n snapshot = this.collection.currentStateAsChanges(stateOpts)\n }\n // Snapshot evaluation may call user code that retires this demand.\n if (!this.isDemandActive(demand)) return false\n\n if (snapshot === undefined) {\n // Couldn't load from indexes\n return false\n }\n\n // Skip known rows, except retained rows from an abandoned replay: a new\n // snapshot must reconcile those with the source, not suppress their update.\n const knownRows =\n this.truncateReplayState?.privateRows ?? this.publishedRows\n const filteredSnapshot = snapshot.filter(\n (change) =>\n (!this.isBufferingForTruncate &&\n this.stalePublishedRows.has(change.key)) ||\n (!this.sentKeys.has(change.key) && !knownRows.has(change.key)),\n )\n\n // Reserve the selected keys before publication. A truncate replay can keep\n // this snapshot private, so callback tracking cannot reserve it yet.\n for (const change of filteredSnapshot) {\n this.sentKeys.add(change.key)\n }\n\n this.snapshotSent = true\n this.publishSnapshot(\n this.isBufferingForTruncate\n ? filteredSnapshot\n : this.reconcileStalePublishedChanges(filteredSnapshot),\n )\n return true\n }\n\n /**\n * Release exact subset requests while keeping the subscription alive. The\n * releases are one demand change (law 9): an open replay is judged once,\n * after all of them.\n */\n releaseSnapshot(...wheres: Array<BasicExpression<boolean>>): void {\n const demands: Array<SubsetDemand> = []\n for (const where of wheres) {\n const demand = this.subsetDemands.find(\n (candidate) =>\n !demands.includes(candidate) && this.requestedWhere(candidate, where),\n )\n if (demand) demands.push(demand)\n }\n if (demands.length > 0) this.releaseDemands(demands)\n }\n\n /**\n * @internal The snapshot for `where` replaces those for `replaced` for\n * their owner, which releases them once it applies. Until then they keep\n * their older work in the replay.\n */\n replaceSnapshots(\n where: BasicExpression<boolean>,\n replaced: Array<BasicExpression<boolean>>,\n ): void {\n const replacement = this.subsetDemands.find((demand) =>\n this.requestedWhere(demand, where),\n )\n if (!replacement) return\n replacement.replaces = this.subsetDemands.filter((demand) =>\n replaced.some((other) => this.requestedWhere(demand, other)),\n )\n }\n\n private requestedWhere(\n demand: SubsetDemand,\n where: BasicExpression<boolean>,\n ): boolean {\n return (\n demand.requestOptions.where === where ||\n this.requestedSubsetWhere.get(demand.requestOptions) === where\n )\n }\n\n private releaseDemand(\n demand: SubsetDemand,\n primaryFailure?: { error: unknown },\n ): void {\n try {\n if (primaryFailure)\n this.recordLoadSubsetError(\n demand.acquisition.options,\n primaryFailure.error,\n true,\n )\n } finally {\n // The failed request remains the public error, even if cleanup also fails.\n if (this.subsetDemands.includes(demand)) this.releaseDemands([demand])\n }\n }\n\n /** Retire held demands as one step, then judge an open replay once. */\n private releaseDemands(demands: Array<SubsetDemand>): void {\n const replayState = this.truncateReplayState\n const releaseCallbacks: Array<() => void> = []\n for (const demand of demands) {\n const acquisition = demand.acquisition\n this.subsetDemands.splice(this.subsetDemands.indexOf(demand), 1)\n demand.initialResult?.reject(new LoadSubsetOperationAbortedError())\n releaseCallbacks.push(() => this.removeTruncateReplayParticipant(demand))\n // Adapter release is a supported reentrancy boundary. A demand started\n // from unload joins this replacement before completion.\n if (demand.acquisitionState === `active`)\n releaseCallbacks.push(() => this.releaseAcquisition(acquisition))\n }\n runAllCallbacks([\n ...releaseCallbacks,\n () => this.retireEmptyReplay(),\n () => {\n if (replayState) this.checkTruncateReplayComplete(replayState)\n },\n // Ready follows replacement publication, never the delete half of it.\n ...demands.map(\n (demand) => () => this.stopDemandStatusParticipants(demand),\n ),\n ])\n }\n\n /**\n * A replay with no remaining logical demand cannot establish more rows. One\n * that has not failed publishes the rows it holds, so the subscriber does\n * not keep values the source has replaced or deleted. A failed replay keeps\n * the last public snapshot until an authoritative replay succeeds.\n */\n private retireEmptyReplay(): void {\n const replayState = this.truncateReplayState\n if (this.subsetDemands.length !== 0 || !replayState) return\n if (replayState.privateRows && !replayState.failed) {\n this.flushTruncateReplay(replayState)\n return\n }\n if (this.awaitsSiblingReplays(replayState, () => this.retireEmptyReplay()))\n return\n this.discardTruncateReplay()\n this.stalePublishedRows = new Map(this.publishedRows)\n this.restorePublishedSnapshotTracking()\n this.options.truncateReplayPublication?.succeed()\n }\n\n /** Read source-derived ordered rows without starting demand. */\n readOrderedSnapshot(\n options: LoadSubsetOptions,\n ): Array<ChangeMessage<Record<string, unknown>, string | number>> {\n const predicates = [\n this.options.whereExpression,\n options.where,\n options.cursor?.whereFrom,\n ].filter((where) => where !== undefined)\n const snapshot = this.collection.currentStateAsChanges({\n orderBy: options.orderBy,\n limit: options.limit,\n where:\n predicates.length > 0\n ? predicates.reduce((left, right) => and(left, right))\n : undefined,\n })\n // Optimistic rows can fill the visible window but cannot establish a\n // provider offset or cursor boundary. Excluding their keys is conservative\n // when an optimistic update hides a source row in the local ordered view.\n return Array.isArray(snapshot)\n ? snapshot.filter(\n ({ key }) => !this.collection._hasOptimisticOverlay(key),\n )\n : []\n }\n\n /**\n * Sends a snapshot that fulfills the `where` clause and all rows are bigger or equal to the cursor.\n * Requires a range index to be set with `setOrderByIndex` prior to calling this method.\n * It uses that range index to load the items in the order of the index.\n *\n * Cursor requests use one minValue for the leading order term. For a\n * multi-column order, a separate equality request loads the complete\n * leading-value tie before local ordering applies the trailing terms.\n *\n * Note 1: it may load more rows than the provided LIMIT because it loads all values equal to the first cursor value + limit values greater.\n * This is needed to ensure that it does not accidentally skip duplicate values when the limit falls in the middle of some duplicated values.\n * Note 2: it does not send keys that have already been sent before.\n */\n requestLimitedSnapshot({\n refetch,\n orderBy,\n limit,\n minValues,\n offset,\n trackLoadSubsetPromise: shouldTrackLoadSubsetPromise = true,\n onLoadSubsetResult,\n }: RequestLimitedSnapshotOptions) {\n if (this.unsubscribed) return\n if (!limit)\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `limit is required`\n : codedMessage(96),\n )\n\n if (!this.orderByIndex) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.`\n : codedMessage(97),\n )\n }\n\n // Validate cursor input before local delivery changes sent keys or calls user code.\n const whereFromCursor = minValues\n ? buildCursor(orderBy, minValues)\n : undefined\n\n // Check if minValues has a first element (regardless of its value)\n // This distinguishes between \"no min value provided\" vs \"min value is undefined\"\n const hasMinValue = minValues !== undefined && minValues.length > 0\n // Derive first column value from minValues (used for local index operations)\n const minValue = minValues?.[0]\n // Cast for index operations (index expects string | number)\n const minValueForIndex = minValue as string | number | undefined\n\n const index = this.orderByIndex\n const where = this.options.whereExpression\n const whereFilterFn = where\n ? createFilterFunctionFromExpression(where)\n : undefined\n\n const filterFn = (key: string | number | undefined): boolean => {\n if (key !== undefined && this.sentKeys.has(key)) {\n return false\n }\n\n const value = this.collection.get(key)\n if (value === undefined) {\n return false\n }\n\n return whereFilterFn?.(value) ?? true\n }\n\n let biggestObservedValue = minValueForIndex\n const changes: Array<ChangeMessage<any, string | number>> = []\n\n // If we have a minValue we need to handle the case\n // where there might be duplicate values equal to minValue that we need to include\n // because we can have data like this: [1, 2, 3, 3, 3, 4, 5]\n // so if minValue is 3 then the previous snapshot may not have included all 3s\n // e.g. if it was offset 0 and limit 3 it would only have loaded the first 3\n // so we load all rows equal to minValue first, to be sure we don't skip any duplicate values\n let keys: Array<string | number> = []\n if (hasMinValue) {\n // First, get all items with the same FIRST COLUMN value as minValue\n // This provides wide bounds for the local index\n const { expression } = orderBy[0]!\n const allRowsWithMinValue = this.collection.currentStateAsChanges({\n where: eq(expression, new Value(minValueForIndex)),\n })\n\n if (allRowsWithMinValue) {\n const keysWithMinValue = allRowsWithMinValue\n .map((change) => change.key)\n .filter(filterFn)\n\n // Add items with the minValue first\n keys.push(...keysWithMinValue)\n\n // Then get items greater than minValue\n const keysGreaterThanMin = index.take(\n limit - keys.length,\n minValueForIndex!,\n filterFn,\n )\n keys.push(...keysGreaterThanMin)\n } else {\n keys = index.take(limit, minValueForIndex!, filterFn)\n }\n } else {\n // No min value provided, start from the beginning\n keys = index.takeFromStart(limit, filterFn)\n }\n\n const valuesNeeded = () => Math.max(limit - changes.length, 0)\n const collectionExhausted = () => keys.length === 0\n\n // Create a value extractor for the orderBy field to properly track the biggest indexed value\n const orderByExpression = orderBy[0]!.expression\n const valueExtractor =\n orderByExpression.type === `ref`\n ? compileExpression(\n new PropRef(getPropRefPropertyPath(orderByExpression)),\n true,\n )\n : null\n\n while (valuesNeeded() > 0 && !collectionExhausted()) {\n for (const key of keys) {\n const value = this.collection.get(key)!\n changes.push({\n type: `insert`,\n key,\n value,\n })\n // Extract the indexed value (e.g., salary) from the row, not the full row\n // This is needed for index.take() to work correctly with the BTree comparator\n biggestObservedValue = valueExtractor ? valueExtractor(value) : value\n }\n\n keys = index.take(valuesNeeded(), biggestObservedValue!, filterFn)\n }\n\n // Reserve rows before publication. A direct truncate replay keeps them in\n // the private replacement, but repeated ordered snapshots must continue.\n for (const change of changes) {\n this.sentKeys.add(change.key)\n }\n\n this.publishSnapshot(changes)\n // A subscriber callback can synchronously tear down this subscription.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.unsubscribed) return\n\n // Build cursor expressions for sync layer loadSubset\n // The cursor expressions are separate from the main where clause\n // so the sync layer can choose cursor-based or offset-based pagination.\n // A local key is not an authoritative provider cursor: sparse source rows\n // and callback reentry can leave lower-ranked provider rows unseen.\n let cursorExpressions:\n | {\n whereFrom: BasicExpression<boolean>\n whereCurrent: BasicExpression<boolean>\n }\n | undefined\n\n if (whereFromCursor && minValues) {\n const whereCurrentCursor = buildCursorCurrent(orderBy, minValues)\n if (whereCurrentCursor) {\n cursorExpressions = {\n whereFrom: whereFromCursor,\n whereCurrent: whereCurrentCursor,\n }\n }\n }\n\n // A cursor value does not bound how many provider rows precede it. When an\n // adapter ignores cursor expressions and no offset was supplied, only a\n // full-source request can reach an arbitrary cursor value. Otherwise,\n // selected keys and optimistic overlays can each hide source rows from a\n // local page. Their cardinalities bound how many extra provider rows the\n // request may need to reach `limit` visible rows.\n const overlaySize = this.collection._optimisticOverlaySize()\n const providerLimit =\n offset !== undefined\n ? limit + overlaySize\n : hasMinValue\n ? undefined\n : limit + this.sentKeys.size + overlaySize\n\n // Request the sync layer to load more data\n // don't await it, we will load the data into the collection when it comes in\n // Note: `where` does NOT include cursor expressions - they are passed separately\n // The sync layer can choose to use cursor-based or offset-based pagination\n const loadOptions: LoadSubsetOptions = {\n ...(refetch ? { refetch: true } : {}),\n where, // Main filter only, no cursor\n limit: providerLimit,\n orderBy,\n cursor: cursorExpressions, // Cursor expressions passed separately\n offset: offset ?? 0,\n subscription: this,\n }\n\n const {\n demand,\n result: syncResult,\n started,\n } = this.startSubsetDemand(loadOptions)\n if (!this.isDemandActive(demand)) return\n\n // Report the result synchronously, including a wait for an unavailable loader.\n onLoadSubsetResult?.(\n syncResult,\n demand.acquisition.options,\n (primaryFailure) => this.releaseDemand(demand, primaryFailure),\n )\n if (!this.isDemandActive(demand)) return\n if (started) {\n this.observeLoadSubsetResult(\n syncResult,\n demand,\n demand.acquisition.options,\n shouldTrackLoadSubsetPromise,\n )\n }\n if (!this.isDemandActive(demand)) return\n }\n\n // TODO: also add similar test but that checks that it can also load it from the collection's loadSubset function\n // and that that also works properly (i.e. does not skip duplicate values)\n\n /**\n * Filters and flips changes for keys that have not been sent yet.\n * Deletes are filtered out for keys that have not been sent yet.\n * Updates are flipped into inserts for keys that have not been sent yet.\n * Duplicate inserts are filtered out to prevent D2 multiplicity > 1.\n */\n private filterAndFlipChanges(changes: Array<ChangeMessage<any, any>>) {\n changes = this.reconcileStalePublishedChanges(changes)\n\n if (this.loadedInitialState || this.skipFiltering) {\n // We loaded the entire initial state or filtering is explicitly skipped\n // so no need to filter or flip changes\n return changes\n }\n\n // A former full-state subscription is reset before truncate deletes arrive.\n // Pass even unreserved deletes into its private replacement so stale\n // published rows do not survive the replay.\n const skipDeleteFilter = this.isBufferingForTruncate\n\n // sentKeys covers snapshot selections and callback rows. Keys inserted\n // earlier in this batch are tracked locally, so a row the where clause\n // drops cannot advance pagination or later look like a duplicate insert.\n const insertedInBatch = new Set<string | number>()\n const newChanges = []\n for (const change of changes) {\n let newChange = change\n const keyInSentKeys =\n this.sentKeys.has(change.key) || insertedInBatch.has(change.key)\n\n if (!keyInSentKeys) {\n if (change.type === `update`) {\n newChange = { ...change, type: `insert`, previousValue: undefined }\n insertedInBatch.add(change.key)\n } else if (change.type === `delete`) {\n // Filter out deletes for keys that have not been sent,\n // UNLESS we're buffering for truncate (where all deletes should pass through)\n if (!skipDeleteFilter) {\n continue\n }\n } else {\n insertedInBatch.add(change.key)\n }\n } else {\n // Key was already sent - handle based on change type\n if (change.type === `insert`) {\n // Filter out duplicate inserts - the key was already inserted.\n // This prevents D2 multiplicity from going above 1, which would\n // cause deletes to not properly remove items (multiplicity would\n // go from 2 to 1 instead of 1 to 0).\n continue\n } else if (change.type === `delete`) {\n // Remove from sentKeys so future inserts for this key are allowed\n // (e.g., after truncate + reinsert)\n this.sentKeys.delete(change.key)\n insertedInBatch.delete(change.key)\n }\n }\n newChanges.push(newChange)\n }\n return newChanges\n }\n\n /**\n * After a failed replay, the source collection is empty but subscribers still\n * hold the last good publication. Reconcile the first later source delta for\n * each retained key against that publication instead of treating it as a\n * duplicate insert.\n */\n private reconcileStalePublishedChanges(\n changes: Array<ChangeMessage<any, any>>,\n ): Array<ChangeMessage<any, any>> {\n if (this.stalePublishedRows.size === 0) return changes\n\n const reconciled: Array<ChangeMessage<any, any>> = []\n for (const change of changes) {\n const previous = this.stalePublishedRows.get(change.key)\n if (previous === undefined) {\n reconciled.push(change)\n continue\n }\n\n this.stalePublishedRows.delete(change.key)\n if (change.type === `delete`) {\n reconciled.push({\n ...change,\n value: previous,\n previousValue: undefined,\n })\n } else if (\n this.truncateReplayState?.privateRows ||\n !sameRowValue(previous, change.value)\n ) {\n // An equal retained row still belongs in the private replacement.\n // Its final diff suppresses the redundant public update.\n reconciled.push({\n ...change,\n type: `update`,\n previousValue: previous,\n })\n }\n }\n // Cleanup discards rows without publishing deletes. Eager sources publish\n // their installed state; subset sources must first finish reacquisition.\n if (\n this.collection.config.syncMode !== `on-demand` &&\n !this.isBufferingForTruncate\n ) {\n for (const [key, value] of this.stalePublishedRows) {\n if (this.collection.has(key)) continue\n this.stalePublishedRows.delete(key)\n reconciled.push({ type: `delete`, key, value })\n }\n }\n return reconciled\n }\n\n /**\n * Mark that the subscription should not filter any changes.\n * This is used when includeInitialState is explicitly set to false,\n * meaning the caller doesn't want initial state but does want ALL future changes.\n */\n markAllStateAsSeen() {\n this.skipFiltering = true\n }\n\n unsubscribe() {\n if (this.unsubscribed) return\n this.unsubscribed = true\n // Stop any status listener set already being iterated. Clearing the\n // emitter's map cannot invalidate that captured Set by itself.\n this.statusRevision++\n const sourceListenerCleanups = this.sourceListenerCleanups\n this.sourceListenerCleanups = []\n\n runAllCallbacks([\n ...sourceListenerCleanups,\n () => {\n // Stop any buffered replay from publishing after unsubscription.\n this.discardTruncateReplay()\n this.stalePublishedRows.clear()\n\n // Retire every owner before an unload can reenter teardown.\n const acquisitions = this.subsetDemands\n .filter((demand) => demand.acquisitionState === `active`)\n .map((demand) => demand.acquisition)\n for (const demand of this.subsetDemands) {\n demand.initialResult?.reject(new LoadSubsetOperationAbortedError())\n this.stopDemandStatusParticipants(demand)\n if (demand.acquisitionState === `starting`) {\n cancelAcquisition(demand.acquisition)\n }\n }\n this.subsetDemands = []\n for (const acquisition of acquisitions) {\n this.releaseAcquisition(acquisition)\n }\n },\n () =>\n this.emitInner(`unsubscribed`, {\n type: `unsubscribed`,\n subscription: this,\n }),\n // Clear all event listeners to prevent memory leaks\n () => this.clearListeners(),\n ])\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiKA,SAAS,yBAAyC;C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