UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

1 lines • 116 kB
{"version":3,"file":"index.cjs","names":["IncludeWrapper","BaseQueryBuilder","ToArrayWrapper","ConcatToArrayWrapper","MaterializeWrapper","CaseWhenWrapper","isExpressionLike","UnsupportedFnSelectResultError","getRouteMetadata","getParentContextValue","getParentContextProjectedBindings","createParentContext","getParentContextIdentity","crossJoinParentRoutes","INCLUDES_PUBLIC_KEY","serializeValue","normalizeValue","getOrCreate","createValueIdentity","collectCollectionSources","optimizeQuery","createSourceRecord","map","reduce","joinOperator","filter","attachRouteMetadata","processJoins","compileExpression","getNamespacedRouteMetadata","getWhereExpression","toBooleanPredicate","stripInternalCallbackMetadata","getSourceRouting","findAggregate","NonAggregateExpressionNotInGroupByError","IncludeOperatorRequiredError","getLazyLoadTargets","registerLazyDemandPlan","tap","DistinctRequiresSelectError","FnSelectWithGroupByError","codedMessage","INCLUDES_ROUTING","isPublicContainer","processSelect","getRoutedScalarMetadata","GroupingOperatorRequiredError","HavingRequiresGroupByError","distinct","getSourceMetadata","ROW_METADATA","stripInternalRouteMetadata","LimitOffsetRequireOrderByError","processOrderBy","deepEquals","collectPropRefs","QueryCompilationError","IncludesSubquery","isBasicOrAggregateExpression","ConditionalSelect","getFromSources","getHavingExpression","collectExternalRefsFromQuery","processSource","UnsupportedFromTypeError","concatOperator","attachRouteMetadataToResult","wrapInputRow","ValClass","PropRef","isPlainObject","VIRTUAL_PROP_NAMES","isRefProxy","isCaseWhenConditionTrue","sourceIncludes","next"],"sources":["../../../../src/query/compiler/index.ts"],"sourcesContent":["import {\n  concat as concatOperator,\n  distinct,\n  filter,\n  join as joinOperator,\n  map,\n  reduce,\n  serializeValue,\n  tap,\n} from '@tanstack/db-ivm'\nimport { isPlainObject } from '../../utils/type-guards.js'\nimport { getOrCreate } from '../../utils/get-or-create.js'\nimport { optimizeQuery } from '../optimizer.js'\nimport {\n  createParentContext,\n  createValueIdentity,\n  getParentContextIdentity,\n  getParentContextProjectedBindings,\n  getParentContextValue,\n} from '../equality-value-identity.js'\nimport {\n  DistinctRequiresSelectError,\n  FnSelectWithGroupByError,\n  GroupingOperatorRequiredError,\n  HavingRequiresGroupByError,\n  IncludeOperatorRequiredError,\n  LimitOffsetRequireOrderByError,\n  NonAggregateExpressionNotInGroupByError,\n  QueryCompilationError,\n  UnsupportedFnSelectResultError,\n  UnsupportedFromTypeError,\n} from '../../errors.js'\nimport { VIRTUAL_PROP_NAMES } from '../../virtual-props.js'\nimport {\n  BaseQueryBuilder,\n  collectExternalRefsFromQuery,\n} from '../builder/index.js'\nimport { isRefProxy } from '../builder/ref-proxy-identity.js'\nimport {\n  CaseWhenWrapper,\n  ConcatToArrayWrapper,\n  IncludeWrapper,\n  MaterializeWrapper,\n  ToArrayWrapper,\n} from '../builder/functions.js'\nimport {\n  ConditionalSelect,\n  IncludesSubquery,\n  PropRef,\n  Value as ValClass,\n  collectCollectionSources,\n  collectPropRefs,\n  getFromSources,\n  getHavingExpression,\n  getWhereExpression,\n  isBasicOrAggregateExpression,\n  isExpressionLike,\n} from '../ir.js'\nimport { ensureIndexForField } from '../../indexes/auto-index.js'\nimport { createSourceRecord } from '../../utils/source-record.js'\nimport { deepEquals } from '../../utils.js'\nimport { normalizeValue } from '../../utils/comparison.js'\nimport { codedMessage, devBuild } from '../../error-message.js'\nimport {\n  compileExpression,\n  isCaseWhenConditionTrue,\n  toBooleanPredicate,\n} from './evaluators.js'\nimport { processJoins, processSource, registerLazyDemandPlan } from './joins.js'\nimport { findAggregate } from './find-aggregate.js'\nimport { getLazyLoadTargets } from './lazy-targets.js'\nimport { processOrderBy } from './order-by.js'\nimport { crossJoinParentRoutes } from './parent-routes.js'\nimport {\n  INCLUDES_PUBLIC_KEY,\n  INCLUDES_ROUTING,\n  ROW_METADATA,\n  attachRouteMetadata,\n  attachRouteMetadataToResult,\n  getNamespacedRouteMetadata,\n  getRouteMetadata,\n  getRoutedScalarMetadata,\n  getSourceMetadata,\n  getSourceRouting,\n  isPublicContainer,\n  restoreInternalRouteMetadata,\n  stripInternalCallbackMetadata,\n  stripInternalRouteMetadata,\n  wrapInputRow,\n} from './route-metadata.js'\nimport { processSelect } from './select.js'\nimport type { RowMetadata } from './route-metadata.js'\nimport type { ValueIdentity } from '../equality-value-identity.js'\nimport type { IncludesRuntime } from '../live/includes-runtime.js'\nimport type { CollectionSubscription } from '../../collection/subscription.js'\nimport type { OrderByOptimizationInfo } from './order-by.js'\nimport type {\n  Aggregate,\n  BasicExpression,\n  CollectionRef,\n  CollectionSourceRef,\n  From,\n  IncludesMaterialization,\n  QueryIR,\n  QueryRef,\n  UnionAll,\n} from '../ir.js'\nimport type { LazyCollectionCallbacks } from './joins.js'\nimport type { IStreamBuilder, KeyValue, MultiSet } from '@tanstack/db-ivm'\nimport type { Collection } from '../../collection/index.js'\nimport type {\n  InputRow,\n  KeyedStream,\n  NamespacedAndKeyedStream,\n  NamespacedRow,\n  ResultStream,\n} from '../../types.js'\nimport type { QueryCache, QueryMapping, WindowOptions } from './types.js'\n\nexport type { WindowOptions } from './types.js'\nexport { INCLUDES_PUBLIC_KEY, INCLUDES_ROUTING } from './route-metadata.js'\n\nfunction getUnsupportedFnSelectResultDescription(\n  value: unknown,\n  seen: Set<object> = new Set(),\n): string | undefined {\n  if (value instanceof IncludeWrapper) return `include()`\n  if (value instanceof BaseQueryBuilder) return `a child query builder`\n  if (value instanceof ToArrayWrapper) return `toArray()`\n  if (value instanceof ConcatToArrayWrapper) return `concat(toArray())`\n  if (value instanceof MaterializeWrapper) return `materialize()`\n  if (value instanceof CaseWhenWrapper) return `caseWhen()`\n  if (isExpressionLike(value)) {\n    return value &&\n      typeof value === `object` &&\n      `name` in value &&\n      typeof value.name === `string`\n      ? `${value.name}()`\n      : `a query expression`\n  }\n  if (value === null || typeof value !== `object` || seen.has(value)) {\n    return undefined\n  }\n\n  seen.add(value)\n  const keys = Reflect.ownKeys(value).filter((key) =>\n    Object.prototype.propertyIsEnumerable.call(value, key),\n  )\n  for (const key of keys) {\n    const entry = (value as Record<PropertyKey, unknown>)[key]\n    const unsupported = getUnsupportedFnSelectResultDescription(entry, seen)\n    if (unsupported) return unsupported\n  }\n  return undefined\n}\n\nexport function validateFnSelectResult(value: unknown): void {\n  const unsupportedValueDescription =\n    getUnsupportedFnSelectResultDescription(value)\n  if (unsupportedValueDescription) {\n    throw new UnsupportedFnSelectResultError(unsupportedValueDescription)\n  }\n}\n\ntype ConditionalSelectGuard = {\n  condition: BasicExpression\n  expected: boolean\n}\n\nexport type SourceInclude = {\n  sourceAlias: string\n  include: IncludesCompilationResult\n}\n\ntype ProjectedSourceIncludePath = {\n  path: Array<string>\n  guards: Array<ConditionalSelectGuard>\n}\n\ntype CompiledParentProjection = {\n  alias: string\n  field: Array<string>\n  bindingKey?: string\n  compiled: (row: NamespacedRow) => unknown\n}\n\nfunction projectParentContext(\n  nsRow: NamespacedRow,\n  projections: Array<CompiledParentProjection>,\n  valueIdentity: ValueIdentity,\n): Record<string, any> {\n  const inherited = getRouteMetadata(nsRow)?.parentContext\n  const parentContext: Record<string, any> = {\n    ...getParentContextValue(inherited),\n  }\n  const projectedBindings = {\n    ...getParentContextProjectedBindings(inherited),\n  }\n  const projectedIdentity: Array<unknown> = []\n\n  for (const projection of projections) {\n    const projectedValue = projection.compiled(nsRow)\n    projectedIdentity.push([\n      projection.alias,\n      projection.bindingKey,\n      projection.field,\n      valueIdentity.equality(projectedValue),\n    ])\n    if (projection.bindingKey !== undefined) {\n      projectedBindings[projection.bindingKey] = projectedValue\n    }\n    if (projection.field.length === 0) {\n      const projectedAlias = projectedValue\n      parentContext[projection.alias] =\n        projectedAlias != null && typeof projectedAlias === `object`\n          ? { ...projectedAlias }\n          : projectedAlias\n      continue\n    }\n\n    const inheritedAlias = parentContext[projection.alias]\n    const aliasContext =\n      inheritedAlias != null && typeof inheritedAlias === `object`\n        ? { ...inheritedAlias }\n        : {}\n    parentContext[projection.alias] = aliasContext\n\n    let target = aliasContext\n    for (let index = 0; index < projection.field.length - 1; index++) {\n      const segment = projection.field[index]!\n      const inheritedNested = target[segment]\n      const nested =\n        inheritedNested != null && typeof inheritedNested === `object`\n          ? { ...inheritedNested }\n          : {}\n      target[segment] = nested\n      target = nested\n    }\n    target[projection.field[projection.field.length - 1]!] = projectedValue\n  }\n\n  return createParentContext(\n    parentContext,\n    [getParentContextIdentity(inherited), projectedIdentity],\n    projectedBindings,\n  )\n}\n\nfunction parameterizeByParentRoutes(\n  pipeline: NamespacedAndKeyedStream,\n  parentKeyStream: KeyedStream,\n  valueIdentity: ValueIdentity,\n): NamespacedAndKeyedStream {\n  return crossJoinParentRoutes(\n    pipeline,\n    parentKeyStream,\n    (rowKey, row, correlationKey, parentContext) => {\n      const namespaced = {\n        ...getParentContextValue(parentContext),\n        ...(row as Record<string, unknown>),\n      } as Record<PropertyKey, unknown>\n      namespaced[INCLUDES_PUBLIC_KEY] =\n        namespaced[INCLUDES_PUBLIC_KEY] ?? rowKey\n      attachRouteMetadata(namespaced, correlationKey, parentContext)\n      return [\n        serializeValue([\n          valueIdentity.equality(rowKey),\n          valueIdentity.equality(correlationKey),\n          getParentContextIdentity(parentContext),\n        ]),\n        namespaced,\n      ] as [string, NamespacedRow]\n    },\n  ) as NamespacedAndKeyedStream\n}\n\nfunction correlationValuesEqual(left: unknown, right: unknown): boolean {\n  if (left == null || right == null) return false\n  const normalizedLeft = normalizeValue(left)\n  const normalizedRight = normalizeValue(right)\n  return Object.is(normalizedLeft, normalizedRight)\n}\n\n/**\n * Result of compiling an includes subquery, including the child pipeline\n * and metadata needed to route child results to parent-scoped Collections.\n */\nexport interface IncludesCompilationResult {\n  /** Filtered child pipeline (post inner-join with parent keys) */\n  pipeline: ResultStream\n  /** Result field name on parent (e.g., \"issues\") */\n  fieldName: string\n  /** Path where the included value is written in the parent result */\n  resultPath: Array<string>\n  /** Parent-side correlation ref (e.g., project.id) */\n  correlationField: PropRef\n  /** Child-side correlation ref (e.g., issue.projectId) */\n  childCorrelationField: PropRef\n  /** Whether the child query has an ORDER BY clause */\n  hasOrderBy: boolean\n  /** Full compilation result for the child query (for nested includes + alias tracking) */\n  childCompilationResult: CompilationResult\n  /** Parent-side projection refs for parent-referencing filters */\n  parentProjection?: Array<PropRef>\n  /** How the output layer materializes the child result on the parent row */\n  materialization: IncludesMaterialization\n  /** Internal field used to unwrap scalar child selects */\n  scalarField?: string\n  /** The materializer the include value brought */\n  runtime: IncludesRuntime\n}\n\n/**\n * Result of query compilation including both the pipeline and source-specific WHERE clauses\n */\nexport interface CompilationResult {\n  /** The ID of the main collection */\n  collectionId: string\n\n  /** The compiled query pipeline (D2 stream) */\n  pipeline: ResultStream\n\n  /** Runtime identity scope owned by this compiled graph. */\n  valueIdentity: ValueIdentity\n\n  /** Map of opaque source IDs to their WHERE clauses for index optimization */\n  sourceWhereClauses: Map<string, BasicExpression<boolean>>\n\n  /**\n   * Maps FROM and JOIN source aliases to collection IDs within this compiled\n   * query. Includes keep their own alias maps in their child results.\n   * Enables per-alias subscriptions for self-joins.\n   * Example: `{ employee: 'employees-col-id', manager: 'employees-col-id' }`\n   */\n  aliasToCollectionId: Record<string, string>\n\n  /**\n   * Flattened mapping from outer alias to innermost alias for subqueries.\n   * Always provides one-hop lookups, never recursive chains.\n   *\n   * Example: `{ activeUser: 'user' }` when `.from({ activeUser: subquery })`\n   * where the subquery uses `.from({ user: collection })`.\n   *\n   * For deeply nested subqueries, the mapping goes directly to the innermost alias:\n   * `{ author: 'user' }` (not `{ author: 'activeUser' }`), so `aliasRemapping[alias]`\n   * always resolves in a single lookup.\n   *\n   * Used to resolve subscriptions during lazy loading when join aliases differ from\n   * the inner aliases where collection subscriptions were created.\n   */\n  aliasRemapping: Record<string, string>\n\n  /** Child pipelines for includes subqueries */\n  includes?: Array<IncludesCompilationResult>\n}\n\nconst valueIdentitiesByCache = new WeakMap<QueryCache, ValueIdentity>()\n\nfunction getCompilationValueIdentity(cache: QueryCache): ValueIdentity {\n  return getOrCreate(valueIdentitiesByCache, cache, createValueIdentity)\n}\n\n/**\n * Compiles a query IR into a D2 pipeline\n * @param rawQuery The query IR to compile\n * @param inputs Mapping of source aliases to input streams (e.g., `{ employee: input1, manager: input2 }`)\n * @param collections Mapping of collection IDs to Collection instances\n * @param subscriptions Mapping of source aliases to CollectionSubscription instances\n * @param callbacks Mapping of source aliases to lazy loading callbacks\n * @param lazySources Set of source identities that should load data lazily\n * @param optimizableOrderByCollections Map of source IDs to order-by optimization info\n * @param cache Optional cache for compiled subqueries (used internally for recursion)\n * @param queryMapping Optional lineage from optimized queries to user-defined queries\n * @returns A CompilationResult with the pipeline, source WHERE clauses, and alias metadata\n */\ntype CompileQueryArgs = [\n  rawQuery: QueryIR,\n  inputs: Record<string, KeyedStream>,\n  collections: Record<string, Collection<any, any, any, any, any>>,\n  subscriptions: Record<string, CollectionSubscription>,\n  callbacks: Record<string, LazyCollectionCallbacks>,\n  lazySources: Set<string>,\n  optimizableOrderByCollections: Record<string, OrderByOptimizationInfo>,\n  setWindowFn: (windowFn: (options: WindowOptions) => void) => void,\n  cache?: QueryCache,\n  queryMapping?: QueryMapping,\n  parentKeyStream?: KeyedStream,\n  childCorrelationField?: PropRef,\n  // An enclosing windowed query or findOne can drop this include's parents.\n  ancestorHasTopK?: boolean,\n]\n\nexport function compileQuery(...args: CompileQueryArgs): CompilationResult {\n  return compileQueryInternal(args, false)\n}\n\nexport function compileCollectionQuery(\n  ...args: CompileQueryArgs\n): CompilationResult {\n  return compileQueryInternal(args, false, true)\n}\n\nfunction compileQueryInternal(\n  [\n    rawQuery,\n    inputs,\n    collections,\n    subscriptions,\n    callbacks,\n    lazySources,\n    optimizableOrderByCollections,\n    setWindowFn,\n    cache = new WeakMap(),\n    queryMapping = new WeakMap(),\n    parentKeyStream,\n    childCorrelationField,\n    ancestorHasTopK = false,\n  ]: CompileQueryArgs,\n  scopeValidated: boolean,\n  isCollectionRoot = false,\n): CompilationResult {\n  // Publication changes metadata. A separately compiled authored root also\n  // owns its movable top-K; reusing it as a source would couple the windows.\n  const cacheSlot = isCollectionRoot ? 1 : scopeValidated ? 2 : 0\n  const cachedResult =\n    parentKeyStream === undefined ? cache.get(rawQuery)?.[cacheSlot] : undefined\n  if (cachedResult) {\n    return cachedResult\n  }\n  const valueIdentity = getCompilationValueIdentity(cache)\n\n  // Validate the raw query BEFORE optimization to check user's original structure.\n  // This must happen before optimization because the optimizer may create internal\n  // subqueries (e.g., for predicate pushdown) that reuse aliases, which is fine.\n  if (!scopeValidated) validateQueryStructure(rawQuery)\n  const rawSources = collectCollectionSources(rawQuery)\n\n  // Optimize the query before compilation\n  const { optimizedQuery, sourceWhereClauses: aliasWhereClauses } =\n    optimizeQuery(rawQuery)\n  const sourceWhereClauses = keyWhereClausesBySource(\n    rawQuery,\n    aliasWhereClauses,\n  )\n  // Use a mutable binding so we can shallow-clone select before includes mutation\n  let query = optimizedQuery\n\n  // Create mapping from optimized query to original for caching\n  queryMapping.set(query, rawQuery)\n  mapNestedQueries(query, rawQuery, queryMapping)\n\n  // Create a copy of the inputs map to avoid modifying the original\n  const allInputs = Object.assign(createSourceRecord<KeyedStream>(), inputs)\n  bindSourceInputs(rawSources, allInputs)\n\n  // Track alias to collection id relationships discovered during compilation.\n  // This includes all user-declared aliases plus inner aliases from subqueries.\n  const aliasToCollectionId: Record<string, string> = {}\n\n  // Track alias remapping for subqueries (outer alias → inner alias)\n  // e.g., when .join({ activeUser: subquery }) where subquery uses .from({ user: collection })\n  // we store: aliasRemapping['activeUser'] = 'user'\n  const aliasRemapping: Record<string, string> = {}\n\n  // Create a map of source aliases to input streams.\n  // Inputs MUST be keyed by alias (e.g., `{ employee: input1, manager: input2 }`),\n  // not by collection ID. This enables per-alias subscriptions where different aliases\n  // of the same collection (e.g., self-joins) maintain independent filtered streams.\n  const sources: Record<string, KeyedStream> = {}\n\n  // Process the FROM clause to get the source stream.\n  const {\n    alias: mainSource,\n    collectionId: mainCollectionId,\n    pipeline: initialPipeline,\n    sources: fromSources,\n    sourceIncludes,\n    directIncludes,\n    isUnionFrom,\n    isParentRouted,\n  } = processFromClause(\n    query.from,\n    allInputs,\n    collections,\n    subscriptions,\n    callbacks,\n    lazySources,\n    optimizableOrderByCollections,\n    ignoreWindow,\n    cache,\n    queryMapping,\n    aliasToCollectionId,\n    aliasRemapping,\n    sourceWhereClauses,\n    parentKeyStream,\n  )\n  Object.assign(sources, fromSources)\n  const sourceCarriesInternalRouteState =\n    parentKeyStream !== undefined ||\n    sourceIncludes.length > 0 ||\n    directIncludes.length > 0\n\n  // If this is an includes child query, inner-join the raw input with parent keys.\n  // This filters the child collection to only rows matching parents in the result set.\n  // The inner join happens BEFORE namespace wrapping / WHERE / SELECT / ORDER BY,\n  // so the child pipeline only processes rows that match parents.\n  let pipeline: NamespacedAndKeyedStream = initialPipeline\n  const childCorrelationAlias = childCorrelationField?.path[0]\n  const joinsParentDirectly =\n    !isUnionFrom &&\n    !isParentRouted &&\n    parentKeyStream !== undefined &&\n    childCorrelationField !== undefined &&\n    childCorrelationAlias === mainSource\n  if (parentKeyStream && childCorrelationField && joinsParentDirectly) {\n    const mainInput = sources[mainSource]!\n    let filteredMainInput = mainInput\n    // Join on query equality rather than raw JavaScript identity. Keep the raw\n    // child value beside the row so result routing can still expose it.\n    const childFieldPath = childCorrelationField.path.slice(1) // remove alias prefix\n    const childRekeyed = mainInput.pipe(\n      map(([key, row, metadata]: [...InputRow, unknown?]) => {\n        const correlationValue = getNestedValue(row, childFieldPath)\n        return [\n          valueIdentity.serializeEquality(correlationValue),\n          [key, row, correlationValue, metadata],\n        ] as [unknown, [unknown, any, unknown, unknown?]]\n      }),\n    )\n\n    const equalityParentKeys = parentKeyStream.pipe(\n      map(([correlationValue, parentContext]: [unknown, unknown]) => [\n        valueIdentity.serializeEquality(correlationValue),\n        parentContext,\n      ]),\n      reduce((values: Array<[unknown, number]>) =>\n        values.map(([value, multiplicity]) => [\n          value,\n          multiplicity > 0 ? 1 : 0,\n        ]),\n      ),\n    )\n\n    // Inner join: only children whose correlation key exists in parent keys pass through\n    const joined = childRekeyed.pipe(joinOperator(equalityParentKeys, `inner`))\n\n    // Extract: [correlationValue, [[childKey, childRow], parentContext]] → [childKey, childRow]\n    // Keep routing metadata outside the user-visible row namespace.\n    filteredMainInput = joined.pipe(\n      filter(([_correlationValue, [childSide]]: any) => {\n        return childSide != null\n      }),\n      map(([_correlationIdentity, [childSide, parentSide]]: any) => {\n        const [childKey, childRow, correlationValue, metadata] = childSide\n        const tagged: any = attachRouteMetadata(\n          {\n            ...childRow,\n            [INCLUDES_PUBLIC_KEY]: childKey,\n          },\n          correlationValue,\n          parentSide,\n        )\n        const effectiveKey =\n          parentSide != null\n            ? serializeValue([\n                valueIdentity.equality(childKey),\n                getParentContextIdentity(parentSide),\n              ])\n            : childKey\n        return [effectiveKey, tagged, metadata] as unknown as InputRow\n      }),\n    )\n\n    // Update sources so the rest of the pipeline uses the filtered input\n    sources[mainSource] = filteredMainInput\n\n    pipeline = wrapInputWithAlias(filteredMainInput, mainSource)\n  } else if (parentKeyStream && !isParentRouted) {\n    // QueryRefs, unions, and joined-source correlations need the route before\n    // source-local joins, filters, grouping, ordering, or windows run.\n    pipeline = parameterizeByParentRoutes(\n      initialPipeline,\n      parentKeyStream,\n      valueIdentity,\n    )\n  }\n\n  // Process JOIN clauses if they exist\n  if (query.join && query.join.length > 0) {\n    pipeline = processJoins(\n      pipeline,\n      query.join,\n      sources,\n      mainCollectionId,\n      mainSource,\n      allInputs,\n      queryMapping,\n      collections,\n      callbacks,\n      lazySources,\n      rawQuery,\n      query.from,\n      (subquery, parentRoutes) =>\n        compileQueryInternal(\n          [\n            subquery,\n            allInputs,\n            collections,\n            subscriptions,\n            callbacks,\n            lazySources,\n            optimizableOrderByCollections,\n            ignoreWindow,\n            cache,\n            queryMapping,\n            parentRoutes,\n          ],\n          true,\n          false,\n        ),\n      aliasToCollectionId,\n      aliasRemapping,\n      sourceWhereClauses,\n      joinsParentDirectly,\n      valueIdentity,\n      sourceIncludes,\n      parentKeyStream,\n    )\n  }\n\n  // A RIGHT or FULL join can add a row without the main source after that\n  // source was filtered by parent keys. Check the correlation again once the\n  // joined row is visible; a missing main-side correlation cannot join a route.\n  const canLoseMainSide = query.join?.some(\n    ({ type }) => type === `right` || type === `full`,\n  )\n  if (\n    parentKeyStream &&\n    childCorrelationField &&\n    (!joinsParentDirectly || canLoseMainSide)\n  ) {\n    const compiledChildCorrelation = compileExpression(childCorrelationField)\n    pipeline = pipeline.pipe(\n      filter(([, row]) =>\n        correlationValuesEqual(\n          compiledChildCorrelation(row),\n          getNamespacedRouteMetadata(row, mainSource)?.correlationKey,\n        ),\n      ),\n    ) as NamespacedAndKeyedStream\n  }\n\n  // Process the WHERE clause if it exists\n  if (query.where && query.where.length > 0) {\n    // Apply each WHERE condition as a filter (they are ANDed together)\n    for (const where of query.where) {\n      const whereExpression = getWhereExpression(where)\n      const compiledWhere = compileExpression(whereExpression)\n      pipeline = pipeline.pipe(\n        filter(([_key, namespacedRow]) => {\n          return toBooleanPredicate(compiledWhere(namespacedRow))\n        }),\n      )\n    }\n  }\n\n  // Process functional WHERE clauses if they exist\n  if (query.fnWhere && query.fnWhere.length > 0) {\n    for (const fnWhere of query.fnWhere) {\n      pipeline = pipeline.pipe(\n        filter(([_key, namespacedRow]) => {\n          const callbackRow = stripInternalCallbackMetadata(\n            namespacedRow,\n          ) as NamespacedRow\n          return toBooleanPredicate(fnWhere(callbackRow))\n        }),\n      )\n    }\n  }\n\n  // Extract includes from SELECT, compile child pipelines, and replace with placeholders.\n  // This must happen AFTER WHERE (so parent pipeline is filtered) but BEFORE processSelect\n  // (so IncludesSubquery nodes are stripped before select compilation).\n  const inputIncludes = [\n    ...directIncludes,\n    ...sourceIncludes.map(({ include }) => include),\n  ]\n  const materializeSelectInput = !!query.fnSelect && inputIncludes.length > 0\n  let includesResults: Array<IncludesCompilationResult> = !query.select\n    ? [...directIncludes]\n    : []\n  let includesRoutingFns: Array<{\n    fieldName: string\n    getRouting: (nsRow: any) => IncludeRouting\n  }> = []\n  // Includes inherited from a source or a QueryRef route by the tag their\n  // compiled rows already carry, at each path the select projects them to.\n  const inheritedIncludes = [\n    ...sourceIncludes.map(({ sourceAlias, include }) => ({\n      include,\n      keyPrefix: `${sourceAlias}.`,\n      paths:\n        query.select != null\n          ? findProjectedIncludePaths(query.select, [\n              sourceAlias,\n              ...include.resultPath,\n            ])\n          : query.fnSelect && !materializeSelectInput\n            ? []\n            : [{ path: [sourceAlias, ...include.resultPath], guards: [] }],\n      route: (nsRow: NamespacedRow) =>\n        (\n          getSourceRouting(nsRow, sourceAlias) as\n            Record<string, any> | undefined\n        )?.[include.fieldName],\n    })),\n    ...(query.select ? directIncludes : []).map((include) => ({\n      include,\n      keyPrefix: ``,\n      paths: findProjectedIncludePaths(query.select!, include.resultPath),\n      route: (nsRow: NamespacedRow) => readRouteTag(nsRow, include.fieldName),\n    })),\n  ]\n  for (const { include, keyPrefix, paths, route } of inheritedIncludes) {\n    for (const { path: resultPath, guards } of paths) {\n      const fieldName = getUniqueIncludesRoutingKey(\n        keyPrefix + resultPath.join(`.`),\n        includesRoutingFns,\n      )\n      includesResults.push({ ...include, fieldName, resultPath })\n      includesRoutingFns.push({\n        fieldName,\n        getRouting: compileGuardedRouting(guards, route),\n      })\n    }\n  }\n  // One walker finds aggregates; the aggregate it finds carries the grouping\n  // compiler.\n  const selectAggregate = findAggregate(query.select)\n  const selectHasAggregates = selectAggregate !== undefined\n  // A windowed query's or a findOne's includes compile after its top-K and\n  // route only from the rows it shows (law 12); others compile here.\n  const hasOrderBy = (query.orderBy?.length ?? 0) > 0\n  const parentHasTopK = hasOrderBy || !!query.singleResult\n  const deferredIncludes: Array<(windowRows: WindowRows) => void> = []\n  if (query.select) {\n    const includesEntries = extractIncludesFromSelect(query.select)\n    // A nested include has one Collection per row, not one value per group,\n    // so it cannot sit in a grouped or aggregate select.\n    if (\n      includesEntries.length > 0 &&\n      ((query.groupBy?.length ?? 0) > 0 || selectHasAggregates)\n    )\n      throw new NonAggregateExpressionNotInGroupByError(\n        includesEntries[0]!.path.join(`.`),\n      )\n    if (includesEntries.length > 0) {\n      query = { ...query, select: { ...query.select } }\n    }\n    for (const { key, path, subquery, guards } of includesEntries) {\n      // Query IR built by hand must carry the runtime its include needs.\n      const runtime = subquery.runtime as Partial<IncludesRuntime> | undefined\n      if (typeof runtime?.materializeCompilation !== `function`)\n        throw new IncludeOperatorRequiredError(key)\n      const fieldName = getUniqueIncludesRoutingKey(key, includesRoutingFns)\n      // Branch parent pipeline: map to [correlationValue, parentContext]\n      // When parentProjection exists, project referenced parent fields; otherwise null (zero overhead)\n      const compiledCorrelation = compileExpression(subquery.correlationField)\n      const compiledProjections: Array<CompiledParentProjection> =\n        subquery.parentProjection?.map((ref) => ({\n          alias: ref.path[0]!,\n          field: ref.path.slice(1),\n          bindingKey: ref.bindingId\n            ? JSON.stringify([ref.bindingId, ref.path.slice(1)])\n            : undefined,\n          compiled: compileExpression(ref),\n        })) ?? []\n      // One routing function serves both the parent-key branch and the\n      // INCLUDES_ROUTING tag on $selected.\n      const getRouting = compileGuardedRouting(guards, (nsRow) => ({\n        active: true,\n        correlationKey: compiledCorrelation(nsRow),\n        parentContext:\n          compiledProjections.length > 0\n            ? projectParentContext(nsRow, compiledProjections, valueIdentity)\n            : null,\n      }))\n      const compileInclude = (windowRows?: WindowRows) => {\n        // A top-K result row carries the route its select tagged; reading it\n        // keeps the routes identical to the rows the query publishes.\n        const routes = windowRows\n          ? windowRows.pipe(map(([, [row]]) => windowRoute(row, fieldName)))\n          : pipeline.pipe(map(([, row]) => getRouting(row)))\n        // Deduplicate: when multiple parents share the same correlation key (and\n        // parentContext), clamp multiplicity to 1 so the inner join doesn't\n        // produce duplicate child entries that cause incorrect deletions.\n        let parentKeys: KeyedStream = routes.pipe(\n          filter((routing: IncludeRouting) => routing.active),\n          // A parent key may carry no parent context (null).\n          map(\n            (routing) =>\n              [routing.correlationKey, routing.parentContext] as InputRow,\n          ),\n          reduce((values) =>\n            values.map(\n              ([v, mult]) => [v, mult > 0 ? 1 : 0] as [typeof v, number],\n            ),\n          ),\n        )\n\n        // --- Includes lazy loading (mirrors join lazy loading in joins.ts) ---\n        // Resolve the child correlation field to concrete collection targets so\n        // subquery and union child sources can load by branch when it is safe.\n        const childSourceAlias = subquery.childCorrelationField.path[0]!\n        const directChildCollection =\n          subquery.query.from.type === `collectionRef`\n            ? subquery.query.from.collection\n            : undefined\n        const lazyTargets = getLazyLoadTargets(\n          subquery.query,\n          subquery.query.from,\n          childSourceAlias,\n          subquery.childCorrelationField,\n          directChildCollection,\n          aliasRemapping,\n        )\n\n        if (lazyTargets.length > 0) {\n          // Mark each child source as lazy so CollectionSubscriber skips its\n          // initial full load, and index the correlation field for lookups.\n          for (const target of lazyTargets) {\n            lazySources.add(target.sourceId)\n            const targetFieldName = target.path[0]\n            if (targetFieldName) {\n              ensureIndexForField(\n                targetFieldName,\n                target.path,\n                target.collection,\n              )\n            }\n          }\n\n          // Static demand starts at once only when no top-K here or in an\n          // enclosing query can drop the rows it names: no window and no\n          // findOne, or a findOne showing one row for one named value.\n          const staticKeys = getStaticDemandKeys(\n            rawQuery,\n            subquery.correlationField,\n          )\n          const initialKeys =\n            !ancestorHasTopK &&\n            (!windowRows ||\n              (query.singleResult &&\n                query.offset === undefined &&\n                (query.limit ?? 1) > 0 &&\n                staticKeys.size === 1))\n              ? staticKeys\n              : new Set<unknown>()\n          const demandPlans = lazyTargets.map((target) =>\n            registerLazyDemandPlan(callbacks, target, initialKeys),\n          )\n          const demandWeights = new Map<\n            string,\n            { key: unknown; weight: number }\n          >()\n\n          // Keep the async demand adapter in sync with the current parent-key\n          // relation. Retired keys stop participating in readiness immediately.\n          parentKeys = parentKeys.pipe(\n            tap((data: MultiSet<InputRow>) => {\n              for (const [[correlationValue], weight] of data.getInner()) {\n                if (correlationValue == null) continue\n                const encoded =\n                  valueIdentity.serializeEquality(correlationValue)\n                const nextWeight =\n                  (demandWeights.get(encoded)?.weight ?? 0) + weight\n                if (nextWeight === 0) demandWeights.delete(encoded)\n                else\n                  demandWeights.set(encoded, {\n                    key: correlationValue,\n                    weight: nextWeight,\n                  })\n              }\n              const keys = new Set(\n                [...demandWeights.values()]\n                  .filter(({ weight }) => weight > 0)\n                  .map(({ key: demandedKey }) => demandedKey),\n              )\n              lazyTargets.forEach((target, index) =>\n                callbacks[target.sourceId]?.setDemand?.(\n                  demandPlans[index]!,\n                  keys,\n                ),\n              )\n            }),\n          )\n        }\n\n        // If parent filters exist, append them to the child query's WHERE\n        const childQuery =\n          subquery.parentFilters && subquery.parentFilters.length > 0\n            ? {\n                ...subquery.query,\n                where: [\n                  ...(subquery.query.where || []),\n                  ...subquery.parentFilters,\n                ],\n              }\n            : subquery.query\n\n        // Recursively compile child query WITH the parent key stream\n        const childResult = compileQueryInternal(\n          [\n            childQuery,\n            allInputs,\n            collections,\n            subscriptions,\n            callbacks,\n            lazySources,\n            optimizableOrderByCollections,\n            ignoreWindow,\n            cache,\n            queryMapping,\n            parentKeys,\n            subquery.childCorrelationField,\n            ancestorHasTopK || parentHasTopK,\n          ],\n          true,\n          subquery.materialization === `collection`,\n        )\n\n        // Each include retains its own compilation result and lexical aliases.\n        // Copying them into this scope would let a child shadow a source used by\n        // the enclosing query's lazy join.\n        for (const [alias, whereClause] of childResult.sourceWhereClauses) {\n          sourceWhereClauses.set(alias, whereClause)\n        }\n\n        includesResults.push({\n          pipeline: childResult.pipeline,\n          fieldName,\n          resultPath: path,\n          correlationField: subquery.correlationField,\n          childCorrelationField: subquery.childCorrelationField,\n          hasOrderBy: (subquery.query.orderBy?.length ?? 0) > 0,\n          childCompilationResult: childResult,\n          parentProjection: subquery.parentProjection,\n          materialization: subquery.materialization,\n          scalarField: subquery.scalarField,\n          runtime: subquery.runtime,\n        })\n      }\n      if (parentHasTopK) deferredIncludes.push(compileInclude)\n      else compileInclude()\n\n      includesRoutingFns.push({ fieldName, getRouting })\n\n      // Replace includes entry in select with a null placeholder\n      query = {\n        ...query,\n        select: replaceIncludesInSelectValue(query.select!, path),\n      }\n    }\n  }\n\n  if (\n    query.distinct &&\n    !query.fnSelect &&\n    !query.select &&\n    query.from.type !== `unionAll`\n  ) {\n    throw new DistinctRequiresSelectError()\n  }\n\n  if (query.fnSelect && query.groupBy && query.groupBy.length > 0) {\n    throw new FnSelectWithGroupByError()\n  }\n\n  const routingFns = includesRoutingFns\n  const getRowIncludesRouting = (row: NamespacedRow) =>\n    Object.fromEntries(\n      routingFns.map(({ fieldName, getRouting }) => [\n        fieldName,\n        getRouting(row),\n      ]),\n    )\n  if (materializeSelectInput) {\n    if (!inputIncludes.every(isInlineInclude)) {\n      throw new Error(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `fn.select() cannot consume Collection-valued includes. Use toArray() or materialize() in the upstream select(), or use an expression select() to keep live Collections.`\n          : codedMessage(128),\n      )\n    }\n    // Input paths belong before the callback: its arbitrary output may rename\n    // or discard them. Inline values need no public Collection boundary.\n    const inputPipeline = pipeline.pipe(\n      map(\n        ([key, row]: [\n          unknown,\n          NamespacedRow & { [INCLUDES_ROUTING]?: object },\n        ]) => [\n          key,\n          [\n            {\n              ...row,\n              [INCLUDES_ROUTING]: {\n                ...row[INCLUDES_ROUTING],\n                ...getRowIncludesRouting(row),\n              },\n            },\n            undefined,\n          ],\n        ],\n      ),\n    ) as ResultStream\n    const materializedInput =\n      includesResults[0]!.runtime.materializeCompilation({\n        pipeline: inputPipeline,\n        includes: includesResults,\n        valueIdentity,\n        collectionId: mainCollectionId,\n        sourceWhereClauses,\n        aliasToCollectionId,\n        aliasRemapping,\n      })\n    const resolveInput = materializedInput.resolve\n    pipeline = materializedInput.pipeline.pipe(\n      map(([key, [value]]) => {\n        // Resolution cleans public values, while this internal namespace must\n        // keep its route and genuine source attribution through the callback.\n        const resolved = resolveInput\n          ? resolveInput(value, (leaf) => leaf)\n          : value\n        const row = (\n          resolved === value ? { ...value } : resolved\n        ) as NamespacedRow & Record<PropertyKey, unknown>\n        restoreInternalRouteMetadata(row, value)\n        delete row[INCLUDES_ROUTING]\n        return [key, row]\n      }),\n    ) as NamespacedAndKeyedStream\n    includesResults = []\n    includesRoutingFns = []\n  }\n\n  const sourceBindings = new Map(\n    getAllSources(query).map((source) => [source.alias, source.bindingId]),\n  )\n  const sourceAliases = [...sourceBindings.keys()]\n  const unionRows = query.from.type === `unionAll`\n  // Process the SELECT clause early - always create $selected\n  // This eliminates duplication and allows for DISTINCT implementation\n  if (query.fnSelect) {\n    // Handle functional select - apply the function to transform the row\n    pipeline = pipeline.pipe(\n      map(([key, namespacedRow]) => {\n        const callbackRow = stripInternalCallbackMetadata(\n          namespacedRow,\n        ) as NamespacedRow\n        const selectResults = query.fnSelect!(callbackRow)\n        validateFnSelectResult(selectResults)\n        let selected = selectResults\n        const routing = (namespacedRow as any)[INCLUDES_ROUTING]\n        if (routing && isPublicContainer(selectResults)) {\n          selected = copySelectedRow(selectResults)\n          selected[INCLUDES_ROUTING] = routing\n        }\n        return [\n          key,\n          {\n            ...namespacedRow,\n            $selected: selected,\n          },\n        ]\n      }),\n    )\n  } else if (query.select) {\n    // An aggregate query computes its select values from each group, so it\n    // does not project rows first.\n    if (!selectHasAggregates && !(query.groupBy && query.groupBy.length > 0))\n      pipeline = processSelect(pipeline, query.select, allInputs)\n  } else {\n    // If no SELECT clause, create $selected with the main table data\n    pipeline = pipeline.pipe(\n      map(([key, namespacedRow]) => {\n        const routedScalar = getRoutedScalarMetadata(namespacedRow)\n        const selectResults =\n          isUnionFrom && routedScalar\n            ? routedScalar.value\n            : !isUnionFrom && !query.join && !query.groupBy\n              ? namespacedRow[mainSource]\n              : namespacedRow\n\n        return [\n          key,\n          {\n            ...namespacedRow,\n            $selected: selectResults,\n          },\n        ] as [string, typeof namespacedRow & { $selected: any }]\n      }),\n    )\n  }\n\n  // Tag $selected with routing metadata so the materialization graph can route\n  // children without depending on the user's projection.\n  if (includesRoutingFns.length > 0) {\n    pipeline = pipeline.pipe(\n      map(([key, namespacedRow]: any) => {\n        const selected = copySelectedRow(namespacedRow.$selected)\n        selected[INCLUDES_ROUTING] = getRowIncludesRouting(namespacedRow)\n        return [key, { ...namespacedRow, $selected: selected }]\n      }),\n    )\n  }\n\n  // Process the GROUP BY clause if it exists.\n  // When in includes mode (parentKeyStream), pass mainSource so that groupBy\n  // preserves route metadata for per-parent aggregation.\n  const groupByMainSource = parentKeyStream ? mainSource : undefined\n  // A ref reads the query's own rows when it is bound to one of its sources.\n  // A ref bound to an ancestor scope can reuse a source alias. After a\n  // unionAll, an unbound ref names a field of the union's rows.\n  const isSourceRef = (ref: PropRef) => {\n    const binding = sourceBindings.get(ref.path[0]!)\n    if (binding !== undefined) return (ref.bindingId ?? binding) === binding\n    // `$selected` names the query's own select values, not a source.\n    return (\n      unionRows && ref.bindingId === undefined && ref.path[0] !== `$selected`\n    )\n  }\n  // An aggregate value or groupKeys brings the grouping compiler. A groupBy,\n  // or an aggregate anywhere, needs it; query IR built by hand may lack it.\n  // The query compiles every aggregate with the compiler any one brings.\n  const aggregate =\n    selectAggregate ??\n    findAggregate([\n      query.having,\n      query.orderBy?.map((clause) => clause.expression),\n    ])\n  const grouping = query.grouping ?? aggregate?.grouping\n  const grouped = (query.groupBy?.length ?? 0) > 0\n  if ((grouped || aggregate) && !grouping)\n    throw new GroupingOperatorRequiredError()\n  // SELECT aggregates without GROUP BY make one implicit group.\n  if (grouping && (grouped || selectAggregate)) {\n    pipeline = grouping.processGroupBy(\n      pipeline,\n      query.groupBy ?? [],\n      valueIdentity,\n      isSourceRef,\n      query.having,\n      query.select,\n      query.fnHaving,\n      groupByMainSource,\n      sourceCarriesInternalRouteState || includesRoutingFns.length > 0,\n    )\n  }\n\n  // Process the HAVING clause if it exists (only applies after GROUP BY)\n  // An aggregate anywhere in SELECT, wrapped or not, makes one implicit group.\n  if (\n    query.having &&\n    (!query.groupBy || query.groupBy.length === 0) &&\n    !selectHasAggregates\n  ) {\n    throw new HavingRequiresGroupByError()\n  }\n\n  // Process functional HAVING clauses outside of GROUP BY (treat as additional WHERE filters)\n  if (\n    query.fnHaving &&\n    query.fnHaving.length > 0 &&\n    (!query.groupBy || query.groupBy.length === 0)\n  ) {\n    // If there's no GROUP BY but there are fnHaving clauses, apply them as filters\n    for (const fnHaving of query.fnHaving) {\n      pipeline = pipeline.pipe(\n        filter(([_key, namespacedRow]) => {\n          const callbackRow = stripInternalCallbackMetadata(\n            namespacedRow,\n          ) as NamespacedRow\n          // $selected is compiler-created context at this stage. A flat\n          // union's implicit selection can still hold namespace sidecars at\n          // its root; remove them without visiting authored payloads.\n          const selected = stripInternalCallbackMetadata(\n            callbackRow.$selected,\n          ) as Record<string, unknown>\n          return fnHaving(\n            selected === callbackRow.$selected\n              ? callbackRow\n              : { ...callbackRow, $selected: selected },\n          )\n        }),\n      )\n    }\n  }\n\n  // DISTINCT tracks visibility by selected value, so an insert-before-delete\n  // replacement with the same key must be normalized first; joined\n  // contributors may differ in unselected namespaces, and only the public\n  // value and its route/order inputs must be congruent. Ordering already\n  // batches each key's retractions before its insertions (topKBatch), and\n  // materialized relations reduce by public key, so other queries keep their\n  // compiled rows.\n  if (!selectHasAggregates && query.distinct) {\n    pipeline = canonicalizeSelectedRows(\n      pipeline,\n      query,\n      mainSource,\n      parentKeyStream !== undefined,\n    )\n  }\n\n  // Process the DISTINCT clause if it exists\n  if (query.distinct) {\n    pipeline = pipeline.pipe(distinct(([_key, row]) => row.$selected))\n  }\n\n  const metadataSource = query.select\n    ? getWholeRowSourceAliases(query.select)\n    : query.from.type === `unionAll`\n      ? undefined\n      : query.join\n        ? []\n        : [mainSource]\n  const finalizeRow = (\n    key: unknown,\n    row: Record<PropertyKey, any>,\n    orderByIndex: string | undefined,\n  ) => {\n    const selected = unwrapValue(row.$selected)\n    // Grouping supplies a public key even before Collection publication.\n    // Authored fields still win at intermediate boundaries, including null.\n    const selectedValue =\n      !isCollectionRoot &&\n      (grouped || selectAggregate) &&\n      isPublicContainer(selected) &&\n      !(`$key` in selected)\n        ? Object.assign(copySelectedRow(selected), { $key: row.$key })\n        : selected\n    let metadata: RowMetadata | null = null\n    if (query.fnSelect) {\n      const alias = sourceAliases.find(\n        (source) => selectedValue === row[source],\n      )\n      if (alias !== undefined) metadata = getSourceMetadata(row, alias)\n    } else if (metadataSource === undefined) {\n      metadata = row[ROW_METADATA] ?? null\n    } else {\n      for (const alias of metadataSource)\n        if (row[alias] != null) metadata = getSourceMetadata(row, alias)\n    }\n    // A source owns attribution, but a joined occurrence has its own identity.\n    // Collection publication supplies its computed or explicitly configured key.\n    if (query.join && metadata && `$key` in metadata) {\n      metadata = { ...metadata }\n      delete metadata.$key\n    }\n    const finalResults = stripInternalRouteMetadata(\n      isCollectionRoot\n        ? attachVirtualPropsToSelected(selectedValue, metadata)\n        : selectedValue,\n    )\n    const route = parentKeyStream\n      ? getNamespacedRouteMetadata(row, mainSource)\n      : undefined\n    return [\n      key,\n      [\n        finalResults,\n        orderByIndex,\n        route?.correlationKey,\n        parentKeyStream ? (route?.parentContext ?? null) : undefined,\n        parentKeyStream ? (row[INCLUDES_PUBLIC_KEY] ?? key) : undefined,\n        metadata,\n      ],\n    ] as unknown as [unknown, [any, string | undefined]]\n  }\n\n  // A single-result query must expose only its first row when another query\n  // consumes it as a QueryRef, before the outer join or filter runs.\n  const resultLimit = query.singleResult\n    ? Math.min(query.limit ?? 1, 1)\n    : query.limit\n  if (\n    !hasOrderBy &&\n    (query.limit !== undefined || query.offset !== undefined)\n  ) {\n    throw new LimitOffsetRequireOrderByError()\n  }\n  let resultPipeline: ResultStream\n  let ownWindowFn: ((options: WindowOptions) => void) | undefined\n  if (hasOrderBy || query.singleResult) {\n    // When in includes mode with limit/offset, use grouped ordering so that\n    // the limit is applied per parent (per correlation key), not globally.\n    const includesGroupKeyFn =\n      parentKeyStream &&\n      (resultLimit !== undefined || query.offset !== undefined)\n        ? (_key: unknown, row: unknown) => {\n            const route = getNamespacedRouteMetadata(row, mainSource)\n            const correlationKey = route?.correlationKey\n            const parentContext = route?.parentContext\n            if (parentContext != null) {\n              return serializeValue([\n                valueIdentity.equality(correlationKey),\n                getParentContextIdentity(parentContext),\n              ])\n            }\n            return valueIdentity.equality(correlationKey)\n          }\n        : undefined\n\n    const ordered = processOrderBy(\n      rawQuery,\n      pipeline,\n      // With no explicit order, top-K breaks ties by the public row key.\n      query.orderBy ?? [],\n      query.select || {},\n      grouping,\n      collections[mainCollectionId]!,\n      optimizableOrderByCollections,\n      (windowFn) => (ownWindowFn = windowFn),\n      resultLimit,\n      query.offset,\n      includesGroupKeyFn,\n    )\n    for (const compileInclude of deferredIncludes) compileInclude(ordered)\n    // Only after its includes compile, so a failed child leaves no window.\n    if (ownWindowFn) setWindowFn(ownWindowFn)\n    resultPipeline = ordered.pipe(\n      map(([key, [row, orderByIndex]]) => finalizeRow(key, row, orderByIndex)),\n    ) as ResultStream\n  } else {\n    resultPipeline = pipeline.pipe(\n      map(([key, row]) => finalizeRow(key, row, undefined)),\n    ) as ResultStream\n  }\n\n  // Cache by original query and compilation role, preserving independent roots.\n  const compilationResult: CompilationResult = {\n    collectionId: mainCollectionId,\n    pipeline: resultPipeline,\n    valueIdentity,\n    sourceWhereClauses,\n    aliasToCollectionId,\n    aliasRemapping,\n    includes: includesResults.length > 0 ? includesResults : undefined,\n  }\n  if (parentKeyStream === undefined) {\n    getOrCreate(\n      cache,\n      rawQuery,\n      (): [CompilationResult?, CompilationResult?, CompilationResult?] => [],\n    )[cacheSlot] = compilationResult\n  }\n\n  return compilationResult\n}\n\nfunction isInlineInclude(include: IncludesCompilationResult): boolean {\n  return (\n    include.materialization !== `collection` &&\n    (include.childCompilationResult.includes ?? []).every(isInlineInclude)\n  )\n}\n\nfunction keyWhereClausesBySource(\n  query: QueryIR,\n  clauses: Map<string, BasicExpression<boolean>>,\n): Map<string, BasicExpression<boolean>> {\n  const localSources = getAllSources(query).filter(\n    (source): source is CollectionRef => source.type === `collectionRef`,\n  )\n  const localSourceByAlias = new Map(\n    localSources.map((source) => [source.alias, source]),\n  )\n  const result = new Map<string, BasicExpression<boolean>>()\n  for (const [key, clause] of clauses) {\n    const source = localSourceByAlias.get(key)\n    if (source) result.set(source.sourceId, clause)\n  }\n  return result\n}\n\nfunction bindSourceInputs(\n  sources: Array<CollectionRef>,\n  inputs: Record<string, KeyedStream>,\n): void {\n  // Callers may key inputs by alias. Bind them to source identities once;\n  // compilation then reads inputs by SourceId only, so a source whose\n  // identity was lost fails instead of reading a same-named source.\n  for (const source of sources) {\n    const input = inputs[source.sourceId] ?? inputs[source.alias]\n    if (input) inputs[source.sourceId] = input\n  }\n}\n\nfunction canonicalizeSelectedRows(\n  pipeline: NamespacedAndKeyedStream,\n  query: QueryIR,\n  mainSource: string,\n  isIncludedRelation: boolean,\n): NamespacedAndKeyedStream {\n  const compiledOrder = (query.orderBy ?? []).map(({ expression }) =>\n    compileExpression(expression),\n  )\n  const signature = (row: any) => {\n    const route = isIncludedRelation\n      ? getNamespacedRouteMetadata(row, mainSource)\n      : undefined\n    return {\n      value: row.$selected,\n      routing: row.$selected?.[INCLUDES_ROUTING],\n      outerCorrelation: route?.correlationKey,\n      parentContext: isIncludedRelation\n        ? (route?.parentContext ?? null)\n        : undefined,\n      order: compiledOrder.map((evaluate) => evaluate(row)),\n    }\n  }\n\n  return pipeline.pipe(\n    reduce((values: Array<[any, number]>) => {\n      const totalMultiplicity = values.reduce(\n        (total, [, multiplicity]) => total + multiplicity,\n        0,\n      )\n      if (totalMultiplicity === 0) return []\n      if (totalMultiplicity < 0) {\n        throw new Error(\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `Query row has negative multiplicity`\n            : codedMessage(129),\n        )\n      }\n\n      const visible = values.find(([, multiplicity]) => multiplicity > 0)?.[0]\n      if (!visible)\n        throw new Error(\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `Query row has no positive contributor`\n            : codedMessage(130),\n        )\n      const visibleSignature = signature(visible)\n\n      for (const [candidate, multiplicity] of values) {\n        if (\n          multiplicity > 0 &&\n          !deepEquals(visibleSignature, signature(candidate))\n        ) {\n          throw new Error(\n            devBuild() && process.env.NODE_ENV !== `production`\n              ? `Query contributors with the same row key are not congruent`\n              : codedMessage(131),\n          )\n        }\n      }\n\n      return [[visible, 1]]\n    }),\n  ) as NamespacedAndKeyedStream\n}\n\n/** Validate each lexical scope before optimization changes the plan. */\nfunction validateExpressionBindings(\n  expression: BasicExpression | Aggregate,\n  availableBindings: ReadonlySet<string>,\n): void {\n  for (const ref of collectPropRefs(expression)) {\n    if (ref.bindingId !== undefined && !availableBindings.has(ref.bindingId)) {\n      throw new QueryCompilationError(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `Query reference \"${ref.path.join(`.`)}\" is out of scope. Use a source from this query or a containing query.`\n          : codedMessage(238, { path: ref.path }),\n      )\n    }\n  }\n}\n\nfunction validateSelectBindings(\n  value: unknown,\n  availableBindings: ReadonlySet<string>,\n): void {\n  if (value instanceof IncludesSubquery) return\n  if (isBasicOrAggregateExpression(value)) {\n    validateExpressionBindings(value, availableBindings)\n  } else if (value instanceof ConditionalSelect) {\n    for (const branch of value.branches) {\n      validateExpressionBindings(branch.condition, availableBindings)\n      validateSelectBindings(branch.value, availableBindings)\n    }\n    if (value.defaultValue !== undefined) {\n      validateSelectBindings(value.defaultValue, availableBindings)\n    }\n  } else if (isNestedSelectObject(value)) {\n    for (const nested of Object.values(value)) {\n      validateSelectBindings(nested, availableBindings)\n    }\n  }\n}\n\nfunction validateQueryStructure(\n  query: QueryIR,\n  ancestorBindings: ReadonlySet<string> = new Set(),\n): void {\n  // One scope cannot name two sources alike.\n  const levelAliases = getAllSources(query).map((source) => source.alias)\n  for (const [index, alias] of levelAliases.entries()) {\n    if (levelAliases.indexOf(alias) !== index) {\n      throw new QueryCompilationError(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `Query uses alias \"${alias}\" more than once. Give each source in one query a distinct alias.`\n          : codedMessage(211, { alias }),\n      )\n    }\n  }\n\n  const availableBindings = new Set(ancestorBindings)\n\n  // A FROM subquery sees ancestors, but not its own enclosing source\n  // declaration. Union branches do not expose their sources to one another.\n  if (query.from.type === `unionAll`) {\n    for (const branch of query.from.queries) {\n      validateQueryStructure(branch, ancestorBindings)\n    }\n  } else {\n    for (const source of getFromSources(query.from)) {\n      if (source.type === `queryRef`) {\n        validateQueryStructure(source.query, ancestorBindings)\n      }\n      availableBindings.add(source.bindingId)\n    }\n  }\n\n  // Each join may read sources declared before it and its joined source.\n  // A binding captured from an unrelated query is not an ancestor, even if\n  // that query happened to use the same alias text.\n  if (query.join) {\n    for (const joinClause of query.join) {\n      if (joinClause.from.type === `queryRef`) {\n        validateQueryStructure(joinClause.from.query, ancestorBindings)\n      }\n      const joinBindings = new Set(availableBindings)\n      joinBindings.add(joinClause.from.bindingId)\n      validateExpressionBindings(joinClause.on, joinBindings)\n      availableBindings.add(joinClause.from.bindingId)\n    }\n  }\n\n  for (const where of query.where ?? []) {\n    validateExpressionBindings(getWhereExpression(where), availableBindings)\n  }\n  for (const expression of query.groupBy ?? []) {\n    validateExpressionBindings(expression, availableBindings)\n  }\n  for (const having of query.having ?? []) {\n    validateExpressionBindings(getHavingExpression(having), availableBindings)\n  }\n  for (const { expression } of query.orderBy ?? []) {\n    validateExpressionBindings(expression, availableBindings)\n  }\n  if (query.select) {\n    validateSelectBindings(query.select, availableBindings)\n    for (const { subquery } of extractIncludesFromSelect(query.select)) {\n      validateExpressionBindings(subquery.correlationField, availableBindings)\n      const childBindings = new Set(availableBindings)\n      for (const source of getAllSources(subquery.query)) {\n        childBindings.add(source.bindingId)\n      }\n      validateExpressionBindings(subquery.childCorrelationField, childBindings)\n      for (const where of subquery.parentFilters ?? []) {\n        validateExpressionBindings(getWhereExpression(where), childBindings)\n      }\n      validateQueryStructure(subquery.query, availableBindings)\n      const projected = new Set(\n        (subquery.parentProjection ?? []).map((ref) =>\n          JSON.stringify([ref.bindingId, ref.path]),\n        ),\n      )\n      const required = [\n        ...collectExternalRefsFromQuery(subquery.query),\n        ...(subquery.parentFilters ?? []).flatMap((where) =>\n          collectPropRefs(getWhereExpression(where)),\n        ),\n      ]\n      for (const ref of required) {\n        if (\n          ref.bindingId !== undefined &&\n          availableBindings.has(ref.bindingId) &&\n          !projected.has(JSON.stringify([ref.bindingId, ref.path]))\n        ) {\n          throw new QueryCompilationError(\n            devBuild() && process.env.NODE_ENV !== `production`\n              ? `Include query is missing a captured parent projection for \"${ref.path.join(`.`)}\".`\n              : codedMessage(239, { path: ref.path }),\n          )\n        }\n      }\n    }\n  }\n}\n\n/**\n * Processes the FROM clause, handling direct collection references and subqueries.\n * Populates `aliasToCollectionId` and `aliasRemapping` for per-alias subscription tracking.\n */\nfunction processFromClause(\n  from: From,\n  allInputs: Record<string, KeyedStream>,\n  collections: Record<string, Collection>,\n  subscriptions: Record<string, CollectionSubscription>,\n  callbacks: Record<string, LazyCollectionCallbacks>,\n  lazySources: Set<string>,\n  optimizableOrderByCollections: Record<string, OrderByOptimizationInfo>,\n  setWindowFn: (windowFn: (options: WindowOptions) => void) => void,\n  cache: QueryCache,\n  queryMapping: QueryMapping,\n  aliasToCollectionId: Record<string, string>,\n  aliasRemapping: Record<string, string>,\n  sourceWhereClauses: Map<string, BasicExpression<boolean>>,\n  parentKeyStream?: KeyedStream,\n): {\n  alias: string\n  pipeline: NamespacedAndKeyedStream\n  collectionId: string\n  sources: Record<string, KeyedStream>\n  sourceIncludes: Array<SourceInclude>\n  directIncludes: Array<IncludesCompilationResult>\n  isUnionFrom: boolean\n  isParentRouted: boolean\n} {\n  const valueIdentity = getCompilationValueIdentity(cache)\n  if (from.type === `unionAll`) {\n    return processUnionAll(\n      from,\n      allInputs,\n      collections,\n      subscriptions,\n      callbacks,\n      lazySources,\n      optimizableOrderByCollections,\n      setWindowFn,\n      cache,\n      queryMapping,\n      aliasToCollectionId,\n      aliasRemapping,\n      sourceWhereClauses,\n      parentKeyStream,\n    )\n  }\n\n  const compileSource = (source: CollectionSourceRef | QueryRef) => {\n    const result = processSource(\n      source,\n      allInputs,\n      queryMapping,\n      (subquery, parentRoutes) =>\n        compileQueryInternal(\n          [\n            subquery,\n            allInputs,\n            collections,\n            subscriptions,\n            callbacks,\n            lazySources,\n            optimizableOrderByCollections,\n            setWindowFn,\n            cache,\n            queryMapping,\n            parentRoutes,\n          ],\n          true,\n        ),\n      aliasToCollectionId,\n      aliasRemapping,\n      sourceWhereClauses,\n      valueIdentity,\n      `from`,\n      parentKeyStream,\n    )\n    return {\n      ...result,\n      sourceIncludes:\n        result.includes?.map((include) => ({\n          sourceAlias: source.alias,\n          include,\n        })) ?? [],\n      isParentRouted:\n        source.type === `queryRef` && parentKeyStream !== undefined,\n    }\n  }\n\n  if (from.type !== `unionFrom`) {\n    const { alias, input, collectionId, sourceIncludes, isParentRouted } =\n      compileSource(from)\n\n    return {\n      alias,\n      pipeline: wrapInputWithAlias(input, alias, from.type === `queryRef`),\n      collectionId,\n      sources: { [alias]: input },\n      sourceIncludes,\n      directIncludes: [],\n      isUnionFrom: false,\n      isParentRouted,\n    }\n  }\n\n  if (from.sources.length === 0) {\n    throw new UnsupportedFromTypeError(`empty unionFrom`)\n  }\n\n  const sources: Record<string, KeyedStream> = {}\n  const sourceIncludes: Array<SourceInclude> = []\n  let pipeline: NamespacedAndKeyedStream | undefined\n  let mainAlias = ``\n  let mainCollectionId = ``\n\n  for (const source of from.sources) {\n    const {\n      alias,\n      input,\n      collectionId,\n      sourceIncludes: childSourceIncludes,\n      isParentRouted,\n    } = compileSource(source)\n\n    if (!mainAlias) {\n      mainAlias = alias\n      mainCollectionId = collectionId\n    }\n    sources[alias] = input\n    sourceIncludes.push(...childSourceIncludes)\n\n    const routedBranch =\n      parentKeyStream && !isParentRouted\n        ? parameterizeByParentRoutes(\n            wrapInputWithAlias(input, alias, source.type === `queryRef`),\n            parentKeyStream,\n            valueIdentity,\n          )\n        : wrapInputWithAlias(input, alias, source.type === `queryRef`)\n    const branch = routedBranch.pipe(\n      map(([key, row]) => {\n        const branchKey = `${alias}:${encodeKeyForUnionBranch(key)}`\n        const publicKey =\n          (row as Record<PropertyKey, unknown>)[INCLUDES_PUBLIC_KEY] ?? key\n        const branchPublicKey = `${alias}:${encodeKeyForUnionBranch(publicKey)}`\n        const branchRow = parentKeyStream\n          ? {\n              ...row,\n              [INCLUDES_PUBLIC_KEY]: branchPublicKey,\n            }\n          : row\n        return [branchKey, branchRow] as [string, typeof row]\n      }),\n    )\n\n    pipeline = pipeline ? pipeline.pipe(concatOperator(branch)) : branch\n  }\n\n  return {\n    alias: mainAlias,\n    pipeline: pipeline!,\n    collectionId: mainCollectionId,\n    sources,\n    sourceIncludes,\n    directIncludes: [],\n    isUnionFrom: true,\n    isParentRouted: parentKeyStream !== undefined,\n  }\n}\n\nfunction processUnionAll(\n  from: UnionAll,\n  allInputs: Record<string, KeyedStream>,\n  collections: Record<string, Collection>,\n  subscriptions: Record<string, CollectionSubscription>,\n  callbacks: Record<string, LazyCollectionCallbacks>,\n  lazySources: Set<string>,\n  optimizableOrderByCollections: Record<string, OrderByOptimizationInfo>,\n  setWindowFn: (windowFn: (options: WindowOptions) => void) => void,\n  cache: QueryCache,\n  queryMapping: QueryMapping,\n  aliasToCollectionId: Record<string, string>,\n  aliasRemapping: Record<string, string>,\n  sourceWhereClauses: Map<string, BasicExpression<boolean>>,\n  parentKeyStream?: KeyedStream,\n): {\n  alias: string\n  pipeline: NamespacedAndKeyedStream\n  collectionId: string\n  sources: Record<string, KeyedStream>\n  sourceIncludes: Array<SourceInclude>\n  directIncludes: Array<IncludesCompilationResult>\n  isUnionFrom: boolean\n  isParentRouted: boolean\n} {\n  if (from.queries.length === 0) {\n    throw new UnsupportedFromTypeError(`empty unionAll`)\n  }\n\n  const sources: Record<string, KeyedStream> = {}\n  const sourceIncludes: Array<SourceInclude> = []\n  const directIncludes: Array<IncludesCompilationResult> = []\n  let pipeline: NamespacedAndKeyedStream | undefined\n  let mainCollectionId = ``\n  const branchAliases = new Set<string>()\n\n  for (let index = 0; index < from.queries.length; index++) {\n    const branch = from.queries[index]!\n    for (const source of getAllSources(branch)) {\n      if (branchAliases.has(source.alias)) {\n        throw new Error(\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `Duplicate source alias \"${source.alias}\" in unionAll query branches. ` +\n                `Use distinct aliases in each branch before passing them to unionAll().`\n            : codedMessage(132, { alias: source.alias }),\n        )\n      }\n      branchAliases.add(source.alias)\n    }\n    const branchResult = compileQueryInternal(\n      [\n        branch,\n        allInputs,\n        collections,\n        subscriptions,\n        callbacks,\n        lazySources,\n        optimizableOrderByCollections,\n        setWindowFn,\n        cache,\n        queryMapping,\n        parentKeyStream,\n        undefined,\n      ],\n      true,\n    )\n\n    if (!mainCollectionId) {\n      mainCollectionId = branchResult.collectionId\n    }\n    Object.assign(aliasToCollectionId, branchResult.aliasToCollectionId)\n    Object.assign(aliasRemapping, branchResult.aliasRemapping)\n    directIncludes.push(...(branchResult.includes ?? []))\n    Object.assign(sources, allInputs)\n    for (const [alias, where] of branchResult.sourceWhereClauses) {\n      sourceWhereClauses.set(alias, where)\n    }\n\n    const branchPipeline = branchResult.pipeline.pipe(\n      map((data: any) => {\n        const [\n          key,\n          [row, _order, correlationKey, parentContext, publicKey, metadata],\n        ] = data\n        const branchKey = `${index}:${encodeKeyForUnionBranch(key)}`\n        const branchPublicKey = `${index}:${encodeKeyForUnionBranch(\n          publicKey ?? key,\n        )}`\n        const routedRow = parentKeyStream\n          ? attachRouteMetadataToResult(\n              row,\n              correlationKey,\n              parentContext,\n              branchPublicKey,\n            )\n          : row\n        return [\n          branchKey,\n          metadata != null && isPublicContainer(routedRow)\n            ? Object.assign(copySelectedRow(routedRow), {\n                [ROW_METADATA]: metadata ?? null,\n              })\n            : routedRow,\n        ] as [string, Record<string, any>]\n      }),\n    )\n\n    pipeline = pipeline\n      ? pipeline.pipe(concatOperator(branchPipeline))\n      : branchPipeline\n  }\n\n  return {\n    alias: ``,\n    pipeline: pipeline!,\n    collectionId: mainCollectionId,\n    sources,\n    sourceIncludes,\n    directIncludes,\n    isUnionFrom: true,\n    isParentRouted: parentKeyStream !== undefined,\n  }\n}\n\nfunction wrapInputWithAlias(\n  input: KeyedStream,\n  alias: string,\n  hasInternalState = true,\n): NamespacedAndKeyedStream {\n  return input.pipe(\n    map(([key, row, metadata]: [...InputRow, unknown?]) => [\n      key,\n      wrapInputRow(\n        alias,\n        row,\n        metadata as RowMetadata | null | undefined,\n        hasInternalState,\n      ),\n    ]),\n  )\n}\n\nfunction encodeKeyForUnionBranch(key: unknown): string {\n  const type = typeof key\n  const value =\n    type === `string` || type === `number` || type === `bigint`\n      ? String(key)\n      : JSON.stringify(key)\n  return `${type}:${value}`\n}\n\n// Only compiler-created Value instances are wrappers; user rows may have\n// ordinary `type` and `value` fields with the same shape.\nfunction unwrapValue(value: any): any {\n  return value instanceof ValClass ? value.value : value\n}\n\n// A nullish spread contributes no properties. Keep source order so the last\n// present whole-row spread supplies metadata, just as it supplies row fields.\nfunction getWholeRowSourceAliases(select: unknown): Array<string> {\n  if (select instanceof PropRef && select.path.length === 1)\n    return [select.path[0]!]\n  if (!isPlainObject(select)) return []\n  return Object.entries(select).flatMap(([name, value]) =>\n    name.startsWith(`__SPREAD_SENTINEL__`) &&\n    value instanceof PropRef &&\n    value.path.length === 1\n      ? [value.path[0]!]\n      : [],\n  )\n}\n\nfunction copySelectedRow(\n  selected: Record<PropertyKey, any>,\n): Record<PropertyKey, any> {\n  return Array.isArray(selected) ? [...selected] : { ...selected }\n}\n\nfunction attachVirtualPropsToSelected(\n  selected: unknown,\n  metadata: RowMetadata | null,\n): unknown {\n  if (!isPublicContainer(selected)) return selected\n  const selectedRecord = selected as Record<PropertyKey, unknown>\n  let result = selectedRecord\n  for (const prop of VIRTUAL_PROP_NAMES) {\n    const present = metadata !== null && prop in metadata\n    if (\n      present\n        ? prop in selectedRecord && selectedRecord[prop] === metadata[prop]\n        : !(prop in selectedRecord)\n    )\n      continue\n    if (result === selectedRecord) result = copySelectedRow(selectedRecord)\n    if (present) result[prop] = metadata[prop]\n    else delete result[prop]\n  }\n  return result\n}\n\n/**\n * Recursively records the user-defined origin of optimized subqueries.\n * Compilation still consumes the optimized query; the mapping is lineage used\n * to distinguish user-defined subqueries from optimizer-created wrappers.\n */\nfunction mapNestedQueries(\n  optimizedQuery: QueryIR,\n  originalQuery: QueryIR,\n  queryMapping: QueryMapping,\n): void {\n  mapNestedFromQueries(optimizedQuery.from, originalQuery.from, queryMapping)\n\n  // Map JOIN clauses if they exist\n  if (optimizedQuery.join && originalQuery.join) {\n    for (\n      let i = 0;\n      i < optimizedQuery.join.length && i < originalQuery.join.length;\n      i++\n    ) {\n      mapNestedFromQueries(\n        optimizedQuery.join[i]!.from,\n        originalQuery.join[i]!.from,\n        queryMapping,\n      )\n    }\n  }\n}\n\nfunction getAllSources(query: QueryIR): Array<CollectionSourceRef | QueryRef> {\n  return [\n    ...getFromSources(query.from),\n    ...(query.join?.map((join) => join.from) ?? []),\n  ]\n}\n\nfunction findProjectedIncludePaths(\n  select: Record<string, any>,\n  targetPath: Array<string>,\n): Array<ProjectedSourceIncludePath> {\n  const resultPaths: Array<ProjectedSourceIncludePath> = []\n\n  const visitSelectObject = (\n    obj: Record<string, any>,\n    prefix: Array<string>,\n    guards: Array<ConditionalSelectGuard>,\n  ) => {\n    for (const [key, value] of Object.entries(obj)) {\n      if (key.startsWith(`__SPREAD_SENTINEL__`)) {\n        visitSpreadSentinel(key, value, prefix, guards)\n        continue\n      }\n      visitSelectValue(value, [...prefix, key], guards)\n    }\n  }\n\n  const visitSpreadSentinel = (\n    key: string,\n    value: any,\n    path: Array<string>,\n    guards: Array<ConditionalSelectGuard>,\n  ) => {\n    const rest = key.slice(`__SPREAD_SENTINEL__`.length)\n    const splitIndex = rest.lastIndexOf(`__`)\n    const pathStr = splitIndex >= 0 ? rest.slice(0, splitIndex) : rest\n    const isRefExpr =\n      value &&\n      typeof value === `object` &&\n      `type` in value &&\n      value.type === `ref`\n    const sourcePath = isRefExpr\n      ? (value as PropRef).path\n      : pathStr.split(`.`).filter(Boolean)\n\n    if (pathStartsWith(targetPath, sourcePath)) {\n      resultPaths.push({\n        path: [...path, ...targetPath.slice(sourcePath.length)],\n        guards,\n      })\n    }\n  }\n\n  const visitSelectValue = (\n    value: any,\n    path: Array<string>,\n    guards: Array<ConditionalSelectGuard>,\n  ) => {\n    if (value instanceof PropRef && pathStartsWith(targetPath, value.path)) {\n      resultPaths.push({\n        path: [...path, ...targetPath.slice(value.path.length)],\n        guards,\n      })\n      return\n    }\n\n    if (value instanceof ConditionalSelect) {\n      visitConditionalSelect(value, guards, (child, childGuards) =>\n        visitSelectValue(child, path, childGuards),\n      )\n      return\n    }\n\n    if (isNestedSelectObject(value)) {\n      visitSelectObject(value, path, guards)\n    }\n  }\n\n  visitSelectObject(select, [], [])\n  return resultPaths\n}\n\nfunction pathStartsWith(path: Array<string>, prefix: Array<string>): boolean {\n  return (\n    prefix.length <= path.length && prefix.every((part, i) => path[i] === part)\n  )\n}\n\nfunction mapNestedFromQueries(\n  optimizedFrom: QueryIR[`from`],\n  originalFrom: QueryIR[`from`],\n  queryMapping: QueryMapping,\n): void {\n  if (optimizedFrom.type === `unionAll` && originalFrom.type === `unionAll`) {\n    for (\n      let i = 0;\n      i < optimizedFrom.queries.length && i < originalFrom.queries.length;\n      i++\n    ) {\n      const optimizedBranch = optimizedFrom.queries[i]!\n      const originalBranch = originalFrom.queries[i]!\n      queryMapping.set(optimizedBranch, originalBranch)\n      mapNestedQueries(optimizedBranch, originalBranch, queryMapping)\n    }\n    return\n  }\n\n  const optimizedSources = getFromSources(optimizedFrom)\n  const originalSources = getFromSources(originalFrom)\n\n  for (\n    let i = 0;\n    i < optimizedSources.length && i < originalSources.length;\n    i++\n  ) {\n    const optimizedSource = optimizedSources[i]!\n    const originalSource = originalSources[i]!\n    if (\n      optimizedSource.type === `queryRef` &&\n      originalSource.type === `queryRef`\n    ) {\n      queryMapping.set(optimizedSource.query, originalSource.query)\n      mapNestedQueries(\n        optimizedSource.query,\n        originalSource.query,\n        queryMapping,\n      )\n    }\n  }\n}\n\n/**\n * Walks a Select object to find IncludesSubquery entries.\n * Plain nested objects still reject includes, but ConditionalSelect branches can\n * contain guarded nested includes that are only materialized when the branch\n * condition is true.\n */\nfunction extractIncludesFromSelect(select: Record<string, any>): Array<{\n  key: string\n  path: Array<string>\n  subquery: IncludesSubquery\n  guards: Array<ConditionalSelectGuard>\n}> {\n  const results: Array<{\n    key: string\n    path: Array<string>\n    subquery: IncludesSubquery\n    guards: Array<ConditionalSelectGuard>\n  }> = []\n  for (const [key, value] of Object.entries(select)) {\n    if (key.startsWith(`__SPREAD_SENTINEL__`)) continue\n    if (isNestedSelectObject(value)) {\n      // Plain nested includes remain invalid; conditional branches may contain them.\n      assertNoNestedIncludes(value, key)\n    } else {\n      collectIncludesFromSelectValue(value, [key], [], results)\n    }\n  }\n  return results\n}\n\n/** Each branch requires every earlier branch to be false. */\nfunction visitConditionalSelect(\n  conditional: ConditionalSelect,\n  guards: Array<ConditionalSelectGuard>,\n  visit: (value: any, guards: Array<ConditionalSelectGuard>) => void,\n): void {\n  const previousBranchGuards: Array<ConditionalSelectGuard> = []\n  for (const branch of conditional.branches) {\n    visit(branch.value, [\n      ...guards,\n      ...previousBranchGuards,\n      { condition: branch.condition, expected: true },\n    ])\n    previousBranchGuards.push({ condition: branch.condition, expected: false })\n  }\n  if (conditional.defaultValue !== undefined)\n    visit(conditional.defaultValue, [...guards, ...previousBranchGuards])\n}\n\nfunction collectIncludesFromSelectValue(\n  value: any,\n  prefixPath: Array<string>,\n  guards: Array<ConditionalSelectGuard>,\n  results: Array<{\n    key: string\n    path: Array<string>\n    subquery: IncludesSubquery\n    guards: Array<ConditionalSelectGuard>\n  }>,\n): void {\n  if (value instanceof IncludesSubquery) {\n    const key = getUniqueIncludesRoutingKey(prefixPath.join(`.`), results)\n    results.push({ key, path: prefixPath, subquery: value, guards })\n    return\n  }\n\n  if (value instanceof ConditionalSelect) {\n    visitConditionalSelect(value, guards, (child, childGuards) =>\n      collectIncludesFromSelectValue(child, prefixPath, childGuards, results),\n    )\n    return\n  }\n\n  if (!isNestedSelectObject(value)) {\n    return\n  }\n\n  for (const [key, child] of Object.entries(value)) {\n    if (key.startsWith(`__SPREAD_SENTINEL__`)) continue\n    collectIncludesFromSelectValue(child, [...prefixPath, key], guards, results)\n  }\n}\n\nfunction getUniqueIncludesRoutingKey(\n  baseKey: string,\n  entries: Array<{ key?: string; fieldName?: string }>,\n): string {\n  const taken = new Set(entries.map((entry) => entry.key ?? entry.fieldName))\n  if (!taken.has(baseKey)) return baseKey\n  let suffix = entries.length\n  while (taken.has(`${baseKey}#${suffix}`)) suffix++\n  return `${baseKey}#${suffix}`\n}\n\n/** Check if a value is a nested plain object in a select (not an IR expression node) */\nfunction isNestedSelectObject(value: any): value is Record<string, any> {\n  return (\n    value != null &&\n    typeof value === `object` &&\n    !Array.isArray(value) &&\n    !isExpressionLike(value) &&\n    !isRefProxy(value)\n  )\n}\n\nfunction assertNoNestedIncludes(\n  obj: Record<string, any>,\n  parentPath: string,\n): void {\n  for (const [key, value] of Object.entries(obj)) {\n    if (key.startsWith(`__SPREAD_SENTINEL__`)) continue\n    if (value instanceof IncludesSubquery) {\n      throw new Error(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `Includes subqueries must be at the top level of select(). ` +\n              `Found nested includes at \"${parentPath}.${key}\".`\n          : codedMessage(133, { parentPath, key }),\n      )\n    }\n    if (isNestedSelectObject(value)) {\n      assertNoNestedIncludes(value, `${parentPath}.${key}`)\n    }\n  }\n}\n\n/**\n * Replaces the IncludesSubquery at `path` inside a select value, through\n * nested objects and conditional branches, with a null Value placeholder, so\n * processSelect() never sees it. Unchanged values retain their identity, so\n * each level rebuilds only the objects that changed.\n */\nfunction replaceIncludesInSelectValue(value: any, path: Array<string>): any {\n  if (path.length === 0 && value instanceof IncludesSubquery)\n    return new ValClass(null)\n  if (value instanceof ConditionalSelect) {\n    const branches = value.branches.map((branch) => {\n      const next = replaceIncludesInSelectValue(branch.value, path)\n      return Object.is(next, branch.value) ? branch : { ...branch, value: next }\n    })\n    const defaultValue =\n      value.defaultValue === undefined\n        ? undefined\n        : replaceIncludesInSelectValue(value.defaultValue, path)\n    return branches.some((branch, index) => branch !== value.branches[index]) ||\n      !Object.is(defaultValue, value.defaultValue)\n      ? new ConditionalSelect(branches, defaultValue)\n      : value\n  }\n  if (path.length === 0 || !isNestedSelectObject(value)) return value\n  const [head, ...rest] = path\n  const child = value[head!]\n  const next = replaceIncludesInSelectValue(child, rest)\n  return Object.is(next, child) ? value : { ...value, [head!]: next }\n}\n\n/**\n * Gets a nested value from an object by path segments.\n * For v1 with single-level correlation fields (e.g., `projectId`), it's just `obj[path[0]]`.\n */\nfunction getNestedValue(obj: any, path: Array<string>): any {\n  let value = obj\n  for (const segment of path) {\n    if (value == null) return value\n    value = value[segment]\n  }\n  return value\n}\n\ntype IncludeRouting = {\n  active: boolean\n  correlationKey: unknown\n  parentContext: Record<string, any> | null\n}\n\n/** Only the query's own top-K answers setWindow; subqueries never do. */\nconst ignoreWindow = () => {}\n\n/** Rows a windowed query or a findOne shows, with their fractional index. */\ntype WindowRows = IStreamBuilder<KeyValue<unknown, [NamespacedRow, string]>>\n\n/** The include route a compiled value's routing tag holds for one field. */\nfunction readRouteTag(\n  value: unknown,\n  fieldName: string,\n): IncludeRouting | undefined {\n  const tag = (\n    value as { [INCLUDES_ROUTING]?: Record<string, IncludeRouting> } | undefined\n  )?.[INCLUDES_ROUTING]\n  return tag?.[fieldName]\n}\n\n/** The route a top-K result row's select tagged; a missing tag is an invariant. */\nfunction windowRoute(row: NamespacedRow, fieldName: string): IncludeRouting {\n  const routing = readRouteTag(row.$selected, fieldName)\n  if (!routing)\n    throw new Error(\n      devBuild() && process.env.NODE_ENV !== `production`\n        ? `A windowed or findOne result row has no include route`\n        : codedMessage(243),\n    )\n  return routing\n}\n\n/**\n * Compiles a select-branch guard set once and resolves the include route only\n * for rows whose guards hold. Every other row is routed as inactive.\n */\nfunction compileGuardedRouting(\n  guards: Array<ConditionalSelectGuard>,\n  resolve: (nsRow: any) => IncludeRouting | undefined,\n): (nsRow: any) => IncludeRouting {\n  const compiledGuards = guards.map((guard) => ({\n    condition: compileExpression(guard.condition),\n    expected: guard.expected,\n  }))\n  return (nsRow) => {\n    const active = compiledGuards.every(\n      (guard) =>\n        isCaseWhenConditionTrue(guard.condition(nsRow)) === guard.expected,\n    )\n    return (\n      (active ? resolve(nsRow) : undefined) ?? {\n        active: false,\n        correlationKey: null,\n        parentContext: null,\n      }\n    )\n  }\n}\n\nexport type CompileQueryFn = typeof compileQuery\n\nfunction getStaticDemandKeys(query: QueryIR, ref: PropRef): Set<unknown> {\n  const constraints: Array<Set<unknown>> = []\n  const visit = (expression: BasicExpression): void => {\n    if (expression.type !== `func`) return\n    if (expression.name === `and`) {\n      expression.args.forEach(visit)\n      return\n    }\n    if (expression.name !== `eq` && expression.name !== `in`) return\n\n    const [left, right] = expression.args\n    const value =\n      left?.type === `ref` &&\n      pathsEqual(left.path, ref.path) &&\n      right instanceof ValClass\n        ? right.value\n        : right?.type === `ref` &&\n            pathsEqual(right.path, ref.path) &&\n            left instanceof ValClass\n          ? left.value\n          : undefined\n    if (value === undefined) return\n    constraints.push(new Set(Array.isArray(value) ? value : [value]))\n  }\n\n  query.where?.forEach((where) => visit(getWhereExpression(where)))\n  if (constraints.length === 0) return new Set()\n  return new Set(\n    [...constraints[0]!].filter((value) =>\n      constraints.slice(1).every((constraint) => constraint.has(value)),\n    ),\n  )\n}\n\nfunction pathsEqual(left: Array<string>, right: Array<string>): boolean {\n  return (\n    left.length === right.length &&\n    left.every((segment, index) => segment === right[index])\n  )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0HA,SAAS,wCACP,OACA,uBAAoB,IAAI,IAAI,GACR;CACpB,IAAI,iBAAiBA,kBAAAA,gBAAgB,OAAO;CAC5C,IAAI,iBAAiBC,cAAAA,kBAAkB,OAAO;CAC9C,IAAI,iBAAiBC,kBAAAA,gBAAgB,OAAO;CAC5C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