UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

1 lines • 47.4 kB
{"version":3,"file":"live-query-window-controller.cjs","names":["isCollection","codedMessage","BaseQueryBuilder","SetWindowRequiresOrderByError","isSingleResultCollection","deepEquals","createLiveQueryObserver","LiveQueryWindowControllerDisposedError","leases","leaseVersions","shouldCaptureBaseline","leaseVersion","retainedWindow","baselineWindow","applyDesiredWindow","rollbackLease","appliedLimit","restoreInitialWindow","getDesiredLimit","lease","activeFetchPromise","windowGeneration","leaseActive","leaseGeneration","inFlightLeaseHolders","restoreInitialWindowOnRelease","publicationQueue","dispatching","blockDelivery","transitionDepth","transitionNeedsNotify","observerUnsub","cachedSnapshot","cachedFrom","snapshotFrom","ensureLeaseActive","deactivateLease","requestPageCount","pendingWindowGeneration","acquireInFlightLease","releaseInFlightLease","beginTransition","activateLease","endTransition","hasBeenDisposed"],"sources":["../../src/live-query-window-controller.ts"],"sourcesContent":["import {\n LiveQueryWindowControllerDisposedError,\n SetWindowRequiresOrderByError,\n} from './errors.js'\nimport {\n isCollection,\n isSingleResultCollection,\n} from './live-query-primitives.js'\nimport { createLiveQueryObserver } from './live-query-observer.js'\nimport { BaseQueryBuilder } from './query/builder/index.js'\nimport { deepEquals } from './utils.js'\nimport { codedMessage, devBuild } from './error-message.js'\nimport type {\n LiveQueryObserver,\n LiveQuerySnapshot,\n} from './live-query-observer.js'\nimport type { DbClient } from './client.js'\nimport type { Collection } from './collection/index.js'\nimport type { CollectionStatus, HealthNode } from './types.js'\nimport type {\n Context,\n InitialQueryBuilder,\n QueryBuilder,\n} from './query/builder/index.js'\n\nconst DEFAULT_PAGE_SIZE = 20\n\nexport type LiveQueryWindowInputKind = `collection` | `query`\n\n/** @internal The supported, enabled input forms for infinite-query adapters. */\nexport type ResolvedLiveQueryWindowInput<TContext extends Context> =\n | { kind: `collection`; collection: Collection<any, any, any> }\n | { kind: `query`; query: QueryBuilder<TContext> }\n\n/**\n * Classify an infinite-query input without invoking its query callback.\n * Frameworks use this during lifecycle comparison so unchanged React renders\n * do not execute the callback again.\n *\n * @internal This contract is unstable while RFC #1623 is being implemented.\n */\nexport function getLiveQueryWindowInputKind(\n input: unknown,\n): LiveQueryWindowInputKind {\n if (isCollection(input)) return `collection`\n if (typeof input === `function`) return `query`\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `useLiveInfiniteQuery: First argument must be either a pre-created live query collection or a query function. ` +\n `Received: ${typeof input}`\n : codedMessage(103, { type: typeof input }),\n )\n}\n\n/**\n * Resolve a supported infinite-query input and invoke a query callback once.\n * A function may resolve to a collection for framework getter compatibility.\n * Nullable/disabled and config-object inputs are intentionally not supported.\n *\n * @internal This contract is unstable while RFC #1623 is being implemented.\n */\nexport function resolveLiveQueryWindowInput<TContext extends Context>(\n input: unknown,\n): ResolvedLiveQueryWindowInput<TContext> {\n if (getLiveQueryWindowInputKind(input) === `collection`) {\n return {\n kind: `collection`,\n collection: input as Collection<any, any, any>,\n }\n }\n\n const value = (\n input as (q: InitialQueryBuilder) => QueryBuilder<TContext> | unknown\n )(new BaseQueryBuilder() as InitialQueryBuilder)\n if (isCollection(value)) {\n return { kind: `collection`, collection: value }\n }\n if (\n typeof value !== `object` ||\n value === null ||\n typeof (value as { limit?: unknown }).limit !== `function` ||\n typeof (value as { offset?: unknown }).offset !== `function`\n ) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `useLiveInfiniteQuery: Query function must return a query builder. ` +\n `Disabled null or undefined queries are not supported.`\n : codedMessage(104),\n )\n }\n return { kind: `query`, query: value as QueryBuilder<TContext> }\n}\n\n/**\n * Whether a window collection may start from its current window. An adapter\n * may then start the collection, or reuse one it started, during render, as\n * useLiveQuery does. That holds for exactly the requested rows from offset 0,\n * whose first published rows are already correct. It also holds for an\n * unbounded window, which the controller cannot narrow before its source\n * request anyway. Any other window waits for the controller to adjust it when\n * the subscription commits: a shifted or narrower window would publish the\n * wrong rows first, and a wider finite one would request rows from an\n * on-demand source that the hook does not need.\n *\n * @internal This contract is unstable while RFC #1623 is being implemented.\n */\nexport function liveQueryWindowMatches(\n collection: Collection<any, any, any>,\n requiredLimit: number,\n): boolean {\n const window = (collection as WindowTarget).utils?.getWindow?.()\n return (\n window !== undefined &&\n window.offset === 0 &&\n (window.limit === requiredLimit || window.limit === Infinity)\n )\n}\n\n/** @internal This contract is unstable while RFC #1623 is being implemented. */\nexport function normalizeLiveQueryWindowPageSize(\n pageSize: number | undefined,\n): number {\n if (\n pageSize === undefined ||\n !Number.isSafeInteger(pageSize) ||\n pageSize <= 0 ||\n pageSize >= Number.MAX_SAFE_INTEGER\n ) {\n return DEFAULT_PAGE_SIZE\n }\n return pageSize\n}\n\ntype WindowResult = true | Promise<void>\n\ntype LiveQueryWindow = { offset: number; limit: number }\n\n/** @internal Shared adapter view of a collection with an ordered window. */\nexport type LiveQueryWindowCollection = Collection<any, any, any> & {\n utils: {\n setWindow: (options: LiveQueryWindow) => WindowResult\n getWindow: () => LiveQueryWindow | undefined\n }\n}\n\ntype WindowTarget = object & {\n utils?: {\n setWindow?: (options: { offset: number; limit: number }) => WindowResult\n getWindow?: () => { offset: number; limit: number } | undefined\n }\n}\n\ntype PendingWindow = {\n generation: number\n limit: number\n promise: Promise<void>\n}\n\nclass WindowCoordinator {\n private readonly leases = new Map<symbol, number>()\n private readonly leaseVersions = new Map<symbol, number>()\n private baselineWindow: { offset: number; limit: number } | undefined\n private retainedWindow: { offset: number; limit: number } | undefined\n private shouldCaptureBaseline = true\n private appliedLimit: number | undefined\n private pending: PendingWindow | undefined\n private generation = 0\n private leaseVersion = 0\n\n constructor(private readonly target: WindowTarget) {}\n\n request(lease: symbol, limit: number): WindowResult {\n if (this.leases.size === 0) {\n const currentWindow = this.target.utils?.getWindow?.()\n const retainedWindowChanged =\n this.retainedWindow !== undefined &&\n (currentWindow?.offset !== this.retainedWindow.offset ||\n currentWindow.limit !== this.retainedWindow.limit)\n if (this.shouldCaptureBaseline || retainedWindowChanged) {\n this.baselineWindow = currentWindow\n this.shouldCaptureBaseline = false\n }\n this.retainedWindow = undefined\n }\n const previousLimit = this.leases.get(lease)\n const previousVersion = this.leaseVersions.get(lease)\n const version = ++this.leaseVersion\n this.leases.set(lease, limit)\n this.leaseVersions.set(lease, version)\n\n let result: WindowResult\n try {\n result = this.applyDesiredWindow()\n } catch (error) {\n this.rollbackLease(lease, version, previousLimit, previousVersion)\n this.appliedLimit = undefined\n if (this.leases.size === 0) this.shouldCaptureBaseline = true\n throw error\n }\n\n if (result === true) return true\n return result.catch(async (error: unknown) => {\n if (this.rollbackLease(lease, version, previousLimit, previousVersion)) {\n this.generation++\n this.pending = undefined\n this.appliedLimit = undefined\n try {\n if (this.leases.size === 0) {\n this.restoreInitialWindow()\n } else {\n const rollback = this.applyDesiredWindow()\n if (rollback !== true) await rollback\n }\n } catch {\n // Preserve the failure from the requested window.\n }\n }\n throw error\n })\n }\n\n getLeaseResult(lease: symbol, minimumLimit: number): WindowResult | false {\n const limit = this.leases.get(lease)\n if (limit === undefined || limit < minimumLimit) return false\n const desiredLimit = this.getDesiredLimit()\n // getWindow reports settled state; the current lease may still be loading.\n if (this.pending && this.pending.limit === desiredLimit)\n return this.pending.promise\n const currentWindow = this.target.utils?.getWindow?.()\n return (\n currentWindow === undefined ||\n (currentWindow.offset === 0 && currentWindow.limit === desiredLimit)\n )\n }\n\n hasLeases(): boolean {\n return this.leases.size > 0\n }\n\n release(lease: symbol, restoreWhenEmpty: boolean): void {\n if (!this.leases.delete(lease)) return\n this.leaseVersions.delete(lease)\n\n // A pending request may still mutate the physical operator, but it no longer\n // establishes the accepted window for the remaining lease set.\n this.generation++\n this.pending = undefined\n this.appliedLimit = undefined\n\n if (this.leases.size === 0) {\n if (restoreWhenEmpty) {\n this.restoreInitialWindow()\n } else {\n this.retainedWindow = this.target.utils?.getWindow?.()\n }\n return\n }\n\n try {\n const result = this.applyDesiredWindow()\n if (result !== true) {\n void result.catch(() => {\n // Unsubscribe has no async error channel. Leave the physical window\n // unaccepted so the next request retries it.\n this.appliedLimit = undefined\n })\n }\n } catch {\n // The remaining controller will retry on its next request.\n this.appliedLimit = undefined\n }\n }\n\n private getDesiredLimit(): number | undefined {\n let desired: number | undefined\n for (const limit of this.leases.values()) {\n desired = desired === undefined ? limit : Math.max(desired, limit)\n }\n return desired\n }\n\n private rollbackLease(\n lease: symbol,\n version: number,\n previousLimit: number | undefined,\n previousVersion: number | undefined,\n ): boolean {\n if (this.leaseVersions.get(lease) !== version) return false\n if (previousLimit === undefined) {\n this.leases.delete(lease)\n this.leaseVersions.delete(lease)\n } else {\n this.leases.set(lease, previousLimit)\n if (previousVersion === undefined) {\n this.leaseVersions.delete(lease)\n } else {\n this.leaseVersions.set(lease, previousVersion)\n }\n }\n return true\n }\n\n private restoreInitialWindow(): void {\n const setWindow = this.target.utils?.setWindow\n const baselineWindow = this.baselineWindow\n this.retainedWindow = undefined\n this.shouldCaptureBaseline = false\n if (!baselineWindow || typeof setWindow !== `function`) {\n this.shouldCaptureBaseline = true\n return\n }\n const generation = this.generation\n const markRestored = () => {\n if (generation === this.generation && this.leases.size === 0) {\n this.shouldCaptureBaseline = true\n }\n }\n try {\n const result = setWindow.call(this.target.utils, baselineWindow)\n if (result === true) {\n markRestored()\n } else {\n void result.then(markRestored, () => {\n // Keep the original baseline so a later release can retry it.\n })\n }\n } catch {\n // Release has no error channel. Keep the baseline for a later retry.\n }\n }\n\n private applyDesiredWindow(): WindowResult {\n const limit = this.getDesiredLimit()\n if (limit === undefined) return true\n if (this.pending?.limit === limit) return this.pending.promise\n if (this.pending) {\n // `setWindow` mutates the physical operator before its load promise\n // settles. A different desired window must therefore be applied again,\n // even when it matches the last settled limit.\n this.generation++\n this.pending = undefined\n this.appliedLimit = undefined\n }\n const currentWindow = this.target.utils?.getWindow?.()\n if (\n limit === this.appliedLimit &&\n currentWindow?.offset === 0 &&\n currentWindow.limit === limit\n ) {\n return true\n }\n\n const setWindow = this.target.utils?.setWindow\n if (typeof setWindow !== `function`) {\n throw new SetWindowRequiresOrderByError()\n }\n\n const generation = ++this.generation\n const result = setWindow.call(this.target.utils, { offset: 0, limit })\n if (result === true) {\n if (generation === this.generation && this.getDesiredLimit() === limit) {\n this.appliedLimit = limit\n }\n return true\n }\n\n const promise = result.then(\n () => {\n if (\n generation === this.generation &&\n this.getDesiredLimit() === limit\n ) {\n this.appliedLimit = limit\n }\n if (this.pending?.generation === generation) {\n this.pending = undefined\n }\n },\n (error: unknown) => {\n if (this.pending?.generation === generation) {\n this.pending = undefined\n }\n throw error\n },\n )\n this.pending = { generation, limit, promise }\n return promise\n }\n}\n\nconst windowCoordinators = new WeakMap<object, WindowCoordinator>()\n\nfunction getWindowCoordinator(target: WindowTarget): WindowCoordinator {\n let coordinator = windowCoordinators.get(target)\n if (!coordinator) {\n coordinator = new WindowCoordinator(target)\n windowCoordinators.set(target, coordinator)\n }\n return coordinator\n}\n\n/** @internal Whether an infinite-query controller currently owns this window. */\nexport function hasLiveQueryWindowLeases(target: object): boolean {\n return windowCoordinators.get(target)?.hasLeases() ?? false\n}\n\n/** @internal Shared validation for infinite-query adapters. */\nexport function assertLiveQueryWindowManyResult(\n collection: Collection<any, any, any>,\n): void {\n if (isSingleResultCollection(collection)) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `useLiveInfiniteQuery: Infinite queries do not support single-result queries. Remove .findOne().`\n : codedMessage(105),\n )\n }\n}\n\n/** @internal Whether a collection exposes an active ordered window. */\nexport function isLiveQueryWindowCollection(\n collection: Collection<any, any, any>,\n): collection is LiveQueryWindowCollection {\n return (\n typeof collection.utils?.setWindow === `function` &&\n collection.utils.getWindow?.() !== undefined\n )\n}\n\n/**\n * Validate a pre-created infinite-query collection and describe any window\n * adjustment the adapter should warn about.\n *\n * @internal Shared validation for infinite-query adapters.\n */\nexport function getLiveQueryWindowCollectionWarning(\n collection: Collection<any, any, any>,\n expectedLimit: number,\n): string | undefined {\n assertLiveQueryWindowManyResult(collection)\n if (!isLiveQueryWindowCollection(collection)) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `useLiveInfiniteQuery: Pre-created live query collection must have an ORDER BY (orderBy) clause for infinite pagination to work. ` +\n `Please add .orderBy() to your createLiveQueryCollection query.`\n : codedMessage(106),\n )\n }\n\n const currentWindow = collection.utils.getWindow()\n if (\n !currentWindow ||\n hasLiveQueryWindowLeases(collection) ||\n (currentWindow.offset === 0 && currentWindow.limit === expectedLimit)\n ) {\n return undefined\n }\n\n // A developer hint: production adapters get no warning to print.\n if (!(devBuild() && process.env.NODE_ENV !== `production`)) return undefined\n return (\n `useLiveInfiniteQuery: Pre-created collection has window {offset: ${currentWindow.offset}, limit: ${currentWindow.limit}} ` +\n `but the hook expects {offset: 0, limit: ${expectedLimit}}. Adjusting window now.`\n )\n}\n\n/** @internal Compare adapter dependencies by identity and structure. */\nexport function compareLiveQueryWindowDependencies(\n previous: ReadonlyArray<unknown> | null | undefined,\n current: ReadonlyArray<unknown>,\n): { changed: boolean; structurallyEqual: boolean } {\n const changed =\n previous === null ||\n previous === undefined ||\n previous.length !== current.length ||\n previous.some((dependency, index) => dependency !== current[index])\n return {\n changed,\n structurallyEqual:\n previous !== null &&\n previous !== undefined &&\n deepEquals(previous, current),\n }\n}\n\n/** @internal Shared page-depth preservation policy for framework adapters. */\nexport function shouldPreserveLiveQueryWindowPageCount(options: {\n hasPreviousController: boolean\n previousInputKind: `collection` | `query` | undefined\n inputKind: `collection` | `query`\n sameCollection: boolean\n dependenciesChanged: boolean\n dependenciesStructurallyEqual: boolean\n pageShapeChanged: boolean\n}): boolean {\n if (\n !options.hasPreviousController ||\n options.previousInputKind !== options.inputKind\n ) {\n return false\n }\n if (options.inputKind === `collection`) return options.sameCollection\n return options.dependenciesChanged\n ? options.dependenciesStructurallyEqual\n : options.pageShapeChanged\n}\n\n/**\n * A page-windowed view of a live query at a point in time.\n *\n * @internal This contract is unstable while RFC #1623 is being implemented.\n */\nexport interface LiveQueryWindowSnapshot<\n T extends object,\n TKey extends string | number,\n> {\n /** Rows across all committed pages, with the peek-ahead row removed. */\n data: ReadonlyArray<T>\n /** Rows grouped into committed pages of `pageSize`. */\n pages: ReadonlyArray<ReadonlyArray<T>>\n /** `initialPageParam + i` for each committed page. */\n pageParams: ReadonlyArray<number>\n hasNextPage: boolean\n isFetchingNextPage: boolean\n /** Keyed results for the physical window, or `undefined` when disabled. */\n state: ReadonlyMap<TKey, T> | undefined\n collection: Collection<T, TKey, any> | undefined\n status: CollectionStatus | `disabled`\n isLoading: boolean\n isReady: boolean\n isIdle: boolean\n isLoadingError: boolean\n isCrashed: boolean\n isCleanedUp: boolean\n isEnabled: boolean\n /** The data is shown, and a sync problem or failed page load is in `health`. */\n isSyncError: boolean\n /** The health tree for the collection and its dependencies, or `undefined` when disabled. */\n health: HealthNode | undefined\n}\n\n/** @internal This contract is unstable while RFC #1623 is being implemented. */\nexport interface CreateLiveQueryWindowControllerOptions {\n client?: DbClient\n queryHash?: string\n /** Rows per page (default 20). Invalid values use the default. */\n pageSize?: number\n /** Value of the first page's `pageParam` (default 0). */\n initialPageParam?: number\n /** Committed pages to preserve when a framework binding changes page shape. */\n initialPageCount?: number\n}\n\n/** @internal This contract is unstable while RFC #1623 is being implemented. */\nexport interface LiveQueryWindowController<\n T extends object,\n TKey extends string | number,\n> {\n getSnapshot: () => LiveQueryWindowSnapshot<T, TKey>\n getServerSnapshot: () => LiveQueryWindowSnapshot<T, TKey>\n subscribe: (listener: () => void) => () => void\n /** Load one more page, resolving only after that page is committed. */\n fetchNextPage: () => Promise<void>\n /** Reset to the first page, resolving after the smaller window is accepted. */\n reset: () => Promise<void>\n preload: () => Promise<void>\n dispose: () => void\n}\n\n/**\n * Run an adapter-facing page fetch. The controller records failures in its\n * snapshot; consuming the rejection here keeps event handlers safe while the\n * returned promise still settles with the request.\n *\n * @internal This contract is unstable while RFC #1623 is being implemented.\n */\nexport function fetchNextLiveQueryWindowPage(\n controller: Pick<\n LiveQueryWindowController<object, string | number>,\n `fetchNextPage`\n >,\n): Promise<void> {\n return controller.fetchNextPage().catch(() => {})\n}\n\ninterface CachedFrom {\n observerSnapshot: unknown\n committedPageCount: number\n isFetchingNextPage: boolean\n}\n\ninterface SubscriptionRecord {\n listener: () => void\n active: boolean\n}\n\ninterface Publication {\n targets: Array<SubscriptionRecord>\n}\n\nclass LiveQueryWindowControllerImpl<\n T extends object,\n TKey extends string | number,\n> implements LiveQueryWindowController<T, TKey> {\n private readonly observer: LiveQueryObserver<T, TKey>\n private readonly collection: Collection<T, TKey, any> | null\n private readonly coordinator: WindowCoordinator | null\n private readonly lease = Symbol(`liveQueryWindowLease`)\n private readonly pageSize: number\n private readonly initialPageParam: number\n\n private committedPageCount: number\n private isFetchingNextPage = false\n private activeFetchPromise: Promise<void> | null = null\n private windowGeneration = 0\n private pendingWindowGeneration: number | undefined\n private leaseActive = false\n private leaseGeneration = 0\n private inFlightLeaseHolders = 0\n private restoreInitialWindowOnRelease = false\n\n private readonly subscriptions = new Set<SubscriptionRecord>()\n private readonly publicationQueue: Array<Publication> = []\n private dispatching = false\n private blockDelivery = false\n private transitionDepth = 0\n private transitionNeedsNotify = false\n private observerUnsub: (() => void) | null = null\n private cachedSnapshot: LiveQueryWindowSnapshot<T, TKey> | null = null\n private cachedFrom: CachedFrom | null = null\n private disposed = false\n\n constructor(\n collection: Collection<T, TKey, any> | null,\n options: CreateLiveQueryWindowControllerOptions,\n ) {\n this.collection = collection\n this.coordinator = collection\n ? getWindowCoordinator(collection as unknown as WindowTarget)\n : null\n this.pageSize = normalizeLiveQueryWindowPageSize(options.pageSize)\n this.initialPageParam = options.initialPageParam ?? 0\n const initialPageCount = Math.floor(options.initialPageCount ?? 1)\n this.committedPageCount = Number.isFinite(initialPageCount)\n ? Math.max(1, initialPageCount)\n : 1\n // The controller listener carries no delta payload, so wholesale is the\n // only coherent observer contract and guarantees non-reentrant subscribe.\n this.observer = createLiveQueryObserver<T, TKey>(collection, {\n mode: `wholesale`,\n client: options.client,\n queryHash: options.queryHash,\n })\n }\n\n getSnapshot(): LiveQueryWindowSnapshot<T, TKey> {\n return this.snapshotFrom(this.observer.getSnapshot())\n }\n\n getServerSnapshot(): LiveQueryWindowSnapshot<T, TKey> {\n return this.snapshotFrom(this.observer.getServerSnapshot())\n }\n\n private snapshotFrom(\n observerSnapshot: LiveQuerySnapshot<T, TKey>,\n ): LiveQueryWindowSnapshot<T, TKey> {\n const cached = this.cachedSnapshot\n if (\n cached &&\n this.cachedFrom &&\n this.cachedFrom.observerSnapshot === observerSnapshot &&\n this.cachedFrom.committedPageCount === this.committedPageCount &&\n this.cachedFrom.isFetchingNextPage === this.isFetchingNextPage\n ) {\n return cached\n }\n\n const enabled = observerSnapshot.isEnabled\n const rows =\n enabled && Array.isArray(observerSnapshot.data)\n ? (observerSnapshot.data as ReadonlyArray<T>)\n : []\n const totalRequested = this.committedPageCount * this.pageSize\n const hasNextPage = enabled && rows.length > totalRequested\n\n const pageCount = enabled ? this.committedPageCount : 0\n const pages: Array<ReadonlyArray<T>> = []\n const pageParams: Array<number> = []\n for (let i = 0; i < pageCount; i++) {\n pages.push(rows.slice(i * this.pageSize, (i + 1) * this.pageSize))\n pageParams.push(this.initialPageParam + i)\n }\n\n this.cachedSnapshot = {\n data: rows.slice(0, totalRequested),\n pages,\n pageParams,\n hasNextPage,\n isFetchingNextPage: this.isFetchingNextPage,\n get state() {\n return observerSnapshot.state\n },\n collection: observerSnapshot.collection,\n status: observerSnapshot.status,\n isLoading: observerSnapshot.isLoading,\n isReady: observerSnapshot.isReady,\n isIdle: observerSnapshot.isIdle,\n isLoadingError: observerSnapshot.isLoadingError,\n isCrashed: observerSnapshot.isCrashed,\n isCleanedUp: observerSnapshot.isCleanedUp,\n isEnabled: observerSnapshot.isEnabled,\n isSyncError: observerSnapshot.isSyncError,\n health: observerSnapshot.health,\n }\n this.cachedFrom = {\n observerSnapshot,\n committedPageCount: this.committedPageCount,\n isFetchingNextPage: this.isFetchingNextPage,\n }\n return this.cachedSnapshot\n }\n\n subscribe(listener: () => void): () => void {\n if (this.disposed) throw new LiveQueryWindowControllerDisposedError()\n\n const record: SubscriptionRecord = { listener, active: true }\n this.subscriptions.add(record)\n if (this.subscriptions.size === 1) {\n this.restoreInitialWindowOnRelease = false\n this.blockDelivery = true\n let observerUnsub: (() => void) | null = null\n try {\n // Store the desired physical window before observer activation can\n // compile or restart the live-query pipeline.\n const windowResult = this.ensureLeaseActive(this.committedPageCount)\n observerUnsub = this.observer.subscribe(() => this.notify())\n this.observerUnsub = observerUnsub\n // A failed load is a request error in the health tree.\n if (windowResult !== true) void windowResult.catch(() => undefined)\n } catch (error) {\n observerUnsub?.()\n this.observerUnsub = null\n this.deactivateLease(true)\n record.active = false\n this.subscriptions.delete(record)\n throw error\n } finally {\n this.blockDelivery = false\n }\n }\n\n return () => {\n if (!record.active) return\n record.active = false\n this.subscriptions.delete(record)\n if (this.subscriptions.size === 0) {\n this.restoreInitialWindowOnRelease = true\n this.observerUnsub?.()\n this.observerUnsub = null\n if (this.inFlightLeaseHolders === 0) this.deactivateLease(true)\n }\n }\n }\n\n fetchNextPage(): Promise<void> {\n if (this.disposed) return Promise.resolve()\n if (this.activeFetchPromise) {\n return this.activeFetchPromise\n }\n const snapshot = this.getSnapshot()\n const awaitingInitialLoad = snapshot.isLoading || snapshot.isIdle\n if (!snapshot.hasNextPage && !awaitingInitialLoad) return Promise.resolve()\n\n let resolveFetch!: () => void\n let rejectFetch!: (error: unknown) => void\n const activeFetchPromise = new Promise<void>((resolve, reject) => {\n resolveFetch = resolve\n rejectFetch = reject\n })\n this.activeFetchPromise = activeFetchPromise\n\n let request: Promise<void>\n try {\n const generation = this.windowGeneration\n // An unpublished initial snapshot cannot establish that there is no next\n // page. Keep one fetch pending, then decide from the settled first page.\n request = awaitingInitialLoad\n ? this.preload().then(() => {\n if (\n this.disposed ||\n generation !== this.windowGeneration ||\n !this.getSnapshot().hasNextPage\n ) {\n return\n }\n return this.requestPageCount(this.committedPageCount + 1, true)\n })\n : this.requestPageCount(this.committedPageCount + 1, true)\n } catch (error) {\n this.activeFetchPromise = null\n rejectFetch(error)\n return activeFetchPromise\n }\n void request.then(\n () => {\n if (this.activeFetchPromise === activeFetchPromise) {\n this.activeFetchPromise = null\n }\n resolveFetch()\n },\n (error: unknown) => {\n if (this.activeFetchPromise === activeFetchPromise) {\n this.activeFetchPromise = null\n }\n rejectFetch(error)\n },\n )\n return activeFetchPromise\n }\n\n reset(): Promise<void> {\n if (this.disposed) return Promise.resolve()\n if (\n this.committedPageCount === 1 &&\n !this.isFetchingNextPage &&\n !this.activeFetchPromise &&\n this.pendingWindowGeneration === undefined\n ) {\n return Promise.resolve()\n }\n this.activeFetchPromise = null\n return this.requestPageCount(1, false)\n }\n\n async preload(): Promise<void> {\n if (this.disposed) throw new LiveQueryWindowControllerDisposedError()\n\n this.acquireInFlightLease()\n try {\n const result = this.ensureLeaseActive(this.committedPageCount)\n if (result !== true) await result\n await this.observer.preload()\n } finally {\n this.releaseInFlightLease()\n }\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.windowGeneration++\n this.pendingWindowGeneration = undefined\n this.observerUnsub?.()\n this.observerUnsub = null\n this.deactivateLease(true)\n this.observer.dispose()\n for (const record of this.subscriptions) record.active = false\n this.subscriptions.clear()\n this.publicationQueue.length = 0\n }\n\n private requestPageCount(\n requestedPageCount: number,\n fetchingNextPage: boolean,\n ): Promise<void> {\n const generation = ++this.windowGeneration\n this.pendingWindowGeneration = undefined\n this.acquireInFlightLease()\n\n this.beginTransition()\n this.isFetchingNextPage = fetchingNextPage\n if (fetchingNextPage) this.notify()\n\n let result: WindowResult\n try {\n result = this.activateLease(requestedPageCount)\n } catch (error) {\n this.isFetchingNextPage = false\n this.notify()\n this.endTransition()\n this.releaseInFlightLease()\n return Promise.reject(error)\n }\n\n if (result === true) {\n if (!this.disposed && generation === this.windowGeneration) {\n this.committedPageCount = requestedPageCount\n this.isFetchingNextPage = false\n this.notify()\n }\n this.endTransition()\n this.releaseInFlightLease()\n return Promise.resolve()\n }\n\n this.pendingWindowGeneration = generation\n this.endTransition()\n\n return result\n .then(\n () => {\n if (this.disposed || generation !== this.windowGeneration) return\n this.beginTransition()\n this.pendingWindowGeneration = undefined\n this.committedPageCount = requestedPageCount\n this.isFetchingNextPage = false\n this.notify()\n this.endTransition()\n },\n (error: unknown) => {\n if (!this.disposed && generation === this.windowGeneration) {\n this.beginTransition()\n this.pendingWindowGeneration = undefined\n this.isFetchingNextPage = false\n this.notify()\n this.endTransition()\n }\n throw error\n },\n )\n .finally(() => {\n this.releaseInFlightLease()\n })\n }\n\n private acquireInFlightLease(): void {\n this.inFlightLeaseHolders++\n }\n\n private releaseInFlightLease(): void {\n this.inFlightLeaseHolders--\n if (this.inFlightLeaseHolders === 0 && this.subscriptions.size === 0) {\n this.deactivateLease(this.restoreInitialWindowOnRelease)\n }\n }\n\n private activateLease(pageCount: number): WindowResult {\n this.leaseGeneration++\n if (!this.coordinator || !this.collection) return true\n this.leaseActive = true\n return this.coordinator.request(this.lease, pageCount * this.pageSize + 1)\n }\n\n private ensureLeaseActive(pageCount: number): WindowResult {\n const minimumLimit = pageCount * this.pageSize + 1\n if (this.leaseActive) {\n const result = this.coordinator?.getLeaseResult(this.lease, minimumLimit)\n if (result) return result\n }\n return this.activateLease(pageCount)\n }\n\n private deactivateLease(restoreWhenEmpty = false): void {\n if (!this.leaseActive || !this.coordinator) return\n this.leaseGeneration++\n this.leaseActive = false\n this.restoreInitialWindowOnRelease = false\n this.coordinator.release(this.lease, restoreWhenEmpty)\n }\n\n private beginTransition(): void {\n this.transitionDepth++\n }\n\n private endTransition(): void {\n this.transitionDepth--\n if (this.transitionDepth === 0 && this.transitionNeedsNotify) {\n this.transitionNeedsNotify = false\n this.publish()\n }\n }\n\n private notify(): void {\n if (this.transitionDepth > 0) {\n this.transitionNeedsNotify = true\n return\n }\n this.publish()\n }\n\n private publish(): void {\n if (this.disposed || this.blockDelivery || this.subscriptions.size === 0) {\n return\n }\n\n this.publicationQueue.push({ targets: [...this.subscriptions] })\n if (this.dispatching) return\n\n this.dispatching = true\n try {\n while (this.publicationQueue.length > 0) {\n const publication = this.publicationQueue.shift()!\n for (const record of publication.targets) {\n if (this.hasBeenDisposed()) return\n if (!record.active) continue\n record.listener()\n }\n }\n } finally {\n this.dispatching = false\n }\n }\n\n private hasBeenDisposed(): boolean {\n return this.disposed\n }\n}\n\n/**\n * Create an internal forward-window controller for an ordered live query.\n *\n * @internal This factory is unstable while RFC #1623 is being implemented.\n */\nexport function createLiveQueryWindowController<\n T extends object,\n TKey extends string | number,\n>(\n collection: Collection<T, TKey, any> | null | undefined,\n options: CreateLiveQueryWindowControllerOptions = {},\n): LiveQueryWindowController<T, TKey> {\n return new LiveQueryWindowControllerImpl<T, TKey>(collection ?? null, options)\n}\n"],"mappings":";;;;;;AAyBA,IAAM,oBAAoB;AAgB1B,SAAgB,4BACd,OAC0B;CAC1B,IAAIA,8BAAAA,aAAa,KAAK,GAAG,OAAO;CAChC,IAAI,OAAO,UAAU,YAAY,OAAO;CACxC,MAAM,IAAI,MACR,sCAAA,SAAS,KAAA,QAAA,IAAA,aAA8B,eACnC,0HACe,OAAO,UACtBC,sBAAAA,aAAa,KAAK,EAAE,MAAM,OAAO,MAAM,CAAC,CAC9C;AACF;AASA,SAAgB,4BACd,OACwC;CACxC,IAAI,4BAA4B,KAAK,MAAM,cACzC,OAAO;EACL,MAAM;EACN,YAAY;CACd;CAGF,MAAM,QACJ,MACA,IAAIC,cAAAA,iBAAiB,CAAwB;CAC/C,IAAIF,8BAAAA,aAAa,KAAK,GACpB,OAAO;EAAE,MAAM;EAAc,YAAY;CAAM;CAEjD,IACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA8B,UAAU,cAChD,OAAQ,MAA+B,WAAW,YAElD,MAAM,IAAI,MACR,sCAAA,SAAS,KAAA,QAAA,IAAA,aAA8B,eACnC,4HAEAC,sBAAAA,aAAa,GAAG,CACtB;CAEF,OAAO;EAAE,MAAM;EAAS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