UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

936 lines • 51.1 kB
const require_type_guards = require("../../utils/type-guards.cjs");
const require_get_or_create = require("../../utils/get-or-create.cjs");
const require_optimizer = require("../optimizer.cjs");
const require_equality_value_identity = require("../equality-value-identity.cjs");
const require_errors = require("../../errors.cjs");
const require_virtual_props = require("../../virtual-props.cjs");
const require_index = require("../builder/index.cjs");
const require_ref_proxy_identity = require("../builder/ref-proxy-identity.cjs");
const require_functions = require("../builder/functions.cjs");
const require_ir = require("../ir.cjs");
const require_auto_index = require("../../indexes/auto-index.cjs");
const require_source_record = require("../../utils/source-record.cjs");
const require_utils = require("../../utils.cjs");
const require_comparison = require("../../utils/comparison.cjs");
const require_error_message = require("../../error-message.cjs");
const require_evaluators = require("./evaluators.cjs");
const require_joins = require("./joins.cjs");
const require_find_aggregate = require("./find-aggregate.cjs");
const require_lazy_targets = require("./lazy-targets.cjs");
const require_order_by = require("./order-by.cjs");
const require_parent_routes = require("./parent-routes.cjs");
const require_route_metadata = require("./route-metadata.cjs");
const require_select = require("./select.cjs");
let _tanstack_db_ivm = require("@tanstack/db-ivm");
function getUnsupportedFnSelectResultDescription(value, seen = /* @__PURE__ */ new Set()) {
	if (value instanceof require_functions.IncludeWrapper) return `include()`;
	if (value instanceof require_index.BaseQueryBuilder) return `a child query builder`;
	if (value instanceof require_functions.ToArrayWrapper) return `toArray()`;
	if (value instanceof require_functions.ConcatToArrayWrapper) return `concat(toArray())`;
	if (value instanceof require_functions.MaterializeWrapper) return `materialize()`;
	if (value instanceof require_functions.CaseWhenWrapper) return `caseWhen()`;
	if (require_ir.isExpressionLike(value)) return value && typeof value === `object` && `name` in value && typeof value.name === `string` ? `${value.name}()` : `a query expression`;
	if (value === null || typeof value !== `object` || seen.has(value)) return;
	seen.add(value);
	const keys = Reflect.ownKeys(value).filter((key) => Object.prototype.propertyIsEnumerable.call(value, key));
	for (const key of keys) {
		const entry = value[key];
		const unsupported = getUnsupportedFnSelectResultDescription(entry, seen);
		if (unsupported) return unsupported;
	}
}
function validateFnSelectResult(value) {
	const unsupportedValueDescription = getUnsupportedFnSelectResultDescription(value);
	if (unsupportedValueDescription) throw new require_errors.UnsupportedFnSelectResultError(unsupportedValueDescription);
}
function projectParentContext(nsRow, projections, valueIdentity) {
	const inherited = require_route_metadata.getRouteMetadata(nsRow)?.parentContext;
	const parentContext = { ...require_equality_value_identity.getParentContextValue(inherited) };
	const projectedBindings = { ...require_equality_value_identity.getParentContextProjectedBindings(inherited) };
	const projectedIdentity = [];
	for (const projection of projections) {
		const projectedValue = projection.compiled(nsRow);
		projectedIdentity.push([
			projection.alias,
			projection.bindingKey,
			projection.field,
			valueIdentity.equality(projectedValue)
		]);
		if (projection.bindingKey !== void 0) projectedBindings[projection.bindingKey] = projectedValue;
		if (projection.field.length === 0) {
			const projectedAlias = projectedValue;
			parentContext[projection.alias] = projectedAlias != null && typeof projectedAlias === `object` ? { ...projectedAlias } : projectedAlias;
			continue;
		}
		const inheritedAlias = parentContext[projection.alias];
		const aliasContext = inheritedAlias != null && typeof inheritedAlias === `object` ? { ...inheritedAlias } : {};
		parentContext[projection.alias] = aliasContext;
		let target = aliasContext;
		for (let index = 0; index < projection.field.length - 1; index++) {
			const segment = projection.field[index];
			const inheritedNested = target[segment];
			const nested = inheritedNested != null && typeof inheritedNested === `object` ? { ...inheritedNested } : {};
			target[segment] = nested;
			target = nested;
		}
		target[projection.field[projection.field.length - 1]] = projectedValue;
	}
	return require_equality_value_identity.createParentContext(parentContext, [require_equality_value_identity.getParentContextIdentity(inherited), projectedIdentity], projectedBindings);
}
function parameterizeByParentRoutes(pipeline, parentKeyStream, valueIdentity) {
	return require_parent_routes.crossJoinParentRoutes(pipeline, parentKeyStream, (rowKey, row, correlationKey, parentContext) => {
		const namespaced = {
			...require_equality_value_identity.getParentContextValue(parentContext),
			...row
		};
		namespaced[require_route_metadata.INCLUDES_PUBLIC_KEY] = namespaced[require_route_metadata.INCLUDES_PUBLIC_KEY] ?? rowKey;
		require_route_metadata.attachRouteMetadata(namespaced, correlationKey, parentContext);
		return [(0, _tanstack_db_ivm.serializeValue)([
			valueIdentity.equality(rowKey),
			valueIdentity.equality(correlationKey),
			require_equality_value_identity.getParentContextIdentity(parentContext)
		]), namespaced];
	});
}
function correlationValuesEqual(left, right) {
	if (left == null || right == null) return false;
	const normalizedLeft = require_comparison.normalizeValue(left);
	const normalizedRight = require_comparison.normalizeValue(right);
	return Object.is(normalizedLeft, normalizedRight);
}
var valueIdentitiesByCache = /* @__PURE__ */ new WeakMap();
function getCompilationValueIdentity(cache) {
	return require_get_or_create.getOrCreate(valueIdentitiesByCache, cache, require_equality_value_identity.createValueIdentity);
}
function compileQuery(...args) {
	return compileQueryInternal(args, false);
}
function compileCollectionQuery(...args) {
	return compileQueryInternal(args, false, true);
}
function compileQueryInternal([rawQuery, inputs, collections, subscriptions, callbacks, lazySources, optimizableOrderByCollections, setWindowFn, cache = /* @__PURE__ */ new WeakMap(), queryMapping = /* @__PURE__ */ new WeakMap(), parentKeyStream, childCorrelationField, ancestorHasTopK = false], scopeValidated, isCollectionRoot = false) {
	const cacheSlot = isCollectionRoot ? 1 : scopeValidated ? 2 : 0;
	const cachedResult = parentKeyStream === void 0 ? cache.get(rawQuery)?.[cacheSlot] : void 0;
	if (cachedResult) return cachedResult;
	const valueIdentity = getCompilationValueIdentity(cache);
	if (!scopeValidated) validateQueryStructure(rawQuery);
	const rawSources = require_ir.collectCollectionSources(rawQuery);
	const { optimizedQuery, sourceWhereClauses: aliasWhereClauses } = require_optimizer.optimizeQuery(rawQuery);
	const sourceWhereClauses = keyWhereClausesBySource(rawQuery, aliasWhereClauses);
	let query = optimizedQuery;
	queryMapping.set(query, rawQuery);
	mapNestedQueries(query, rawQuery, queryMapping);
	const allInputs = Object.assign(require_source_record.createSourceRecord(), inputs);
	bindSourceInputs(rawSources, allInputs);
	const aliasToCollectionId = {};
	const aliasRemapping = {};
	const sources = {};
	const { alias: mainSource, collectionId: mainCollectionId, pipeline: initialPipeline, sources: fromSources, sourceIncludes, directIncludes, isUnionFrom, isParentRouted } = processFromClause(query.from, allInputs, collections, subscriptions, callbacks, lazySources, optimizableOrderByCollections, ignoreWindow, cache, queryMapping, aliasToCollectionId, aliasRemapping, sourceWhereClauses, parentKeyStream);
	Object.assign(sources, fromSources);
	const sourceCarriesInternalRouteState = parentKeyStream !== void 0 || sourceIncludes.length > 0 || directIncludes.length > 0;
	let pipeline = initialPipeline;
	const childCorrelationAlias = childCorrelationField?.path[0];
	const joinsParentDirectly = !isUnionFrom && !isParentRouted && parentKeyStream !== void 0 && childCorrelationField !== void 0 && childCorrelationAlias === mainSource;
	if (parentKeyStream && childCorrelationField && joinsParentDirectly) {
		const mainInput = sources[mainSource];
		let filteredMainInput = mainInput;
		const childFieldPath = childCorrelationField.path.slice(1);
		const childRekeyed = mainInput.pipe((0, _tanstack_db_ivm.map)(([key, row, metadata]) => {
			const correlationValue = getNestedValue(row, childFieldPath);
			return [valueIdentity.serializeEquality(correlationValue), [
				key,
				row,
				correlationValue,
				metadata
			]];
		}));
		const equalityParentKeys = parentKeyStream.pipe((0, _tanstack_db_ivm.map)(([correlationValue, parentContext]) => [valueIdentity.serializeEquality(correlationValue), parentContext]), (0, _tanstack_db_ivm.reduce)((values) => values.map(([value, multiplicity]) => [value, multiplicity > 0 ? 1 : 0])));
		filteredMainInput = childRekeyed.pipe((0, _tanstack_db_ivm.join)(equalityParentKeys, `inner`)).pipe((0, _tanstack_db_ivm.filter)(([_correlationValue, [childSide]]) => {
			return childSide != null;
		}), (0, _tanstack_db_ivm.map)(([_correlationIdentity, [childSide, parentSide]]) => {
			const [childKey, childRow, correlationValue, metadata] = childSide;
			const tagged = require_route_metadata.attachRouteMetadata({
				...childRow,
				[require_route_metadata.INCLUDES_PUBLIC_KEY]: childKey
			}, correlationValue, parentSide);
			return [
				parentSide != null ? (0, _tanstack_db_ivm.serializeValue)([valueIdentity.equality(childKey), require_equality_value_identity.getParentContextIdentity(parentSide)]) : childKey,
				tagged,
				metadata
			];
		}));
		sources[mainSource] = filteredMainInput;
		pipeline = wrapInputWithAlias(filteredMainInput, mainSource);
	} else if (parentKeyStream && !isParentRouted) pipeline = parameterizeByParentRoutes(initialPipeline, parentKeyStream, valueIdentity);
	if (query.join && query.join.length > 0) pipeline = require_joins.processJoins(pipeline, query.join, sources, mainCollectionId, mainSource, allInputs, queryMapping, collections, callbacks, lazySources, rawQuery, query.from, (subquery, parentRoutes) => compileQueryInternal([
		subquery,
		allInputs,
		collections,
		subscriptions,
		callbacks,
		lazySources,
		optimizableOrderByCollections,
		ignoreWindow,
		cache,
		queryMapping,
		parentRoutes
	], true, false), aliasToCollectionId, aliasRemapping, sourceWhereClauses, joinsParentDirectly, valueIdentity, sourceIncludes, parentKeyStream);
	const canLoseMainSide = query.join?.some(({ type }) => type === `right` || type === `full`);
	if (parentKeyStream && childCorrelationField && (!joinsParentDirectly || canLoseMainSide)) {
		const compiledChildCorrelation = require_evaluators.compileExpression(childCorrelationField);
		pipeline = pipeline.pipe((0, _tanstack_db_ivm.filter)(([, row]) => correlationValuesEqual(compiledChildCorrelation(row), require_route_metadata.getNamespacedRouteMetadata(row, mainSource)?.correlationKey)));
	}
	if (query.where && query.where.length > 0) for (const where of query.where) {
		const whereExpression = require_ir.getWhereExpression(where);
		const compiledWhere = require_evaluators.compileExpression(whereExpression);
		pipeline = pipeline.pipe((0, _tanstack_db_ivm.filter)(([_key, namespacedRow]) => {
			return require_evaluators.toBooleanPredicate(compiledWhere(namespacedRow));
		}));
	}
	if (query.fnWhere && query.fnWhere.length > 0) for (const fnWhere of query.fnWhere) pipeline = pipeline.pipe((0, _tanstack_db_ivm.filter)(([_key, namespacedRow]) => {
		const callbackRow = require_route_metadata.stripInternalCallbackMetadata(namespacedRow);
		return require_evaluators.toBooleanPredicate(fnWhere(callbackRow));
	}));
	const inputIncludes = [...directIncludes, ...sourceIncludes.map(({ include }) => include)];
	const materializeSelectInput = !!query.fnSelect && inputIncludes.length > 0;
	let includesResults = !query.select ? [...directIncludes] : [];
	let includesRoutingFns = [];
	const inheritedIncludes = [...sourceIncludes.map(({ sourceAlias, include }) => ({
		include,
		keyPrefix: `${sourceAlias}.`,
		paths: query.select != null ? findProjectedIncludePaths(query.select, [sourceAlias, ...include.resultPath]) : query.fnSelect && !materializeSelectInput ? [] : [{
			path: [sourceAlias, ...include.resultPath],
			guards: []
		}],
		route: (nsRow) => require_route_metadata.getSourceRouting(nsRow, sourceAlias)?.[include.fieldName]
	})), ...(query.select ? directIncludes : []).map((include) => ({
		include,
		keyPrefix: ``,
		paths: findProjectedIncludePaths(query.select, include.resultPath),
		route: (nsRow) => readRouteTag(nsRow, include.fieldName)
	}))];
	for (const { include, keyPrefix, paths, route } of inheritedIncludes) for (const { path: resultPath, guards } of paths) {
		const fieldName = getUniqueIncludesRoutingKey(keyPrefix + resultPath.join(`.`), includesRoutingFns);
		includesResults.push({
			...include,
			fieldName,
			resultPath
		});
		includesRoutingFns.push({
			fieldName,
			getRouting: compileGuardedRouting(guards, route)
		});
	}
	const selectAggregate = require_find_aggregate.findAggregate(query.select);
	const selectHasAggregates = selectAggregate !== void 0;
	const hasOrderBy = (query.orderBy?.length ?? 0) > 0;
	const parentHasTopK = hasOrderBy || !!query.singleResult;
	const deferredIncludes = [];
	if (query.select) {
		const includesEntries = extractIncludesFromSelect(query.select);
		if (includesEntries.length > 0 && ((query.groupBy?.length ?? 0) > 0 || selectHasAggregates)) throw new require_errors.NonAggregateExpressionNotInGroupByError(includesEntries[0].path.join(`.`));
		if (includesEntries.length > 0) query = {
			...query,
			select: { ...query.select }
		};
		for (const { key, path, subquery, guards } of includesEntries) {
			if (typeof subquery.runtime?.materializeCompilation !== `function`) throw new require_errors.IncludeOperatorRequiredError(key);
			const fieldName = getUniqueIncludesRoutingKey(key, includesRoutingFns);
			const compiledCorrelation = require_evaluators.compileExpression(subquery.correlationField);
			const compiledProjections = subquery.parentProjection?.map((ref) => ({
				alias: ref.path[0],
				field: ref.path.slice(1),
				bindingKey: ref.bindingId ? JSON.stringify([ref.bindingId, ref.path.slice(1)]) : void 0,
				compiled: require_evaluators.compileExpression(ref)
			})) ?? [];
			const getRouting = compileGuardedRouting(guards, (nsRow) => ({
				active: true,
				correlationKey: compiledCorrelation(nsRow),
				parentContext: compiledProjections.length > 0 ? projectParentContext(nsRow, compiledProjections, valueIdentity) : null
			}));
			const compileInclude = (windowRows) => {
				let parentKeys = (windowRows ? windowRows.pipe((0, _tanstack_db_ivm.map)(([, [row]]) => windowRoute(row, fieldName))) : pipeline.pipe((0, _tanstack_db_ivm.map)(([, row]) => getRouting(row)))).pipe((0, _tanstack_db_ivm.filter)((routing) => routing.active), (0, _tanstack_db_ivm.map)((routing) => [routing.correlationKey, routing.parentContext]), (0, _tanstack_db_ivm.reduce)((values) => values.map(([v, mult]) => [v, mult > 0 ? 1 : 0])));
				const childSourceAlias = subquery.childCorrelationField.path[0];
				const directChildCollection = subquery.query.from.type === `collectionRef` ? subquery.query.from.collection : void 0;
				const lazyTargets = require_lazy_targets.getLazyLoadTargets(subquery.query, subquery.query.from, childSourceAlias, subquery.childCorrelationField, directChildCollection, aliasRemapping);
				if (lazyTargets.length > 0) {
					for (const target of lazyTargets) {
						lazySources.add(target.sourceId);
						const targetFieldName = target.path[0];
						if (targetFieldName) require_auto_index.ensureIndexForField(targetFieldName, target.path, target.collection);
					}
					const staticKeys = getStaticDemandKeys(rawQuery, subquery.correlationField);
					const initialKeys = !ancestorHasTopK && (!windowRows || query.singleResult && query.offset === void 0 && (query.limit ?? 1) > 0 && staticKeys.size === 1) ? staticKeys : /* @__PURE__ */ new Set();
					const demandPlans = lazyTargets.map((target) => require_joins.registerLazyDemandPlan(callbacks, target, initialKeys));
					const demandWeights = /* @__PURE__ */ new Map();
					parentKeys = parentKeys.pipe((0, _tanstack_db_ivm.tap)((data) => {
						for (const [[correlationValue], weight] of data.getInner()) {
							if (correlationValue == null) continue;
							const encoded = valueIdentity.serializeEquality(correlationValue);
							const nextWeight = (demandWeights.get(encoded)?.weight ?? 0) + weight;
							if (nextWeight === 0) demandWeights.delete(encoded);
							else demandWeights.set(encoded, {
								key: correlationValue,
								weight: nextWeight
							});
						}
						const keys = new Set([...demandWeights.values()].filter(({ weight }) => weight > 0).map(({ key: demandedKey }) => demandedKey));
						lazyTargets.forEach((target, index) => callbacks[target.sourceId]?.setDemand?.(demandPlans[index], keys));
					}));
				}
				const childResult = compileQueryInternal([
					subquery.parentFilters && subquery.parentFilters.length > 0 ? {
						...subquery.query,
						where: [...subquery.query.where || [], ...subquery.parentFilters]
					} : subquery.query,
					allInputs,
					collections,
					subscriptions,
					callbacks,
					lazySources,
					optimizableOrderByCollections,
					ignoreWindow,
					cache,
					queryMapping,
					parentKeys,
					subquery.childCorrelationField,
					ancestorHasTopK || parentHasTopK
				], true, subquery.materialization === `collection`);
				for (const [alias, whereClause] of childResult.sourceWhereClauses) sourceWhereClauses.set(alias, whereClause);
				includesResults.push({
					pipeline: childResult.pipeline,
					fieldName,
					resultPath: path,
					correlationField: subquery.correlationField,
					childCorrelationField: subquery.childCorrelationField,
					hasOrderBy: (subquery.query.orderBy?.length ?? 0) > 0,
					childCompilationResult: childResult,
					parentProjection: subquery.parentProjection,
					materialization: subquery.materialization,
					scalarField: subquery.scalarField,
					runtime: subquery.runtime
				});
			};
			if (parentHasTopK) deferredIncludes.push(compileInclude);
			else compileInclude();
			includesRoutingFns.push({
				fieldName,
				getRouting
			});
			query = {
				...query,
				select: replaceIncludesInSelectValue(query.select, path)
			};
		}
	}
	if (query.distinct && !query.fnSelect && !query.select && query.from.type !== `unionAll`) throw new require_errors.DistinctRequiresSelectError();
	if (query.fnSelect && query.groupBy && query.groupBy.length > 0) throw new require_errors.FnSelectWithGroupByError();
	const routingFns = includesRoutingFns;
	const getRowIncludesRouting = (row) => Object.fromEntries(routingFns.map(({ fieldName, getRouting }) => [fieldName, getRouting(row)]));
	if (materializeSelectInput) {
		if (!inputIncludes.every(isInlineInclude)) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `fn.select() cannot consume Collection-valued includes. Use toArray() or materialize() in the upstream select(), or use an expression select() to keep live Collections.` : require_error_message.codedMessage(128));
		const inputPipeline = pipeline.pipe((0, _tanstack_db_ivm.map)(([key, row]) => [key, [{
			...row,
			[require_route_metadata.INCLUDES_ROUTING]: {
				...row[require_route_metadata.INCLUDES_ROUTING],
				...getRowIncludesRouting(row)
			}
		}, void 0]]));
		const materializedInput = includesResults[0].runtime.materializeCompilation({
			pipeline: inputPipeline,
			includes: includesResults,
			valueIdentity,
			collectionId: mainCollectionId,
			sourceWhereClauses,
			aliasToCollectionId,
			aliasRemapping
		});
		const resolveInput = materializedInput.resolve;
		pipeline = materializedInput.pipeline.pipe((0, _tanstack_db_ivm.map)(([key, [value]]) => {
			const resolved = resolveInput ? resolveInput(value, (leaf) => leaf) : value;
			const row = resolved === value ? { ...value } : resolved;
			require_route_metadata.restoreInternalRouteMetadata(row, value);
			delete row[require_route_metadata.INCLUDES_ROUTING];
			return [key, row];
		}));
		includesResults = [];
		includesRoutingFns = [];
	}
	const sourceBindings = new Map(getAllSources(query).map((source) => [source.alias, source.bindingId]));
	const sourceAliases = [...sourceBindings.keys()];
	const unionRows = query.from.type === `unionAll`;
	if (query.fnSelect) pipeline = pipeline.pipe((0, _tanstack_db_ivm.map)(([key, namespacedRow]) => {
		const callbackRow = require_route_metadata.stripInternalCallbackMetadata(namespacedRow);
		const selectResults = query.fnSelect(callbackRow);
		validateFnSelectResult(selectResults);
		let selected = selectResults;
		const routing = namespacedRow[require_route_metadata.INCLUDES_ROUTING];
		if (routing && require_route_metadata.isPublicContainer(selectResults)) {
			selected = copySelectedRow(selectResults);
			selected[require_route_metadata.INCLUDES_ROUTING] = routing;
		}
		return [key, {
			...namespacedRow,
			$selected: selected
		}];
	}));
	else if (query.select) {
		if (!selectHasAggregates && !(query.groupBy && query.groupBy.length > 0)) pipeline = require_select.processSelect(pipeline, query.select, allInputs);
	} else pipeline = pipeline.pipe((0, _tanstack_db_ivm.map)(([key, namespacedRow]) => {
		const routedScalar = require_route_metadata.getRoutedScalarMetadata(namespacedRow);
		const selectResults = isUnionFrom && routedScalar ? routedScalar.value : !isUnionFrom && !query.join && !query.groupBy ? namespacedRow[mainSource] : namespacedRow;
		return [key, {
			...namespacedRow,
			$selected: selectResults
		}];
	}));
	if (includesRoutingFns.length > 0) pipeline = pipeline.pipe((0, _tanstack_db_ivm.map)(([key, namespacedRow]) => {
		const selected = copySelectedRow(namespacedRow.$selected);
		selected[require_route_metadata.INCLUDES_ROUTING] = getRowIncludesRouting(namespacedRow);
		return [key, {
			...namespacedRow,
			$selected: selected
		}];
	}));
	const groupByMainSource = parentKeyStream ? mainSource : void 0;
	const isSourceRef = (ref) => {
		const binding = sourceBindings.get(ref.path[0]);
		if (binding !== void 0) return (ref.bindingId ?? binding) === binding;
		return unionRows && ref.bindingId === void 0 && ref.path[0] !== `$selected`;
	};
	const aggregate = selectAggregate ?? require_find_aggregate.findAggregate([query.having, query.orderBy?.map((clause) => clause.expression)]);
	const grouping = query.grouping ?? aggregate?.grouping;
	const grouped = (query.groupBy?.length ?? 0) > 0;
	if ((grouped || aggregate) && !grouping) throw new require_errors.GroupingOperatorRequiredError();
	if (grouping && (grouped || selectAggregate)) pipeline = grouping.processGroupBy(pipeline, query.groupBy ?? [], valueIdentity, isSourceRef, query.having, query.select, query.fnHaving, groupByMainSource, sourceCarriesInternalRouteState || includesRoutingFns.length > 0);
	if (query.having && (!query.groupBy || query.groupBy.length === 0) && !selectHasAggregates) throw new require_errors.HavingRequiresGroupByError();
	if (query.fnHaving && query.fnHaving.length > 0 && (!query.groupBy || query.groupBy.length === 0)) for (const fnHaving of query.fnHaving) pipeline = pipeline.pipe((0, _tanstack_db_ivm.filter)(([_key, namespacedRow]) => {
		const callbackRow = require_route_metadata.stripInternalCallbackMetadata(namespacedRow);
		const selected = require_route_metadata.stripInternalCallbackMetadata(callbackRow.$selected);
		return fnHaving(selected === callbackRow.$selected ? callbackRow : {
			...callbackRow,
			$selected: selected
		});
	}));
	if (!selectHasAggregates && query.distinct) pipeline = canonicalizeSelectedRows(pipeline, query, mainSource, parentKeyStream !== void 0);
	if (query.distinct) pipeline = pipeline.pipe((0, _tanstack_db_ivm.distinct)(([_key, row]) => row.$selected));
	const metadataSource = query.select ? getWholeRowSourceAliases(query.select) : query.from.type === `unionAll` ? void 0 : query.join ? [] : [mainSource];
	const finalizeRow = (key, row, orderByIndex) => {
		const selected = unwrapValue(row.$selected);
		const selectedValue = !isCollectionRoot && (grouped || selectAggregate) && require_route_metadata.isPublicContainer(selected) && !(`$key` in selected) ? Object.assign(copySelectedRow(selected), { $key: row.$key }) : selected;
		let metadata = null;
		if (query.fnSelect) {
			const alias = sourceAliases.find((source) => selectedValue === row[source]);
			if (alias !== void 0) metadata = require_route_metadata.getSourceMetadata(row, alias);
		} else if (metadataSource === void 0) metadata = row[require_route_metadata.ROW_METADATA] ?? null;
		else for (const alias of metadataSource) if (row[alias] != null) metadata = require_route_metadata.getSourceMetadata(row, alias);
		if (query.join && metadata && `$key` in metadata) {
			metadata = { ...metadata };
			delete metadata.$key;
		}
		const finalResults = require_route_metadata.stripInternalRouteMetadata(isCollectionRoot ? attachVirtualPropsToSelected(selectedValue, metadata) : selectedValue);
		const route = parentKeyStream ? require_route_metadata.getNamespacedRouteMetadata(row, mainSource) : void 0;
		return [key, [
			finalResults,
			orderByIndex,
			route?.correlationKey,
			parentKeyStream ? route?.parentContext ?? null : void 0,
			parentKeyStream ? row[require_route_metadata.INCLUDES_PUBLIC_KEY] ?? key : void 0,
			metadata
		]];
	};
	const resultLimit = query.singleResult ? Math.min(query.limit ?? 1, 1) : query.limit;
	if (!hasOrderBy && (query.limit !== void 0 || query.offset !== void 0)) throw new require_errors.LimitOffsetRequireOrderByError();
	let resultPipeline;
	let ownWindowFn;
	if (hasOrderBy || query.singleResult) {
		const includesGroupKeyFn = parentKeyStream && (resultLimit !== void 0 || query.offset !== void 0) ? (_key, row) => {
			const route = require_route_metadata.getNamespacedRouteMetadata(row, mainSource);
			const correlationKey = route?.correlationKey;
			const parentContext = route?.parentContext;
			if (parentContext != null) return (0, _tanstack_db_ivm.serializeValue)([valueIdentity.equality(correlationKey), require_equality_value_identity.getParentContextIdentity(parentContext)]);
			return valueIdentity.equality(correlationKey);
		} : void 0;
		const ordered = require_order_by.processOrderBy(rawQuery, pipeline, query.orderBy ?? [], query.select || {}, grouping, collections[mainCollectionId], optimizableOrderByCollections, (windowFn) => ownWindowFn = windowFn, resultLimit, query.offset, includesGroupKeyFn);
		for (const compileInclude of deferredIncludes) compileInclude(ordered);
		if (ownWindowFn) setWindowFn(ownWindowFn);
		resultPipeline = ordered.pipe((0, _tanstack_db_ivm.map)(([key, [row, orderByIndex]]) => finalizeRow(key, row, orderByIndex)));
	} else resultPipeline = pipeline.pipe((0, _tanstack_db_ivm.map)(([key, row]) => finalizeRow(key, row, void 0)));
	const compilationResult = {
		collectionId: mainCollectionId,
		pipeline: resultPipeline,
		valueIdentity,
		sourceWhereClauses,
		aliasToCollectionId,
		aliasRemapping,
		includes: includesResults.length > 0 ? includesResults : void 0
	};
	if (parentKeyStream === void 0) require_get_or_create.getOrCreate(cache, rawQuery, () => [])[cacheSlot] = compilationResult;
	return compilationResult;
}
function isInlineInclude(include) {
	return include.materialization !== `collection` && (include.childCompilationResult.includes ?? []).every(isInlineInclude);
}
function keyWhereClausesBySource(query, clauses) {
	const localSources = getAllSources(query).filter((source) => source.type === `collectionRef`);
	const localSourceByAlias = new Map(localSources.map((source) => [source.alias, source]));
	const result = /* @__PURE__ */ new Map();
	for (const [key, clause] of clauses) {
		const source = localSourceByAlias.get(key);
		if (source) result.set(source.sourceId, clause);
	}
	return result;
}
function bindSourceInputs(sources, inputs) {
	for (const source of sources) {
		const input = inputs[source.sourceId] ?? inputs[source.alias];
		if (input) inputs[source.sourceId] = input;
	}
}
function canonicalizeSelectedRows(pipeline, query, mainSource, isIncludedRelation) {
	const compiledOrder = (query.orderBy ?? []).map(({ expression }) => require_evaluators.compileExpression(expression));
	const signature = (row) => {
		const route = isIncludedRelation ? require_route_metadata.getNamespacedRouteMetadata(row, mainSource) : void 0;
		return {
			value: row.$selected,
			routing: row.$selected?.[require_route_metadata.INCLUDES_ROUTING],
			outerCorrelation: route?.correlationKey,
			parentContext: isIncludedRelation ? route?.parentContext ?? null : void 0,
			order: compiledOrder.map((evaluate) => evaluate(row))
		};
	};
	return pipeline.pipe((0, _tanstack_db_ivm.reduce)((values) => {
		const totalMultiplicity = values.reduce((total, [, multiplicity]) => total + multiplicity, 0);
		if (totalMultiplicity === 0) return [];
		if (totalMultiplicity < 0) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Query row has negative multiplicity` : require_error_message.codedMessage(129));
		const visible = values.find(([, multiplicity]) => multiplicity > 0)?.[0];
		if (!visible) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Query row has no positive contributor` : require_error_message.codedMessage(130));
		const visibleSignature = signature(visible);
		for (const [candidate, multiplicity] of values) if (multiplicity > 0 && !require_utils.deepEquals(visibleSignature, signature(candidate))) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Query contributors with the same row key are not congruent` : require_error_message.codedMessage(131));
		return [[visible, 1]];
	}));
}
function validateExpressionBindings(expression, availableBindings) {
	for (const ref of require_ir.collectPropRefs(expression)) if (ref.bindingId !== void 0 && !availableBindings.has(ref.bindingId)) throw new require_errors.QueryCompilationError(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Query reference "${ref.path.join(`.`)}" is out of scope. Use a source from this query or a containing query.` : require_error_message.codedMessage(238, { path: ref.path }));
}
function validateSelectBindings(value, availableBindings) {
	if (value instanceof require_ir.IncludesSubquery) return;
	if (require_ir.isBasicOrAggregateExpression(value)) validateExpressionBindings(value, availableBindings);
	else if (value instanceof require_ir.ConditionalSelect) {
		for (const branch of value.branches) {
			validateExpressionBindings(branch.condition, availableBindings);
			validateSelectBindings(branch.value, availableBindings);
		}
		if (value.defaultValue !== void 0) validateSelectBindings(value.defaultValue, availableBindings);
	} else if (isNestedSelectObject(value)) for (const nested of Object.values(value)) validateSelectBindings(nested, availableBindings);
}
function validateQueryStructure(query, ancestorBindings = /* @__PURE__ */ new Set()) {
	const levelAliases = getAllSources(query).map((source) => source.alias);
	for (const [index, alias] of levelAliases.entries()) if (levelAliases.indexOf(alias) !== index) throw new require_errors.QueryCompilationError(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Query uses alias "${alias}" more than once. Give each source in one query a distinct alias.` : require_error_message.codedMessage(211, { alias }));
	const availableBindings = new Set(ancestorBindings);
	if (query.from.type === `unionAll`) for (const branch of query.from.queries) validateQueryStructure(branch, ancestorBindings);
	else for (const source of require_ir.getFromSources(query.from)) {
		if (source.type === `queryRef`) validateQueryStructure(source.query, ancestorBindings);
		availableBindings.add(source.bindingId);
	}
	if (query.join) for (const joinClause of query.join) {
		if (joinClause.from.type === `queryRef`) validateQueryStructure(joinClause.from.query, ancestorBindings);
		const joinBindings = new Set(availableBindings);
		joinBindings.add(joinClause.from.bindingId);
		validateExpressionBindings(joinClause.on, joinBindings);
		availableBindings.add(joinClause.from.bindingId);
	}
	for (const where of query.where ?? []) validateExpressionBindings(require_ir.getWhereExpression(where), availableBindings);
	for (const expression of query.groupBy ?? []) validateExpressionBindings(expression, availableBindings);
	for (const having of query.having ?? []) validateExpressionBindings(require_ir.getHavingExpression(having), availableBindings);
	for (const { expression } of query.orderBy ?? []) validateExpressionBindings(expression, availableBindings);
	if (query.select) {
		validateSelectBindings(query.select, availableBindings);
		for (const { subquery } of extractIncludesFromSelect(query.select)) {
			validateExpressionBindings(subquery.correlationField, availableBindings);
			const childBindings = new Set(availableBindings);
			for (const source of getAllSources(subquery.query)) childBindings.add(source.bindingId);
			validateExpressionBindings(subquery.childCorrelationField, childBindings);
			for (const where of subquery.parentFilters ?? []) validateExpressionBindings(require_ir.getWhereExpression(where), childBindings);
			validateQueryStructure(subquery.query, availableBindings);
			const projected = new Set((subquery.parentProjection ?? []).map((ref) => JSON.stringify([ref.bindingId, ref.path])));
			const required = [...require_index.collectExternalRefsFromQuery(subquery.query), ...(subquery.parentFilters ?? []).flatMap((where) => require_ir.collectPropRefs(require_ir.getWhereExpression(where)))];
			for (const ref of required) if (ref.bindingId !== void 0 && availableBindings.has(ref.bindingId) && !projected.has(JSON.stringify([ref.bindingId, ref.path]))) throw new require_errors.QueryCompilationError(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Include query is missing a captured parent projection for "${ref.path.join(`.`)}".` : require_error_message.codedMessage(239, { path: ref.path }));
		}
	}
}
function processFromClause(from, allInputs, collections, subscriptions, callbacks, lazySources, optimizableOrderByCollections, setWindowFn, cache, queryMapping, aliasToCollectionId, aliasRemapping, sourceWhereClauses, parentKeyStream) {
	const valueIdentity = getCompilationValueIdentity(cache);
	if (from.type === `unionAll`) return processUnionAll(from, allInputs, collections, subscriptions, callbacks, lazySources, optimizableOrderByCollections, setWindowFn, cache, queryMapping, aliasToCollectionId, aliasRemapping, sourceWhereClauses, parentKeyStream);
	const compileSource = (source) => {
		const result = require_joins.processSource(source, allInputs, queryMapping, (subquery, parentRoutes) => compileQueryInternal([
			subquery,
			allInputs,
			collections,
			subscriptions,
			callbacks,
			lazySources,
			optimizableOrderByCollections,
			setWindowFn,
			cache,
			queryMapping,
			parentRoutes
		], true), aliasToCollectionId, aliasRemapping, sourceWhereClauses, valueIdentity, `from`, parentKeyStream);
		return {
			...result,
			sourceIncludes: result.includes?.map((include) => ({
				sourceAlias: source.alias,
				include
			})) ?? [],
			isParentRouted: source.type === `queryRef` && parentKeyStream !== void 0
		};
	};
	if (from.type !== `unionFrom`) {
		const { alias, input, collectionId, sourceIncludes: sourceIncludes2, isParentRouted } = compileSource(from);
		return {
			alias,
			pipeline: wrapInputWithAlias(input, alias, from.type === `queryRef`),
			collectionId,
			sources: { [alias]: input },
			sourceIncludes: sourceIncludes2,
			directIncludes: [],
			isUnionFrom: false,
			isParentRouted
		};
	}
	if (from.sources.length === 0) throw new require_errors.UnsupportedFromTypeError(`empty unionFrom`);
	const sources = {};
	const sourceIncludes = [];
	let pipeline;
	let mainAlias = ``;
	let mainCollectionId = ``;
	for (const source of from.sources) {
		const { alias, input, collectionId, sourceIncludes: childSourceIncludes, isParentRouted } = compileSource(source);
		if (!mainAlias) {
			mainAlias = alias;
			mainCollectionId = collectionId;
		}
		sources[alias] = input;
		sourceIncludes.push(...childSourceIncludes);
		const branch = (parentKeyStream && !isParentRouted ? parameterizeByParentRoutes(wrapInputWithAlias(input, alias, source.type === `queryRef`), parentKeyStream, valueIdentity) : wrapInputWithAlias(input, alias, source.type === `queryRef`)).pipe((0, _tanstack_db_ivm.map)(([key, row]) => {
			const branchKey = `${alias}:${encodeKeyForUnionBranch(key)}`;
			const publicKey = row[require_route_metadata.INCLUDES_PUBLIC_KEY] ?? key;
			const branchPublicKey = `${alias}:${encodeKeyForUnionBranch(publicKey)}`;
			return [branchKey, parentKeyStream ? {
				...row,
				[require_route_metadata.INCLUDES_PUBLIC_KEY]: branchPublicKey
			} : row];
		}));
		pipeline = pipeline ? pipeline.pipe((0, _tanstack_db_ivm.concat)(branch)) : branch;
	}
	return {
		alias: mainAlias,
		pipeline,
		collectionId: mainCollectionId,
		sources,
		sourceIncludes,
		directIncludes: [],
		isUnionFrom: true,
		isParentRouted: parentKeyStream !== void 0
	};
}
function processUnionAll(from, allInputs, collections, subscriptions, callbacks, lazySources, optimizableOrderByCollections, setWindowFn, cache, queryMapping, aliasToCollectionId, aliasRemapping, sourceWhereClauses, parentKeyStream) {
	if (from.queries.length === 0) throw new require_errors.UnsupportedFromTypeError(`empty unionAll`);
	const sources = {};
	const sourceIncludes = [];
	const directIncludes = [];
	let pipeline;
	let mainCollectionId = ``;
	const branchAliases = /* @__PURE__ */ new Set();
	for (let index = 0; index < from.queries.length; index++) {
		const branch = from.queries[index];
		for (const source of getAllSources(branch)) {
			if (branchAliases.has(source.alias)) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Duplicate source alias "${source.alias}" in unionAll query branches. Use distinct aliases in each branch before passing them to unionAll().` : require_error_message.codedMessage(132, { alias: source.alias }));
			branchAliases.add(source.alias);
		}
		const branchResult = compileQueryInternal([
			branch,
			allInputs,
			collections,
			subscriptions,
			callbacks,
			lazySources,
			optimizableOrderByCollections,
			setWindowFn,
			cache,
			queryMapping,
			parentKeyStream,
			void 0
		], true);
		if (!mainCollectionId) mainCollectionId = branchResult.collectionId;
		Object.assign(aliasToCollectionId, branchResult.aliasToCollectionId);
		Object.assign(aliasRemapping, branchResult.aliasRemapping);
		directIncludes.push(...branchResult.includes ?? []);
		Object.assign(sources, allInputs);
		for (const [alias, where] of branchResult.sourceWhereClauses) sourceWhereClauses.set(alias, where);
		const branchPipeline = branchResult.pipeline.pipe((0, _tanstack_db_ivm.map)((data) => {
			const [key, [row, _order, correlationKey, parentContext, publicKey, metadata]] = data;
			const branchKey = `${index}:${encodeKeyForUnionBranch(key)}`;
			const branchPublicKey = `${index}:${encodeKeyForUnionBranch(publicKey ?? key)}`;
			const routedRow = parentKeyStream ? require_route_metadata.attachRouteMetadataToResult(row, correlationKey, parentContext, branchPublicKey) : row;
			return [branchKey, metadata != null && require_route_metadata.isPublicContainer(routedRow) ? Object.assign(copySelectedRow(routedRow), { [require_route_metadata.ROW_METADATA]: metadata ?? null }) : routedRow];
		}));
		pipeline = pipeline ? pipeline.pipe((0, _tanstack_db_ivm.concat)(branchPipeline)) : branchPipeline;
	}
	return {
		alias: ``,
		pipeline,
		collectionId: mainCollectionId,
		sources,
		sourceIncludes,
		directIncludes,
		isUnionFrom: true,
		isParentRouted: parentKeyStream !== void 0
	};
}
function wrapInputWithAlias(input, alias, hasInternalState = true) {
	return input.pipe((0, _tanstack_db_ivm.map)(([key, row, metadata]) => [key, require_route_metadata.wrapInputRow(alias, row, metadata, hasInternalState)]));
}
function encodeKeyForUnionBranch(key) {
	const type = typeof key;
	return `${type}:${type === `string` || type === `number` || type === `bigint` ? String(key) : JSON.stringify(key)}`;
}
function unwrapValue(value) {
	return value instanceof require_ir.Value ? value.value : value;
}
function getWholeRowSourceAliases(select) {
	if (select instanceof require_ir.PropRef && select.path.length === 1) return [select.path[0]];
	if (!require_type_guards.isPlainObject(select)) return [];
	return Object.entries(select).flatMap(([name, value]) => name.startsWith(`__SPREAD_SENTINEL__`) && value instanceof require_ir.PropRef && value.path.length === 1 ? [value.path[0]] : []);
}
function copySelectedRow(selected) {
	return Array.isArray(selected) ? [...selected] : { ...selected };
}
function attachVirtualPropsToSelected(selected, metadata) {
	if (!require_route_metadata.isPublicContainer(selected)) return selected;
	const selectedRecord = selected;
	let result = selectedRecord;
	for (const prop of require_virtual_props.VIRTUAL_PROP_NAMES) {
		const present = metadata !== null && prop in metadata;
		if (present ? prop in selectedRecord && selectedRecord[prop] === metadata[prop] : !(prop in selectedRecord)) continue;
		if (result === selectedRecord) result = copySelectedRow(selectedRecord);
		if (present) result[prop] = metadata[prop];
		else delete result[prop];
	}
	return result;
}
function mapNestedQueries(optimizedQuery, originalQuery, queryMapping) {
	mapNestedFromQueries(optimizedQuery.from, originalQuery.from, queryMapping);
	if (optimizedQuery.join && originalQuery.join) for (let i = 0; i < optimizedQuery.join.length && i < originalQuery.join.length; i++) mapNestedFromQueries(optimizedQuery.join[i].from, originalQuery.join[i].from, queryMapping);
}
function getAllSources(query) {
	return [...require_ir.getFromSources(query.from), ...query.join?.map((join) => join.from) ?? []];
}
function findProjectedIncludePaths(select, targetPath) {
	const resultPaths = [];
	const visitSelectObject = (obj, prefix, guards) => {
		for (const [key, value] of Object.entries(obj)) {
			if (key.startsWith(`__SPREAD_SENTINEL__`)) {
				visitSpreadSentinel(key, value, prefix, guards);
				continue;
			}
			visitSelectValue(value, [...prefix, key], guards);
		}
	};
	const visitSpreadSentinel = (key, value, path, guards) => {
		const rest = key.slice(`__SPREAD_SENTINEL__`.length);
		const splitIndex = rest.lastIndexOf(`__`);
		const pathStr = splitIndex >= 0 ? rest.slice(0, splitIndex) : rest;
		const sourcePath = value && typeof value === `object` && `type` in value && value.type === `ref` ? value.path : pathStr.split(`.`).filter(Boolean);
		if (pathStartsWith(targetPath, sourcePath)) resultPaths.push({
			path: [...path, ...targetPath.slice(sourcePath.length)],
			guards
		});
	};
	const visitSelectValue = (value, path, guards) => {
		if (value instanceof require_ir.PropRef && pathStartsWith(targetPath, value.path)) {
			resultPaths.push({
				path: [...path, ...targetPath.slice(value.path.length)],
				guards
			});
			return;
		}
		if (value instanceof require_ir.ConditionalSelect) {
			visitConditionalSelect(value, guards, (child, childGuards) => visitSelectValue(child, path, childGuards));
			return;
		}
		if (isNestedSelectObject(value)) visitSelectObject(value, path, guards);
	};
	visitSelectObject(select, [], []);
	return resultPaths;
}
function pathStartsWith(path, prefix) {
	return prefix.length <= path.length && prefix.every((part, i) => path[i] === part);
}
function mapNestedFromQueries(optimizedFrom, originalFrom, queryMapping) {
	if (optimizedFrom.type === `unionAll` && originalFrom.type === `unionAll`) {
		for (let i = 0; i < optimizedFrom.queries.length && i < originalFrom.queries.length; i++) {
			const optimizedBranch = optimizedFrom.queries[i];
			const originalBranch = originalFrom.queries[i];
			queryMapping.set(optimizedBranch, originalBranch);
			mapNestedQueries(optimizedBranch, originalBranch, queryMapping);
		}
		return;
	}
	const optimizedSources = require_ir.getFromSources(optimizedFrom);
	const originalSources = require_ir.getFromSources(originalFrom);
	for (let i = 0; i < optimizedSources.length && i < originalSources.length; i++) {
		const optimizedSource = optimizedSources[i];
		const originalSource = originalSources[i];
		if (optimizedSource.type === `queryRef` && originalSource.type === `queryRef`) {
			queryMapping.set(optimizedSource.query, originalSource.query);
			mapNestedQueries(optimizedSource.query, originalSource.query, queryMapping);
		}
	}
}
function extractIncludesFromSelect(select) {
	const results = [];
	for (const [key, value] of Object.entries(select)) {
		if (key.startsWith(`__SPREAD_SENTINEL__`)) continue;
		if (isNestedSelectObject(value)) assertNoNestedIncludes(value, key);
		else collectIncludesFromSelectValue(value, [key], [], results);
	}
	return results;
}
function visitConditionalSelect(conditional, guards, visit) {
	const previousBranchGuards = [];
	for (const branch of conditional.branches) {
		visit(branch.value, [
			...guards,
			...previousBranchGuards,
			{
				condition: branch.condition,
				expected: true
			}
		]);
		previousBranchGuards.push({
			condition: branch.condition,
			expected: false
		});
	}
	if (conditional.defaultValue !== void 0) visit(conditional.defaultValue, [...guards, ...previousBranchGuards]);
}
function collectIncludesFromSelectValue(value, prefixPath, guards, results) {
	if (value instanceof require_ir.IncludesSubquery) {
		const key = getUniqueIncludesRoutingKey(prefixPath.join(`.`), results);
		results.push({
			key,
			path: prefixPath,
			subquery: value,
			guards
		});
		return;
	}
	if (value instanceof require_ir.ConditionalSelect) {
		visitConditionalSelect(value, guards, (child, childGuards) => collectIncludesFromSelectValue(child, prefixPath, childGuards, results));
		return;
	}
	if (!isNestedSelectObject(value)) return;
	for (const [key, child] of Object.entries(value)) {
		if (key.startsWith(`__SPREAD_SENTINEL__`)) continue;
		collectIncludesFromSelectValue(child, [...prefixPath, key], guards, results);
	}
}
function getUniqueIncludesRoutingKey(baseKey, entries) {
	const taken = new Set(entries.map((entry) => entry.key ?? entry.fieldName));
	if (!taken.has(baseKey)) return baseKey;
	let suffix = entries.length;
	while (taken.has(`${baseKey}#${suffix}`)) suffix++;
	return `${baseKey}#${suffix}`;
}
function isNestedSelectObject(value) {
	return value != null && typeof value === `object` && !Array.isArray(value) && !require_ir.isExpressionLike(value) && !require_ref_proxy_identity.isRefProxy(value);
}
function assertNoNestedIncludes(obj, parentPath) {
	for (const [key, value] of Object.entries(obj)) {
		if (key.startsWith(`__SPREAD_SENTINEL__`)) continue;
		if (value instanceof require_ir.IncludesSubquery) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `Includes subqueries must be at the top level of select(). Found nested includes at "${parentPath}.${key}".` : require_error_message.codedMessage(133, {
			parentPath,
			key
		}));
		if (isNestedSelectObject(value)) assertNoNestedIncludes(value, `${parentPath}.${key}`);
	}
}
function replaceIncludesInSelectValue(value, path) {
	if (path.length === 0 && value instanceof require_ir.IncludesSubquery) return new require_ir.Value(null);
	if (value instanceof require_ir.ConditionalSelect) {
		const branches = value.branches.map((branch) => {
			const next2 = replaceIncludesInSelectValue(branch.value, path);
			return Object.is(next2, branch.value) ? branch : {
				...branch,
				value: next2
			};
		});
		const defaultValue = value.defaultValue === void 0 ? void 0 : replaceIncludesInSelectValue(value.defaultValue, path);
		return branches.some((branch, index) => branch !== value.branches[index]) || !Object.is(defaultValue, value.defaultValue) ? new require_ir.ConditionalSelect(branches, defaultValue) : value;
	}
	if (path.length === 0 || !isNestedSelectObject(value)) return value;
	const [head, ...rest] = path;
	const child = value[head];
	const next = replaceIncludesInSelectValue(child, rest);
	return Object.is(next, child) ? value : {
		...value,
		[head]: next
	};
}
function getNestedValue(obj, path) {
	let value = obj;
	for (const segment of path) {
		if (value == null) return value;
		value = value[segment];
	}
	return value;
}
var ignoreWindow = () => {};
function readRouteTag(value, fieldName) {
	return value?.[require_route_metadata.INCLUDES_ROUTING]?.[fieldName];
}
function windowRoute(row, fieldName) {
	const routing = readRouteTag(row.$selected, fieldName);
	if (!routing) throw new Error(/* @__PURE__ */ require_error_message.devBuild() && process.env.NODE_ENV !== `production` ? `A windowed or findOne result row has no include route` : require_error_message.codedMessage(243));
	return routing;
}
function compileGuardedRouting(guards, resolve) {
	const compiledGuards = guards.map((guard) => ({
		condition: require_evaluators.compileExpression(guard.condition),
		expected: guard.expected
	}));
	return (nsRow) => {
		return (compiledGuards.every((guard) => require_evaluators.isCaseWhenConditionTrue(guard.condition(nsRow)) === guard.expected) ? resolve(nsRow) : void 0) ?? {
			active: false,
			correlationKey: null,
			parentContext: null
		};
	};
}
function getStaticDemandKeys(query, ref) {
	const constraints = [];
	const visit = (expression) => {
		if (expression.type !== `func`) return;
		if (expression.name === `and`) {
			expression.args.forEach(visit);
			return;
		}
		if (expression.name !== `eq` && expression.name !== `in`) return;
		const [left, right] = expression.args;
		const value = left?.type === `ref` && pathsEqual(left.path, ref.path) && right instanceof require_ir.Value ? right.value : right?.type === `ref` && pathsEqual(right.path, ref.path) && left instanceof require_ir.Value ? left.value : void 0;
		if (value === void 0) return;
		constraints.push(new Set(Array.isArray(value) ? value : [value]));
	};
	query.where?.forEach((where) => visit(require_ir.getWhereExpression(where)));
	if (constraints.length === 0) return /* @__PURE__ */ new Set();
	return new Set([...constraints[0]].filter((value) => constraints.slice(1).every((constraint) => constraint.has(value))));
}
function pathsEqual(left, right) {
	return left.length === right.length && left.every((segment, index) => segment === right[index]);
}
exports.compileCollectionQuery = compileCollectionQuery;
exports.compileQuery = compileQuery;
exports.validateFnSelectResult = validateFnSelectResult;

//# sourceMappingURL=index.cjs.map