UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

851 lines (850 loc) • 35 kB
const require_index = require("../compiler/index.cjs"); const require_validate_limit = require("../validate-limit.cjs"); const require_errors = require("../../errors.cjs"); const require_scheduler = require("../../scheduler.cjs"); const require_deferred = require("../../deferred.cjs"); const require_utils = require("../../utils.cjs"); const require_callbacks = require("../../utils/callbacks.cjs"); const require_error = require("../../utils/error.cjs"); const require_source_record = require("../../utils/source-record.cjs"); const require_error_message = require("../../error-message.cjs"); const require_ir = require("../ir.cjs"); const require_health_tree = require("../../collection/health-tree.cjs"); const require_live_query_primitives = require("../../live-query-primitives.cjs"); const require_public_key_reduction = require("./public-key-reduction.cjs"); const require_collection_subscriber = require("./collection-subscriber.cjs"); const require_collection_registry = require("./collection-registry.cjs"); const require_internal = require("./internal.cjs"); const require_graph_scheduler = require("./graph-scheduler.cjs"); const require_subset_demand_controller = require("./subset-demand-controller.cjs"); const require_utils$1 = require("./utils.cjs"); let _tanstack_db_ivm = require("@tanstack/db-ivm"); var liveQueryCollectionCounter = 0; var CollectionConfigBuilder = class { /** * Reload each source with an error anywhere in its tree, then this query if * its own node shows an error. A nested live query passes the reload down the * same way. A source's reload keeps this query's status until it commits. * A query that is not running starts once its sources reloaded, as any * Collection's reload starts one; `query` is the live-query Collection, * which a query that never started has not given this builder yet. */ async reload(query = this.liveQueryCollection) { if (query?.status === `crashed`) return query._sync.reload(); const failed = this.ai.map(({ collection }) => collection).filter((collection, index, all) => all.indexOf(collection) === index && require_health_tree.findProblems(collection.health).some((node) => node.error !== null)); const ended = query?.status === `idle` || query?.status === `cleaned-up`; await Promise.all(failed.map((collection) => collection.reload())); if (ended) return query.preload(); if (query?._lifecycle.problems.error || query?._lifecycle.reloading) await query._sync.reload(); } /** This live query as its sources' `subscribers` list it. */ dependent() { const collection = this.liveQueryCollection; if (!collection) return void 0; return this.g7 ??= { kind: `live-query`, collection, get active() { return collection.subscribers.length > 0; }, end: () => collection.cleanup({ dependents: true }) }; } /** * Whether this live-query Collection had a subscriber or a preload in its * current sync run. Until then it reads its source Collections without * starting provider work. */ hasSubscriberOrPreload() { return this.liveQueryCollection?._hasSubscriberOrPreload() ?? true; } constructor(config) { this.config = config; this.fz = /* @__PURE__ */ new WeakMap(); this.cN = /* @__PURE__ */ new WeakMap(); this.br = false; this.bq = 0; this.cv = false; this.al = false; this.bh = /* @__PURE__ */ new Set(); this.eY = /* @__PURE__ */ new Set(); this.subscriptions = require_source_record.createSourceRecord(); this.lazySourcesCallbacks = require_source_record.createSourceRecord(); this.lazySources = /* @__PURE__ */ new Set(); this.aQ = /* @__PURE__ */ new Map(); this.fp = 0; this.aG = /* @__PURE__ */ new Set(); this.ba = false; this.dq = false; this.syncRunGeneration = 0; this.windowOperationGeneration = 0; this.av = 0; this.optimizableOrderByCollections = require_source_record.createSourceRecord(); this.id = config.id || `live-query-${++liveQueryCollectionCounter}`; this.query = require_utils$1.buildQueryFromConfig({ query: config.query, requireObjectResult: true }); this.cV = this.query.orderBy?.length || this.query.singleResult ? { offset: this.query.offset ?? 0, limit: this.query.singleResult ? Math.min(this.query.limit ?? 1, 1) : this.query.limit ?? Infinity } : void 0; this.bD = this.cV; this.collections = require_utils$1.extractCollectionsFromQuery(this.query); this.ai = require_ir.collectCollectionSources(this.query); require_ir.collectSourceRefs(this.query, this.eY); if (this.query.orderBy && this.query.orderBy.length > 0) this.compare = createOrderByComparator(this.cN); this.queryCompareOptions = require_utils$1.extractCollectionFromSource(this.query).compareOptions; this.compareOptions = this.config.defaultStringCollation ?? this.queryCompareOptions; this.ef(); } /** Direct lexical source Collections, including joins, unions, and includes. */ getSourceCollections() { return this.ai.map(({ collection }) => collection); } /** * Recursively checks if a query or any of its subqueries contains joins */ hasJoins(query) { if (query.join && query.join.length > 0) return true; if (query.from.type === `queryRef`) { if (this.hasJoins(query.from.query)) return true; } else if (query.from.type === `unionFrom`) { for (const source of query.from.sources) if (source.type === `queryRef` && this.hasJoins(source.query)) return true; } else if (query.from.type === `unionAll`) { for (const branch of query.from.queries) if (this.hasJoins(branch)) return true; } return false; } getConfig() { const builder = this; return { id: this.id, getKey: this.config.getKey || ((item) => this.fz.get(item) ?? item.$key), sync: this.fE(), compare: this.compare, defaultStringCollation: this.compareOptions, gcTime: this.config.gcTime ?? 5e3, autoIndex: this.config.autoIndex, defaultIndexType: this.config.defaultIndexType, schema: this.config.schema, onInsert: this.config.onInsert, onUpdate: this.config.onUpdate, onDelete: this.config.onDelete, startSync: this.config.startSync, singleResult: this.query.singleResult, utils: { get lastSubsetError() { return builder.lastSubsetError; }, setWindow: this.setWindow.bind(this), getWindow: this.getWindow.bind(this), [require_internal.LIVE_QUERY_INTERNAL]: { getBuilder: () => this, hasCustomGetKey: !!this.config.getKey, hasJoins: this.hasJoins(this.query), hasDistinct: !!this.query.distinct } } }; } setWindow(options) { const windowFn = this.f$; if (!windowFn) throw new require_errors.SetWindowRequiresOrderByError(); if (this.query.singleResult) { if (!this.query.orderBy?.length && (options.offset ?? 0) !== 0) throw new require_errors.SetWindowRequiresOrderByError(); if ((options.limit ?? this.cV.limit) !== this.cV.limit) throw new require_errors.SetWindowFindOneLimitError(); } if (this.ag || this.br || Object.values(this.optimizableOrderByCollections).some((info) => info.isRequesting?.())) throw new require_errors.SetWindowReentrancyError(); require_validate_limit.validateLimit(options.limit); const baseWindow = this.a1 ?? this.bD ?? this.cV; const requestedWindow = { offset: options.offset ?? baseWindow?.offset, limit: options.limit ?? baseWindow?.limit }; const request = ++this.av; const sourceRecovery = this.eV(); if (sourceRecovery) { const syncRuns = this.syncRuns(); const resume = async () => { for (let recovery = sourceRecovery; recovery; recovery = this.eV()) try { await recovery; } catch (error) { if (!(error instanceof require_errors.LoadSubsetOperationAbortedError) || syncRuns !== this.syncRuns()) throw error; } if (request !== this.av) { await this.gE; return; } const settlement2 = this.setWindow(requestedWindow); this.gE = deferred; if (settlement2 !== true) await settlement2; }; const deferred = resume(); return this.gE = deferred; } if (this.eF()) return this.gE = Promise.reject(this.lastSubsetError ?? new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Source recovery failed` : require_error_message.codedMessage(147))); const windowOperationGeneration = ++this.windowOperationGeneration; const loadOperation = this.liveQueryCollection?._sync.beginLoadSubsetOperation(); for (const info of Object.values(this.optimizableOrderByCollections)) for (const sourceId of info.joinedFilterSourceIds ?? []) for (const plan of this.lazySourcesCallbacks[sourceId]?.plans ?? []) { const participant = this.aQ.get(plan.id)?.participant; if (participant?.isPending()) this.trackSubsetLoadOperationPromise(participant.promise); } const operation = { generation: windowOperationGeneration, failed: false }; this.ag = operation; this.dq = false; if (this.aG.size === 0) this.ba = false; try { this.a1 = requestedWindow; require_scheduler.withPublicationContext(() => { windowFn(requestedWindow); this.bx?.(); }); if (operation.failed) throw operation.error; } catch (error) { if (windowOperationGeneration === this.windowOperationGeneration) { this.dq = true; this.a1 = this.bD; } loadOperation?.cancel(); throw error; } finally { this.ag = void 0; } const settlement = loadOperation?.wait() ?? true; if (settlement === true) { this.bD = requestedWindow; this.gE = void 0; return true; } return this.gE = settlement.then(() => { if (windowOperationGeneration === this.windowOperationGeneration) this.bD = requestedWindow; return request === this.av ? void 0 : this.gE; }, (error) => { if (windowOperationGeneration === this.windowOperationGeneration) { this.dq = true; this.a1 = this.bD; } throw error; }); } getWindow() { const window = this.bD ?? this.cV; if (!this.f$ || !window) return; return { offset: window.offset ?? 0, limit: window.limit ?? 0 }; } isLazySource(sourceId) { return this.lazySources.has(sourceId); } beginDemand(planId, pending = false) { const generation = ++this.fp; const previous = this.aQ.get(planId); const participant = pending ? require_deferred.createDeferred() : void 0; if (participant) { participant.promise.catch(() => {}); this.trackSubsetLoadOperationPromise(participant.promise); } this.aQ.set(planId, { generation, settled: false, participant }); previous?.participant?.resolve(); return generation; } /** The source aliases of this query, in query order, for its health tree. */ healthSources() { return this.ai.map(({ sourceId, alias, collection }) => ({ id: sourceId, alias, collection, ...this.eY.has(sourceId) ? { kind: `include` } : {} })); } settleDemand(planId, generation) { const demand = this.aQ.get(planId); if (!demand || demand.generation !== generation || demand.settled) return; demand.settled = true; try { this.bx?.(); demand.participant?.resolve(); } catch (error) { demand.participant?.reject(error); throw error; } } hasPendingJoinedWork(joinedSourceId) { return require_subset_demand_controller.hasPendingJoinedWork(joinedSourceId, this.lazySourcesCallbacks, this.subscriptions, (planId) => this.aQ.get(planId)?.settled === false); } failDemand(subscription, collection, planId, generation, error) { const demand = this.aQ.get(planId); if (!demand || demand.generation !== generation) return; const normalized = this.recordSubsetError(error); demand.participant?.reject(normalized); if (this.liveQueryCollection?._lifecycle.status === `ready`) { demand.settled = true; if (this.ai.some((source) => source.collection === collection && this.subscriptions[source.sourceId]?.hasPendingTruncateReplacement)) subscription.failReplacement(normalized); this.bx?.(); return; } this.failQuery(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Subset demand '${planId}' failed: ${normalized.message}` : require_error_message.codedMessage(228, { planId, cause: normalized.message }), normalized); } recordSubsetError(error, fatalBeforeReady = false) { const normalized = require_error.normalizeError(error); this.lastSubsetError = normalized; if (this.ag) { this.ag.failed = true; this.ag.error = normalized; this.ba = true; } if (fatalBeforeReady) this.failQuery(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Initial subset load failed: ${normalized.message}` : require_error_message.codedMessage(229, { cause: normalized.message }), normalized); return normalized; } trackSubsetLoadPromise(promise) { this.liveQueryCollection._sync.trackLoadPromise(promise); } trackSubsetLoadOperationPromise(promise) { this.liveQueryCollection._sync.trackLoadSubsetOperationPromise(promise); } hasActiveWindowOperation() { return this.ag !== void 0; } getActiveWindowOperationGeneration() { return this.ag?.generation; } scheduleGraphRunIfSyncRunCurrent(syncRunGeneration) { if (syncRunGeneration !== this.syncRunGeneration || !this.currentSyncConfig || !this.currentSyncState) return; this.scheduleGraphRun(); } trackOrderedLoadPromise(promise, holdPublication = false) { if (!holdPublication && !this.ag && this.liveQueryCollection?._lifecycle.inFirstLoad !== true && this.aG.size === 0) return; const syncRunGeneration = this.syncRunGeneration; if (this.aG.size === 0) this.ba = false; this.aG.add(promise); const finish = (succeeded) => { if (syncRunGeneration !== this.syncRunGeneration || !this.aG.delete(promise)) return; if (!succeeded) this.ba = true; if (!this.ba && this.aG.size === 0) this.scheduleGraphRun(); }; promise.then(() => finish(true), () => finish(false)); } retireDemand(planId) { const demand = this.aQ.get(planId); this.aQ.delete(planId); demand?.participant?.resolve(); } /** A root load of an eager source failed. */ failRootLoad(sourceId, error) { this.reportFailedRequest(`root:${sourceId}`, [error]); } /** A later root load of the source succeeded. */ settleRootLoad(sourceId) { this.clearFailedRequest(`root:${sourceId}`); } /** A source's truncate replay loaded the query's demand again. */ settleReplayedRequests(sourceId) { this.settleRootLoad(sourceId); this.clearFailedRequest(`replay:${sourceId}`); } /** * A source's truncate replay could not load the query's data again: each * of its failures, in failure order. Before the first ready the earliest * fails the query. */ failReplay(sourceId, errors) { if (this.reportFailedRequest(`replay:${sourceId}`, errors)) return; this.failQuery(errors[0].message, errors[0]); } reportFailedRequest(key, errors) { const lifecycle = this.liveQueryCollection?._lifecycle; if (lifecycle?.status !== `ready`) return false; lifecycle.reportRequestError(key, errors); return true; } /** A request settled later, or the query no longer needs its data. */ clearFailedRequest(key) { this.liveQueryCollection?._lifecycle.clearRequestError(key); } /** This query's sync run and its sources' sync runs. */ syncRuns() { return [this.syncRunGeneration, ...this.ai.map(({ collection }) => collection._sync.getSyncRunGeneration())].join(); } /** Replays of other subscriptions to a source's collection that still load. */ siblingReplays(collection, sourceId) { const pending = this.ai.flatMap((source) => { const subscription = this.subscriptions[source.sourceId]; return source.sourceId !== sourceId && source.collection === collection && subscription?.hasTruncateReplayWork && subscription.pendingTruncateReplacement ? [subscription.pendingTruncateReplacement] : []; }); return pending.length > 0 ? Promise.allSettled(pending) : void 0; } hasPendingSourceRecovery() { return Object.values(this.subscriptions).some((subscription) => subscription.hasPendingTruncateReplacement); } eV() { const pending = Object.values(this.subscriptions).flatMap((subscription) => subscription.pendingTruncateReplacement ? [subscription.pendingTruncateReplacement] : []); return pending.length > 0 ? Promise.all(pending).then(() => void 0) : void 0; } eF() { return Object.values(this.subscriptions).some((subscription) => subscription.hasFailedTruncateReplacement); } getSyncRunGeneration() { return this.syncRunGeneration; } advanceGraphInputRevision() { this.bq++; } getGraphInputRevision() { return this.bq; } maybeRunGraph() { if (this.br) return; if (!this.currentSyncConfig || !this.currentSyncState) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `maybeRunGraph called without active sync run. This should not happen.` : require_error_message.codedMessage(148)); this.br = true; try { const syncRunGeneration = this.syncRunGeneration; const config = this.currentSyncConfig; const { begin, commit } = config; const syncState = this.currentSyncState; const isCurrentSyncRun = () => syncRunGeneration === this.syncRunGeneration && this.currentSyncConfig === config && this.currentSyncState === syncState; if (this.cv) return; if (syncState.subscribedToAllCollections) { let checkedLoaders = false; while (syncState.graph.pendingWork() || !checkedLoaders) { if (syncState.graph.pendingWork()) { try { syncState.graph.run(); } catch (error) { if (isCurrentSyncRun() && this.liveQueryCollection?._lifecycle.stoppedThisRun !== true) this.g0(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Live query graph failed` : require_error_message.codedMessage(212), error); throw error; } if (!isCurrentSyncRun()) return; } this.e_?.(); if (!isCurrentSyncRun()) return; checkedLoaders = true; } syncState.flushPendingChanges?.(); if (!isCurrentSyncRun()) return; if (syncState.messagesCount === 0 && !this.al) { begin(); commit(); } this.bS(config); } } finally { this.br = false; } } /** * Schedules a graph run with the transaction-scoped scheduler. * Ensures each builder runs at most once per transaction, with automatic dependency tracking * to run parent queries before child queries. Outside a transaction, runs immediately. * * Multiple calls during a transaction are coalesced into a single execution. * Dependencies are discovered from subscribed live queries. * * Uses the current sync run's config and syncState from instance properties. * * @param options - Optional scheduling configuration * @param options.contextId - Transaction ID to group work; defaults to active transaction */ scheduleGraphRun(options) { if (!this.currentSyncConfig || !this.currentSyncState) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `scheduleGraphRun called without active sync run. This should not happen.` : require_error_message.codedMessage(149)); const syncRunGeneration = this.syncRunGeneration; require_graph_scheduler.scheduleQueryGraphRun(this, this.bh, () => { if (syncRunGeneration === this.syncRunGeneration && this.currentSyncConfig && this.currentSyncState) this.maybeRunGraph(); }, options?.contextId); } fE() { return { rowUpdateMode: `full`, sync: this.fP.bind(this) }; } fP(config) { const syncRunGeneration = ++this.syncRunGeneration; this.liveQueryCollection = config.collection; this.al = config.collection._lifecycle.reloading; this.cv = false; this.lastSubsetError = void 0; this.currentSyncConfig = config; const syncState = { messagesCount: 0, subscribedToAllCollections: false, unsubscribeCallbacks: /* @__PURE__ */ new Set() }; let tornDown = false; const teardown = () => { if (tornDown) return; tornDown = true; if (this.syncRunGeneration === syncRunGeneration) this.syncRunGeneration++; try { require_callbacks.runAllCallbacks(syncState.unsubscribeCallbacks); } finally { syncState.unsubscribeCallbacks.clear(); this.fl(); } }; try { const fullSyncState = this.dC(config, syncState); this.currentSyncState = fullSyncState; const loadingSubsetUnsubscribe = config.collection.on(`loadingSubset:change`, (event) => { if (!event.isLoadingSubset) { this.bS(config); if (this.hasPendingSourceRecovery()) this.bx?.(); } }); syncState.unsubscribeCallbacks.add(loadingSubsetUnsubscribe); this.e_ = this.ev(config, fullSyncState); this.bx = () => this.scheduleGraphRun(); this.scheduleGraphRun(); } catch (error) { try { teardown(); } catch {} throw error; } return teardown; } fl() { this.windowOperationGeneration++; this.currentSyncConfig = void 0; this.currentSyncState = void 0; this.bx = void 0; this.e_ = void 0; const lifecycle = this.liveQueryCollection?._lifecycle; if (lifecycle?.reloading && !lifecycle.hasStartedCleanup()) this.a1 = this.bD; else { this.a1 = void 0; this.bD = this.cV; } this.cv = false; this.al = false; this.d3 = void 0; this.cY = void 0; this.dL = void 0; this.sourceWhereClausesCache = void 0; this.a2 = void 0; this.dg = void 0; this.ch = void 0; this.lazySources.clear(); for (const demand of this.aQ.values()) demand.participant?.reject(new require_errors.LoadSubsetOperationAbortedError()); this.aQ.clear(); this.aG.clear(); this.ba = false; this.dq = false; this.optimizableOrderByCollections = require_source_record.createSourceRecord(); this.lazySourcesCallbacks = require_source_record.createSourceRecord(); Object.keys(this.subscriptions).forEach((key) => delete this.subscriptions[key]); } /** * Compiles the query pipeline with all declared aliases. */ ef() { this.d3 = new _tanstack_db_ivm.D2(); const inputs = require_source_record.createSourceRecord(); for (const source of this.ai) inputs[source.sourceId] = this.d3.newInput(); this.cY = inputs; const compilation = require_index.compileCollectionQuery(this.query, this.cY, this.collections, this.subscriptions, this.lazySourcesCallbacks, this.lazySources, this.optimizableOrderByCollections, (windowFn) => { this.f$ = windowFn; if (this.a1) windowFn(this.a1); }); const includesRuntime = compilation.includes?.[0]?.runtime; const getKey = this.config.getKey; const materialized = includesRuntime ? includesRuntime.materializeCompilation(compilation, getKey) : getKey && this.hasJoins(this.query) ? require_public_key_reduction.reducePublicKeys(compilation, getKey) : { pipeline: compilation.pipeline, facades: void 0 }; this.dL = materialized.pipeline; this.sourceWhereClausesCache = compilation.sourceWhereClauses; this.a2 = `resolve` in materialized ? materialized.resolve : void 0; this.dg = materialized.facades; this.ch = includesRuntime; const missingSources = this.ai.map((source) => source.sourceId).filter((sourceId) => !Object.hasOwn(this.cY, sourceId)); if (missingSources.length > 0) throw new require_errors.MissingAliasInputsError(missingSources); } eA() { if (!this.d3 || !this.cY || !this.dL) this.ef(); return { graph: this.d3, inputs: this.cY, pipeline: this.dL }; } dC(config, syncState) { const { begin, commit } = config; const { graph, inputs, pipeline } = this.eA(); let pendingChanges = /* @__PURE__ */ new Map(); pipeline.pipe((0, _tanstack_db_ivm.output)((data) => { const messages = data.getInner(); syncState.messagesCount += messages.length; messages.reduce(accumulateChanges, pendingChanges); })); const facadeCompilations = this.dg; const includesRuntime = this.ch; const bucketFacades = facadeCompilations && includesRuntime ? includesRuntime.createBucketFacades(this.id, facadeCompilations, (count) => { syncState.messagesCount += count; }, this.a2) : void 0; if (bucketFacades) syncState.unsubscribeCallbacks.add(() => bucketFacades.cleanup()); syncState.flushPendingChanges = () => { const hasParentChanges = pendingChanges.size > 0; const hasChildChanges = bucketFacades?.hasPendingChanges() ?? false; const snapshot = this.al; if (snapshot && !this.e8()) return; const writesRoot = hasParentChanges || snapshot; if (!writesRoot && !hasChildChanges) return; if (this.dq || this.ba || this.hasPendingSourceRecovery() || this.aG.size > 0 || Object.values(this.optimizableOrderByCollections).some((info) => info.joinedFilterSourceIds?.some((sourceId) => this.hasPendingJoinedWork(sourceId)))) return; for (const [key, { inserts, deletes }] of pendingChanges) if (Math.abs(inserts - deletes) > 1) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Live query result key ${String(key)} changed by ${inserts - deletes} rows in one flush; a key has at most one result row.` : require_error_message.codedMessage(150, { key, change: inserts - deletes })); let facadePublication; let rootPublication; try { facadePublication = bucketFacades?.flush(); rootPublication = writesRoot ? config.collection._deferPublication() : void 0; const changesToApply = bucketFacades ? new Map([...pendingChanges].map(([key, changes]) => { const resolved = { ...changes, value: bucketFacades.resolve(changes.value) }; if (changes.previousValue !== void 0) resolved.previousValue = bucketFacades.resolve(changes.previousValue); return [key, resolved]; })) : pendingChanges; facadePublication?.prepare(); if (writesRoot) { begin(snapshot ? { snapshot } : void 0); let lookup; const hasSyncedKey = (key) => { if (snapshot) return false; lookup ??= config.collection._state.createSyncedKeyLookup(); return lookup(key); }; changesToApply.forEach(this.fG.bind(this, config, hasSyncedKey)); if (hasOrderOnlyMove(changesToApply)) markLayoutChange(config.collection); commit(); this.al = false; } } catch (error) { rootPublication?.discard(); facadePublication?.rollback(); throw error; } pendingChanges = /* @__PURE__ */ new Map(); let publicationError; for (const publish of [rootPublication?.publish, facadePublication?.publish]) { if (!publish) continue; try { publish(); } catch (error) { publicationError ??= error; } } if (publicationError !== void 0) throw publicationError; }; graph.finalize(); syncState.graph = graph; syncState.inputs = inputs; syncState.pipeline = pipeline; return syncState; } fG(config, hasSyncedKey, changes, key) { const { write, collection } = config; const { deletes, inserts, value, orderByIndex } = changes; this.fz.set(value, key); if (orderByIndex !== void 0) this.cN.set(value, orderByIndex); if (inserts && deletes === 0) write({ value, type: `insert` }); else if (inserts > deletes || inserts === deletes && hasSyncedKey(collection.getKeyFromItem(value))) write({ value, type: `update` }); else if (deletes > 0) write({ value, type: `delete` }); else throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Could not apply changes: ${JSON.stringify(changes)}. This should never happen.` : require_error_message.codedMessage(151)); } /** * Handle status changes from source collections */ dj(config, sourceId, collectionId, event) { const { status } = event; if (status === `crashed`) { this.g0(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Source collection '${collectionId}' crashed` : require_error_message.codedMessage(172, { collectionId }), event.collection._lifecycle.getSyncError()); return; } if (status === `error`) { if (this.liveQueryCollection?.status === `ready`) return; this.failQuery(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Source collection '${collectionId}' failed its first load` : require_error_message.codedMessage(260, { collectionId }), event.collection._lifecycle.getSyncError()); return; } if (status === `cleaned-up`) { this.di(collectionId); return; } if (status === `ready`) { if (Object.values(this.optimizableOrderByCollections).some((info) => info.joinedFilterSourceIds?.includes(sourceId))) this.bx?.(); } this.bS(config); } di(collectionId) { if (this.cv) return; const error = new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Source collection '${collectionId}' was manually cleaned up while live query '${this.id}' depends on it. Live queries prevent automatic GC, so this was likely a manual cleanup() call.` : require_error_message.codedMessage(152, { collectionId, id: this.id })); this.g0(error.message, error); return error; } /** * Update the live query status based on source collection statuses */ bS(config) { if (this.cv || !this.e8()) return; if (this.al) this.currentSyncState?.flushPendingChanges?.(); if (!this.al) config.markReady(); } /** Whether the current run's graph result is complete. */ e8() { const syncState = this.currentSyncState; const allReady = this.eD(); const allDemandsSettled = [...this.aQ.values()].every((demand) => demand.settled); const isLoading = this.liveQueryCollection?.isLoadingSubset; return syncState?.subscribedToAllCollections === true && !syncState.graph.pendingWork() && allReady && allDemandsSettled && isLoading !== true && !this.hasPendingSourceRecovery(); } /** * The query's first load failed: status `error`. A sync problem or a * request error after the first ready never reaches here. */ failQuery(message, error) { if (!this.gY(message)) return; this.liveQueryCollection?._lifecycle.fail(error ?? new Error(message)); } /** * The query can no longer serve reads: a crashed source, a graph failure, * or a contract violation such as a source cleaned up under this query. */ g0(message, error) { this.gY(message); this.liveQueryCollection?._lifecycle.crash(error ?? new Error(message)); } /** Returns false when the query already ended. */ gY(message) { if (this.cv) return false; this.cv = true; console.error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `[Live Query Error] ${message}` : message); return true; } eD() { return this.ai.every(({ collection }) => require_utils$1.sourcePermitsInitialReadiness(collection)); } /** * Creates one subscription per lexical collection source. * Each source gets independent filters, even when aliases or collections repeat. * Example: `{ employee: col, manager: col }` creates two separate subscriptions. */ ev(config, syncState) { if (this.ai.length === 0) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Query '${this.id}' has no collection sources. This should not happen; please report.` : require_error_message.codedMessage(153, { id: this.id })); const relayed = /* @__PURE__ */ new Set(); const loaders = this.ai.map((source) => { const { sourceId, alias, collection } = source; const collectionId = collection.id; const dependencyBuilder = require_collection_registry.getCollectionBuilder(collection); if (dependencyBuilder && dependencyBuilder !== this) this.bh.add(dependencyBuilder); const collectionSubscriber = new require_collection_subscriber.CollectionSubscriber(sourceId, alias, collection, this); const statusUnsubscribe = collection.on(`status:change`, (event) => { this.dj(config, sourceId, collectionId, event); }); if (!relayed.has(collection)) { relayed.add(collection); syncState.unsubscribeCallbacks.add(collection.on(`health:change`, () => this.liveQueryCollection?._emitHealthChange())); } let cleanupStartError; const cleanupStartUnsubscribe = collection._onCleanupStart(() => { cleanupStartError = this.di(collectionId); }); if (cleanupStartError) { cleanupStartUnsubscribe(); statusUnsubscribe(); throw cleanupStartError; } syncState.unsubscribeCallbacks.add(statusUnsubscribe); syncState.unsubscribeCallbacks.add(cleanupStartUnsubscribe); if (require_live_query_primitives.isFailedStatus(collection.status)) this.dj(config, sourceId, collectionId, { type: `status:change`, collection, status: collection.status, previousStatus: collection.status }); const subscription = collectionSubscriber.subscribe(); this.subscriptions[sourceId] = subscription; if (subscription.isDeferringAcquisition()) { syncState.unsubscribeCallbacks.add(this.liveQueryCollection._onFirstSubscriberOrPreload(() => subscription.resumeDeferredAcquisition())); if (this.hasSubscriberOrPreload()) subscription.resumeDeferredAcquisition(); } const lazyCallbacks = this.lazySourcesCallbacks[sourceId]; if (lazyCallbacks) { lazyCallbacks.setDemand = (plan, keys) => collectionSubscriber.setDemand(subscription, plan, keys); for (const plan of lazyCallbacks.plans ?? []) if (plan.initialKeys.size > 0 && !this.a1?.offset) lazyCallbacks.setDemand(plan, plan.initialKeys); } return collectionSubscriber.loadMoreIfNeeded.bind(collectionSubscriber, subscription); }); syncState.subscribedToAllCollections = true; return () => require_callbacks.runAllCallbacks(loaders); } }; function createOrderByComparator(orderByIndices) { return (val1, val2) => { const index1 = orderByIndices.get(val1); const index2 = orderByIndices.get(val2); if (index1 && index2) { if (index1 < index2) return -1; else if (index1 > index2) return 1; else return 0; } return 0; }; } function accumulateChanges(acc, [[key, tupleData], multiplicity]) { const [value, orderByIndex] = tupleData; const changes = acc.get(key) || { deletes: 0, inserts: 0, value, orderByIndex }; if (multiplicity < 0) { if (changes.deletes === 0) { changes.previousValue = value; changes.previousOrderByIndex = orderByIndex; } changes.deletes += Math.abs(multiplicity); } else if (multiplicity > 0) { changes.inserts += multiplicity; changes.value = value; if (orderByIndex !== void 0) changes.orderByIndex = orderByIndex; } acc.set(key, changes); return acc; } function hasOrderOnlyMove(changesToApply) { for (const changes of changesToApply.values()) if (changes.inserts > 0 && changes.deletes > 0 && changes.previousValue !== void 0 && require_utils.deepEquals(changes.previousValue, changes.value) && changes.orderByIndex !== changes.previousOrderByIndex) return true; return false; } function markLayoutChange(collection) { collection._markLayoutChange(); } exports.CollectionConfigBuilder = CollectionConfigBuilder; //# sourceMappingURL=collection-config-builder.cjs.map