{"version":3,"file":"index.cjs","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  tap,\n} from '@tanstack/db-ivm'\nimport { optimizeQuery } from '../optimizer.js'\nimport {\n  CollectionInputNotFoundError,\n  DistinctRequiresSelectError,\n  DuplicateAliasInSubqueryError,\n  FnSelectWithGroupByError,\n  HavingRequiresGroupByError,\n  LimitOffsetRequireOrderByError,\n  UnsupportedFromTypeError,\n} from '../../errors.js'\nimport { VIRTUAL_PROP_NAMES } from '../../virtual-props.js'\nimport {\n  ConditionalSelect,\n  IncludesSubquery,\n  PropRef,\n  Value as ValClass,\n  getWhereExpression,\n  isExpressionLike,\n} from '../ir.js'\nimport { ensureIndexForField } from '../../indexes/auto-index.js'\nimport { inArray } from '../builder/functions.js'\nimport {\n  compileExpression,\n  isCaseWhenConditionTrue,\n  toBooleanPredicate,\n} from './evaluators.js'\nimport { processJoins } from './joins.js'\nimport { containsAggregate, processGroupBy } from './group-by.js'\nimport { getLazyLoadTargets } from './lazy-targets.js'\nimport { processOrderBy } from './order-by.js'\nimport { processSelect } from './select.js'\nimport type { CollectionSubscription } from '../../collection/subscription.js'\nimport type { OrderByOptimizationInfo } from './order-by.js'\nimport type {\n  BasicExpression,\n  CollectionRef,\n  IncludesMaterialization,\n  QueryIR,\n  QueryRef,\n  UnionAll,\n  UnionFrom,\n} from '../ir.js'\nimport type { LazyCollectionCallbacks } from './joins.js'\nimport type { Collection } from '../../collection/index.js'\nimport type {\n  KeyedStream,\n  NamespacedAndKeyedStream,\n  ResultStream,\n} from '../../types.js'\nimport type { QueryCache, QueryMapping, WindowOptions } from './types.js'\n\nexport type { WindowOptions } from './types.js'\n\n/** Symbol used to tag parent $selected with routing metadata for includes */\nexport const INCLUDES_ROUTING = Symbol(`includesRouting`)\nexport const FN_SELECT_STATE = Symbol(`fnSelectState`)\nconst SKIP_INCLUDE = Symbol(`skipInclude`)\n\ntype ConditionalSelectGuard = {\n  condition: BasicExpression\n  expected: boolean\n}\n\ntype SourceInclude = {\n  sourceAlias: string\n  include: IncludesCompilationResult\n}\n\ntype ProjectedSourceIncludePath = {\n  path: Array<string>\n  guards: Array<ConditionalSelectGuard>\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}\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  /** Map of source aliases to their WHERE clauses for index optimization */\n  sourceWhereClauses: Map<string, BasicExpression<boolean>>\n\n  /**\n   * Maps each source alias to its collection ID. 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\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 aliases that should load data lazily\n * @param optimizableOrderByCollections Map of collection IDs to order-by optimization info\n * @param cache Optional cache for compiled subqueries (used internally for recursion)\n * @param queryMapping Optional mapping from optimized queries to original queries\n * @returns A CompilationResult with the pipeline, source WHERE clauses, and alias metadata\n */\nexport function compileQuery(\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 = new WeakMap(),\n  queryMapping: QueryMapping = new WeakMap(),\n  // For includes: parent key stream to inner-join with this query's FROM\n  parentKeyStream?: KeyedStream,\n  childCorrelationField?: PropRef,\n): CompilationResult {\n  // Check if the original raw query has already been compiled\n  const cachedResult = cache.get(rawQuery)\n  if (cachedResult) {\n    return cachedResult\n  }\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  validateQueryStructure(rawQuery)\n\n  // Optimize the query before compilation\n  const { optimizedQuery, sourceWhereClauses } = optimizeQuery(rawQuery)\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 = { ...inputs }\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  } = processFromClause(\n    query.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  )\n  Object.assign(sources, fromSources)\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  if (!isUnionFrom && parentKeyStream && childCorrelationField) {\n    const mainInput = sources[mainSource]!\n    let filteredMainInput = mainInput\n    // Re-key child input by correlation field: [correlationValue, [childKey, childRow]]\n    const childFieldPath = childCorrelationField.path.slice(1) // remove alias prefix\n    const childRekeyed = mainInput.pipe(\n      map(([key, row]: [unknown, any]) => {\n        const correlationValue = getNestedValue(row, childFieldPath)\n        return [correlationValue, [key, row]] as [unknown, [unknown, any]]\n      }),\n    )\n\n    // Inner join: only children whose correlation key exists in parent keys pass through\n    const joined = childRekeyed.pipe(joinOperator(parentKeyStream, `inner`))\n\n    // Extract: [correlationValue, [[childKey, childRow], parentContext]] → [childKey, childRow]\n    // Tag the row with __correlationKey for output routing\n    // If parentSide is non-null (parent context projected), attach as __parentContext\n    filteredMainInput = joined.pipe(\n      filter(([_correlationValue, [childSide]]: any) => {\n        return childSide != null\n      }),\n      map(([correlationValue, [childSide, parentSide]]: any) => {\n        const [childKey, childRow] = childSide\n        const tagged: any = { ...childRow, __correlationKey: correlationValue }\n        if (parentSide != null) {\n          tagged.__parentContext = parentSide\n        }\n        const effectiveKey =\n          parentSide != null\n            ? `${String(childKey)}::${JSON.stringify(parentSide)}`\n            : childKey\n        return [effectiveKey, tagged]\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  }\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      cache,\n      queryMapping,\n      collections,\n      subscriptions,\n      callbacks,\n      lazySources,\n      optimizableOrderByCollections,\n      setWindowFn,\n      rawQuery,\n      compileQuery,\n      aliasToCollectionId,\n      aliasRemapping,\n      sourceWhereClauses,\n    )\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          return toBooleanPredicate(fnWhere(namespacedRow))\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 includesResults: Array<IncludesCompilationResult> = !query.select\n    ? [...directIncludes]\n    : []\n  const includesRoutingFns: Array<{\n    fieldName: string\n    getRouting: (nsRow: any) => {\n      correlationKey: unknown\n      parentContext: Record<string, any> | null\n    }\n  }> = []\n  for (const { sourceAlias, include } of sourceIncludes) {\n    const projectedPaths =\n      query.select != null\n        ? findProjectedSourceIncludePaths(\n            query.select,\n            sourceAlias,\n            include.resultPath,\n          )\n        : query.fnSelect\n          ? []\n          : [\n              {\n                path: [sourceAlias, ...include.resultPath],\n                guards: [],\n              },\n            ]\n\n    if (projectedPaths.length === 0) {\n      continue\n    }\n\n    for (const { path: resultPath, guards } of projectedPaths) {\n      const fieldName = getUniqueIncludesRoutingKey(\n        `${sourceAlias}.${resultPath.join(`.`)}`,\n        includesRoutingFns,\n      )\n      const compiledGuards = guards.map((guard) => ({\n        condition: compileExpression(guard.condition),\n        expected: guard.expected,\n      }))\n      includesResults.push({\n        ...include,\n        fieldName,\n        resultPath,\n      })\n\n      includesRoutingFns.push({\n        fieldName,\n        getRouting: (nsRow: any) => {\n          if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n            return { correlationKey: null, parentContext: null }\n          }\n          return (\n            nsRow[sourceAlias]?.[INCLUDES_ROUTING]?.[include.fieldName] ?? {\n              correlationKey: null,\n              parentContext: null,\n            }\n          )\n        },\n      })\n    }\n  }\n  if (query.select && directIncludes.length > 0) {\n    for (const include of directIncludes) {\n      const projectedPaths = findProjectedResultIncludePaths(\n        query.select,\n        include.resultPath,\n      )\n\n      for (const { path: resultPath, guards } of projectedPaths) {\n        const fieldName = getUniqueIncludesRoutingKey(\n          resultPath.join(`.`),\n          includesRoutingFns,\n        )\n        const compiledGuards = guards.map((guard) => ({\n          condition: compileExpression(guard.condition),\n          expected: guard.expected,\n        }))\n\n        includesResults.push({\n          ...include,\n          fieldName,\n          resultPath,\n        })\n\n        includesRoutingFns.push({\n          fieldName,\n          getRouting: (nsRow: any) => {\n            if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n              return { correlationKey: null, parentContext: null }\n            }\n            return (\n              nsRow[INCLUDES_ROUTING]?.[include.fieldName] ?? {\n                correlationKey: null,\n                parentContext: null,\n              }\n            )\n          },\n        })\n      }\n    }\n  }\n  if (query.select) {\n    const includesEntries = extractIncludesFromSelect(query.select)\n    if (includesEntries.length > 0) {\n      query = { ...query, select: { ...query.select } }\n    }\n    for (const { key, path, subquery, guards } of includesEntries) {\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 compiledGuards = guards.map((guard) => ({\n        condition: compileExpression(guard.condition),\n        expected: guard.expected,\n      }))\n      let parentKeys: any\n      if (subquery.parentProjection && subquery.parentProjection.length > 0) {\n        const compiledProjections = subquery.parentProjection.map((ref) => ({\n          alias: ref.path[0]!,\n          field: ref.path.slice(1),\n          compiled: compileExpression(ref),\n        }))\n        parentKeys = pipeline.pipe(\n          map(([_key, nsRow]: any) => {\n            if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n              return [SKIP_INCLUDE, null] as any\n            }\n            const parentContext: Record<string, Record<string, any>> = {}\n            for (const proj of compiledProjections) {\n              if (!parentContext[proj.alias]) {\n                parentContext[proj.alias] = {}\n              }\n              const value = proj.compiled(nsRow)\n              // Set nested field in the alias namespace\n              let target = parentContext[proj.alias]!\n              for (let i = 0; i < proj.field.length - 1; i++) {\n                if (!target[proj.field[i]!]) {\n                  target[proj.field[i]!] = {}\n                }\n                target = target[proj.field[i]!]\n              }\n              target[proj.field[proj.field.length - 1]!] = value\n            }\n            return [compiledCorrelation(nsRow), parentContext] as any\n          }),\n        )\n      } else {\n        parentKeys = pipeline.pipe(\n          map(([_key, nsRow]: any) => {\n            if (!matchesConditionalSelectGuards(compiledGuards, nsRow)) {\n              return [SKIP_INCLUDE, null] as any\n            }\n            return [compiledCorrelation(nsRow), null] as any\n          }),\n        )\n      }\n      parentKeys = parentKeys.pipe(\n        filter(([correlationValue]: any) => correlationValue !== SKIP_INCLUDE),\n      )\n\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      parentKeys = parentKeys.pipe(\n        reduce((values: Array<[any, number]>) =>\n          values.map(([v, mult]) => [v, mult > 0 ? 1 : 0] as [any, number]),\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 childCorrelationAlias = 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        childCorrelationAlias,\n        subquery.childCorrelationField,\n        directChildCollection,\n        aliasRemapping,\n      )\n\n      if (lazyTargets.length > 0) {\n        // 1. Mark child source as lazy so CollectionSubscriber skips initial full load\n        for (const target of lazyTargets) {\n          lazySources.add(target.alias)\n        }\n\n        // 2. Ensure an index on the correlation field for efficient lookups\n        for (const target of lazyTargets) {\n          const targetFieldName = target.path[0]\n          if (targetFieldName) {\n            ensureIndexForField(targetFieldName, target.path, target.collection)\n          }\n        }\n\n        // 3. Tap parent keys to intercept correlation values and request\n        //    matching child rows on-demand via the child's subscription\n        parentKeys = parentKeys.pipe(\n          tap((data: any) => {\n            const joinKeys = [\n              ...new Set(\n                data\n                  .getInner()\n                  .map(\n                    ([[correlationValue]]: any) => correlationValue as unknown,\n                  )\n                  .filter((joinKey: unknown) => joinKey != null),\n              ),\n            ]\n\n            if (joinKeys.length === 0) {\n              return\n            }\n\n            for (const target of lazyTargets) {\n              const lazySourceSubscription = subscriptions[target.alias]\n\n              if (!lazySourceSubscription) {\n                continue\n              }\n\n              if (lazySourceSubscription.hasLoadedInitialState()) {\n                continue\n              }\n\n              const lazyJoinRef = new PropRef(target.path)\n              lazySourceSubscription.requestSnapshot({\n                where: inArray(lazyJoinRef, joinKeys),\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 = compileQuery(\n        childQuery,\n        allInputs,\n        collections,\n        subscriptions,\n        callbacks,\n        lazySources,\n        optimizableOrderByCollections,\n        setWindowFn,\n        cache,\n        queryMapping,\n        parentKeys,\n        subquery.childCorrelationField,\n      )\n\n      // Merge child's alias metadata into parent's\n      Object.assign(aliasToCollectionId, childResult.aliasToCollectionId)\n      Object.assign(aliasRemapping, childResult.aliasRemapping)\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: !!(\n          subquery.query.orderBy && subquery.query.orderBy.length > 0\n        ),\n        childCompilationResult: childResult,\n        parentProjection: subquery.parentProjection,\n        materialization: subquery.materialization,\n        scalarField: subquery.scalarField,\n      })\n\n      // Capture routing function for INCLUDES_ROUTING tagging\n      if (subquery.parentProjection && subquery.parentProjection.length > 0) {\n        const compiledProjs = subquery.parentProjection.map((ref) => ({\n          alias: ref.path[0]!,\n          field: ref.path.slice(1),\n          compiled: compileExpression(ref),\n        }))\n        const compiledCorr = compiledCorrelation\n        const compiledRoutingGuards = compiledGuards\n        includesRoutingFns.push({\n          fieldName,\n          getRouting: (nsRow: any) => {\n            if (!matchesConditionalSelectGuards(compiledRoutingGuards, nsRow)) {\n              return { correlationKey: null, parentContext: null }\n            }\n            const parentContext: Record<string, Record<string, any>> = {}\n            for (const proj of compiledProjs) {\n              if (!parentContext[proj.alias]) {\n                parentContext[proj.alias] = {}\n              }\n              const value = proj.compiled(nsRow)\n              let target = parentContext[proj.alias]!\n              for (let i = 0; i < proj.field.length - 1; i++) {\n                if (!target[proj.field[i]!]) {\n                  target[proj.field[i]!] = {}\n                }\n                target = target[proj.field[i]!]\n              }\n              target[proj.field[proj.field.length - 1]!] = value\n            }\n            return { correlationKey: compiledCorr(nsRow), parentContext }\n          },\n        })\n      } else {\n        const compiledRoutingGuards = compiledGuards\n        includesRoutingFns.push({\n          fieldName,\n          getRouting: (nsRow: any) => {\n            if (!matchesConditionalSelectGuards(compiledRoutingGuards, nsRow)) {\n              return { correlationKey: null, parentContext: null }\n            }\n            return {\n              correlationKey: compiledCorrelation(nsRow),\n              parentContext: null,\n            }\n          },\n        })\n      }\n\n      // Replace includes entry in select with a null placeholder\n      query = {\n        ...query,\n        select: replaceIncludesInSelect(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  // 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 selectResults = query.fnSelect!(namespacedRow)\n        if (selectResults && typeof selectResults === `object`) {\n          const routing = (namespacedRow as any)[INCLUDES_ROUTING]\n          if (routing) {\n            selectResults[INCLUDES_ROUTING] = routing\n          }\n          if (directIncludes.length > 0) {\n            Object.defineProperty(selectResults, FN_SELECT_STATE, {\n              value: {\n                sourceRow: namespacedRow,\n                fnSelect: query.fnSelect!,\n              },\n              enumerable: true,\n              configurable: true,\n            })\n          }\n        }\n        return [\n          key,\n          {\n            ...namespacedRow,\n            $selected: selectResults,\n          },\n        ] as [string, typeof namespacedRow & { $selected: any }]\n      }),\n    )\n  } else if (query.select) {\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 selectResults =\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 for includes.\n  // This lets collection-config-builder extract routing info (correlationKey + parentContext)\n  // from parent results without depending on the user's select.\n  if (includesRoutingFns.length > 0) {\n    pipeline = pipeline.pipe(\n      map(([key, namespacedRow]: any) => {\n        const routing: Record<\n          string,\n          { correlationKey: unknown; parentContext: Record<string, any> | null }\n        > = {}\n        for (const { fieldName, getRouting } of includesRoutingFns) {\n          routing[fieldName] = getRouting(namespacedRow)\n        }\n        namespacedRow.$selected[INCLUDES_ROUTING] = routing\n        return [key, namespacedRow]\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 __correlationKey for per-parent aggregation.\n  const groupByMainSource = parentKeyStream ? mainSource : undefined\n  if (query.groupBy && query.groupBy.length > 0) {\n    pipeline = processGroupBy(\n      pipeline,\n      query.groupBy,\n      query.having,\n      query.select,\n      query.fnHaving,\n      mainCollectionId,\n      groupByMainSource,\n    )\n  } else if (query.select) {\n    // Check if SELECT contains aggregates but no GROUP BY (implicit single-group aggregation)\n    const hasAggregates = Object.values(query.select).some(\n      (expr) => expr.type === `agg` || containsAggregate(expr),\n    )\n    if (hasAggregates) {\n      // Handle implicit single-group aggregation\n      pipeline = processGroupBy(\n        pipeline,\n        [], // Empty group by means single group\n        query.having,\n        query.select,\n        query.fnHaving,\n        mainCollectionId,\n        groupByMainSource,\n      )\n    }\n  }\n\n  // Process the HAVING clause if it exists (only applies after GROUP BY)\n  if (query.having && (!query.groupBy || query.groupBy.length === 0)) {\n    // Check if we have aggregates in SELECT that would trigger implicit grouping\n    const hasAggregates = query.select\n      ? Object.values(query.select).some((expr) => expr.type === `agg`)\n      : false\n\n    if (!hasAggregates) {\n      throw new HavingRequiresGroupByError()\n    }\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          return fnHaving(namespacedRow)\n        }),\n      )\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  // Process orderBy parameter if it exists\n  if (query.orderBy && query.orderBy.length > 0) {\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      (query.limit !== undefined || query.offset !== undefined)\n        ? (_key: unknown, row: unknown) => {\n            const correlationKey = (row as any)?.[mainSource]?.__correlationKey\n            const parentContext = (row as any)?.__parentContext\n            if (parentContext != null) {\n              return JSON.stringify([correlationKey, parentContext])\n            }\n            return correlationKey\n          }\n        : undefined\n\n    const orderedPipeline = processOrderBy(\n      rawQuery,\n      pipeline,\n      query.orderBy,\n      query.select || {},\n      collections[mainCollectionId]!,\n      optimizableOrderByCollections,\n      setWindowFn,\n      query.limit,\n      query.offset,\n      includesGroupKeyFn,\n    )\n\n    // Final step: extract the $selected and include orderBy index\n    const resultPipeline: ResultStream = orderedPipeline.pipe(\n      map(([key, [row, orderByIndex]]) => {\n        // Extract the final results from $selected and include orderBy index\n        const raw = (row as any).$selected\n        const finalResults = attachVirtualPropsToSelected(\n          unwrapValue(raw),\n          row as Record<string, any>,\n        )\n        // When in includes mode, embed the correlation key and parentContext\n        if (parentKeyStream) {\n          const correlationKey = (row as any)[mainSource]?.__correlationKey\n          const parentContext = (row as any).__parentContext ?? null\n          // Strip internal routing properties that may leak via spread selects\n          delete finalResults.__correlationKey\n          delete finalResults.__parentContext\n          return [\n            key,\n            [finalResults, orderByIndex, correlationKey, parentContext],\n          ] as any\n        }\n        return [key, [finalResults, orderByIndex]] as [unknown, [any, string]]\n      }),\n    ) as ResultStream\n\n    const result = resultPipeline\n    // Cache the result before returning (use original query as key)\n    const compilationResult: CompilationResult = {\n      collectionId: mainCollectionId,\n      pipeline: result,\n      sourceWhereClauses,\n      aliasToCollectionId,\n      aliasRemapping,\n      includes: includesResults.length > 0 ? includesResults : undefined,\n    }\n    cache.set(rawQuery, compilationResult)\n\n    return compilationResult\n  } else if (query.limit !== undefined || query.offset !== undefined) {\n    // If there's a limit or offset without orderBy, throw an error\n    throw new LimitOffsetRequireOrderByError()\n  }\n\n  // Final step: extract the $selected and return tuple format (no orderBy)\n  const resultPipeline: ResultStream = pipeline.pipe(\n    map(([key, row]) => {\n      // Extract the final results from $selected and return [key, [results, undefined]]\n      const raw = (row as any).$selected\n      const finalResults = attachVirtualPropsToSelected(\n        unwrapValue(raw),\n        row as Record<string, any>,\n      )\n      // When in includes mode, embed the correlation key and parentContext\n      if (parentKeyStream) {\n        const correlationKey = (row as any)[mainSource]?.__correlationKey\n        const parentContext = (row as any).__parentContext ?? null\n        // Strip internal routing properties that may leak via spread selects\n        delete finalResults.__correlationKey\n        delete finalResults.__parentContext\n        return [\n          key,\n          [finalResults, undefined, correlationKey, parentContext],\n        ] as any\n      }\n      return [key, [finalResults, undefined]] as [\n        unknown,\n        [any, string | undefined],\n      ]\n    }),\n  )\n\n  const result = resultPipeline\n  // Cache the result before returning (use original query as key)\n  const compilationResult: CompilationResult = {\n    collectionId: mainCollectionId,\n    pipeline: result,\n    sourceWhereClauses,\n    aliasToCollectionId,\n    aliasRemapping,\n    includes: includesResults.length > 0 ? includesResults : undefined,\n  }\n  cache.set(rawQuery, compilationResult)\n\n  return compilationResult\n}\n\n/**\n * Collects aliases used for DIRECT collection references (not subqueries).\n * Used to validate that subqueries don't reuse parent query collection aliases.\n * Only direct CollectionRef aliases matter - QueryRef aliases don't cause conflicts.\n */\nfunction collectDirectCollectionAliases(query: QueryIR): Set<string> {\n  const aliases = new Set<string>()\n\n  // Collect FROM alias only if it's a direct collection reference\n  for (const source of getFromSources(query.from)) {\n    if (source.type === `collectionRef`) {\n      aliases.add(source.alias)\n    }\n  }\n\n  // Collect JOIN aliases only for direct collection references\n  if (query.join) {\n    for (const joinClause of query.join) {\n      if (joinClause.from.type === `collectionRef`) {\n        aliases.add(joinClause.from.alias)\n      }\n    }\n  }\n\n  return aliases\n}\n\n/**\n * Validates the structure of a query and its subqueries.\n * Checks that subqueries don't reuse collection aliases from parent queries.\n * This must be called on the RAW query before optimization.\n */\nfunction validateQueryStructure(\n  query: QueryIR,\n  parentCollectionAliases: Set<string> = new Set(),\n): void {\n  // Collect direct collection aliases from this query level\n  const currentLevelAliases = collectDirectCollectionAliases(query)\n\n  // Check if any current alias conflicts with parent aliases\n  for (const alias of currentLevelAliases) {\n    if (parentCollectionAliases.has(alias)) {\n      throw new DuplicateAliasInSubqueryError(\n        alias,\n        Array.from(parentCollectionAliases),\n      )\n    }\n  }\n\n  // Combine parent and current aliases for checking nested subqueries\n  const combinedAliases = new Set([\n    ...parentCollectionAliases,\n    ...currentLevelAliases,\n  ])\n\n  // Recursively validate FROM subqueries\n  if (query.from.type === `unionAll`) {\n    for (const branch of query.from.queries) {\n      validateQueryStructure(branch, combinedAliases)\n    }\n  } else {\n    for (const source of getFromSources(query.from)) {\n      if (source.type === `queryRef`) {\n        validateQueryStructure(source.query, combinedAliases)\n      }\n    }\n  }\n\n  // Recursively validate JOIN subqueries\n  if (query.join) {\n    for (const joinClause of query.join) {\n      if (joinClause.from.type === `queryRef`) {\n        validateQueryStructure(joinClause.from.query, combinedAliases)\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: CollectionRef | QueryRef | UnionFrom | 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): {\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} {\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    )\n  }\n\n  if (from.type !== `unionFrom`) {\n    const { alias, input, collectionId, sourceIncludes } = processFrom(\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    )\n\n    return {\n      alias,\n      pipeline: wrapInputWithAlias(input, alias),\n      collectionId,\n      sources: { [alias]: input },\n      sourceIncludes,\n      directIncludes: [],\n      isUnionFrom: false,\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    } = processFrom(\n      source,\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    )\n\n    if (!mainAlias) {\n      mainAlias = alias\n      mainCollectionId = collectionId\n    }\n    sources[alias] = input\n    sourceIncludes.push(...childSourceIncludes)\n\n    const branch = wrapInputWithAlias(input, alias).pipe(\n      map(([key, row]) => {\n        return [`${alias}:${encodeKeyForUnionBranch(key)}`, row] as [\n          string,\n          typeof row,\n        ]\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  }\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): {\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} {\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          `Duplicate source alias \"${source.alias}\" in unionAll query branches. ` +\n            `Use distinct aliases in each branch before passing them to unionAll().`,\n        )\n      }\n      branchAliases.add(source.alias)\n    }\n    const branchResult = compileQuery(\n      branch,\n      allInputs,\n      collections,\n      subscriptions,\n      callbacks,\n      lazySources,\n      optimizableOrderByCollections,\n      setWindowFn,\n      cache,\n      queryMapping,\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(([key, [row]]) => {\n        return [`${index}:${encodeKeyForUnionBranch(key)}`, row] as [\n          string,\n          Record<string, any>,\n        ]\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  }\n}\n\nfunction wrapInputWithAlias(\n  input: KeyedStream,\n  alias: string,\n): NamespacedAndKeyedStream {\n  return input.pipe(\n    map(([key, row]) => {\n      // Initialize the record with a nested structure.\n      // If __parentContext exists (from parent-referencing includes), merge parent\n      // aliases into the namespaced row so WHERE can resolve parent refs.\n      const { __parentContext, ...cleanRow } = row as any\n      const nsRow: Record<string, any> = { [alias]: cleanRow }\n      if (__parentContext) {\n        Object.assign(nsRow, __parentContext)\n        ;(nsRow as any).__parentContext = __parentContext\n      }\n      return [key, nsRow] as [unknown, Record<string, typeof row>]\n    }),\n  )\n}\n\nfunction encodeKeyForUnionBranch(key: unknown): string {\n  if (typeof key === `string`) {\n    return `string:${key}`\n  }\n  if (typeof key === `number`) {\n    return `number:${String(key)}`\n  }\n  if (typeof key === `bigint`) {\n    return `bigint:${String(key)}`\n  }\n  return `${typeof key}:${JSON.stringify(key)}`\n}\n\nfunction processFrom(\n  from: CollectionRef | QueryRef,\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): {\n  alias: string\n  input: KeyedStream\n  collectionId: string\n  sourceIncludes: Array<SourceInclude>\n} {\n  switch (from.type) {\n    case `collectionRef`: {\n      const input = allInputs[from.alias]\n      if (!input) {\n        throw new CollectionInputNotFoundError(\n          from.alias,\n          from.collection.id,\n          Object.keys(allInputs),\n        )\n      }\n      aliasToCollectionId[from.alias] = from.collection.id\n      return {\n        alias: from.alias,\n        input,\n        collectionId: from.collection.id,\n        sourceIncludes: [],\n      }\n    }\n    case `queryRef`: {\n      // Find the original query for caching purposes\n      const originalQuery = queryMapping.get(from.query) || from.query\n\n      // Recursively compile the sub-query with cache\n      const subQueryResult = compileQuery(\n        originalQuery,\n        allInputs,\n        collections,\n        subscriptions,\n        callbacks,\n        lazySources,\n        optimizableOrderByCollections,\n        setWindowFn,\n        cache,\n        queryMapping,\n      )\n\n      // Pull up alias mappings from subquery to parent scope.\n      // This includes both the innermost alias-to-collection mappings AND\n      // any existing remappings from nested subquery levels.\n      Object.assign(aliasToCollectionId, subQueryResult.aliasToCollectionId)\n      Object.assign(aliasRemapping, subQueryResult.aliasRemapping)\n\n      // Pull up source WHERE clauses from subquery to parent scope.\n      // This enables loadSubset to receive the correct where clauses for subquery collections.\n      //\n      // IMPORTANT: Skip pull-up for optimizer-created subqueries. These are detected when:\n      // 1. The outer alias (from.alias) matches the inner alias (from.query.from.alias)\n      // 2. The subquery was found in queryMapping (it's a user-defined subquery, not optimizer-created)\n      //\n      // For optimizer-created subqueries, the parent already has the sourceWhereClauses\n      // extracted from the original raw query, so pulling up would be redundant.\n      // More importantly, pulling up for optimizer-created subqueries can cause issues\n      // when the optimizer has restructured the query.\n      const isUserDefinedSubquery = queryMapping.has(from.query)\n      const subqueryFromAlias = getFirstFromAlias(from.query.from)\n      const isOptimizerCreated =\n        !isUserDefinedSubquery && from.alias === subqueryFromAlias\n\n      if (!isOptimizerCreated) {\n        for (const [alias, whereClause] of subQueryResult.sourceWhereClauses) {\n          sourceWhereClauses.set(alias, whereClause)\n        }\n      }\n\n      // Create a FLATTENED remapping from outer alias to innermost alias.\n      // For nested subqueries, this ensures one-hop lookups (not recursive chains).\n      //\n      // Example with 3-level nesting:\n      //   Inner:  .from({ user: usersCollection })\n      //   Middle: .from({ activeUser: innerSubquery })     → creates: activeUser → user\n      //   Outer:  .from({ author: middleSubquery })        → creates: author → user (not author → activeUser)\n      //\n      // The key insight: We search through the PULLED-UP aliasToCollectionId (which contains\n      // the innermost 'user' alias), so we always map directly to the deepest level.\n      // This means aliasRemapping[alias] is always a single lookup, never recursive.\n      // Needed for subscription resolution during lazy loading.\n      const innerAlias = Object.keys(subQueryResult.aliasToCollectionId).find(\n        (alias) =>\n          subQueryResult.aliasToCollectionId[alias] ===\n          subQueryResult.collectionId,\n      )\n      if (innerAlias && innerAlias !== from.alias) {\n        aliasRemapping[from.alias] = innerAlias\n      }\n\n      // Extract the pipeline from the compilation result\n      const subQueryInput = subQueryResult.pipeline\n\n      // Subqueries may return [key, [value, orderByIndex]] (with ORDER BY) or [key, value] (without ORDER BY)\n      // We need to extract just the value for use in parent queries\n      const extractedInput = subQueryInput.pipe(\n        map((data: any) => {\n          const [key, [value, _orderByIndex]] = data\n          // Unwrap Value expressions that might have leaked through as the entire row\n          const unwrapped = unwrapValue(value)\n          return [key, unwrapped] as [unknown, any]\n        }),\n      )\n\n      return {\n        alias: from.alias,\n        input: extractedInput,\n        collectionId: subQueryResult.collectionId,\n        sourceIncludes:\n          subQueryResult.includes?.map((include) => ({\n            sourceAlias: from.alias,\n            include,\n          })) ?? [],\n      }\n    }\n    default:\n      throw new UnsupportedFromTypeError((from as any).type)\n  }\n}\n\n// Helper to check if a value is a Value expression\nfunction isValue(raw: any): boolean {\n  return (\n    raw instanceof ValClass ||\n    (raw && typeof raw === `object` && `type` in raw && raw.type === `val`)\n  )\n}\n\n// Helper to unwrap a Value expression or return the value itself\nfunction unwrapValue(value: any): any {\n  return isValue(value) ? value.value : value\n}\n\nfunction attachVirtualPropsToSelected(\n  selected: any,\n  row: Record<string, any>,\n): any {\n  if (!selected || typeof selected !== `object`) {\n    return selected\n  }\n\n  let needsMerge = false\n  for (const prop of VIRTUAL_PROP_NAMES) {\n    if (selected[prop] == null && prop in row) {\n      needsMerge = true\n      break\n    }\n  }\n\n  if (!needsMerge) {\n    return selected\n  }\n\n  for (const prop of VIRTUAL_PROP_NAMES) {\n    if (selected[prop] == null && prop in row) {\n      selected[prop] = row[prop]\n    }\n  }\n\n  return selected\n}\n\n/**\n * Recursively maps optimized subqueries to their original queries for proper caching.\n * This ensures that when we encounter the same QueryRef object in different contexts,\n * we can find the original query to check the cache.\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      const optimizedJoin = optimizedQuery.join[i]!\n      const originalJoin = originalQuery.join[i]!\n\n      if (\n        optimizedJoin.from.type === `queryRef` &&\n        originalJoin.from.type === `queryRef`\n      ) {\n        queryMapping.set(optimizedJoin.from.query, originalJoin.from.query)\n        // Recursively map nested queries in joins\n        mapNestedQueries(\n          optimizedJoin.from.query,\n          originalJoin.from.query,\n          queryMapping,\n        )\n      }\n    }\n  }\n}\n\nfunction getRefFromAlias(\n  query: QueryIR,\n  alias: string,\n): CollectionRef | QueryRef | void {\n  for (const source of getFromSources(query.from)) {\n    if (source.alias === alias) {\n      return source\n    }\n  }\n\n  for (const join of query.join || []) {\n    if (join.from.alias === alias) {\n      return join.from\n    }\n  }\n}\n\nfunction getFromSources(\n  from: QueryIR[`from`],\n): Array<CollectionRef | QueryRef> {\n  if (from.type === `unionFrom`) {\n    return from.sources\n  }\n  if (from.type === `unionAll`) {\n    return []\n  }\n  return [from]\n}\n\nfunction getAllSources(query: QueryIR): Array<CollectionRef | QueryRef> {\n  return [\n    ...getFromSources(query.from),\n    ...(query.join?.map((join) => join.from) ?? []),\n  ]\n}\n\nfunction getFirstFromAlias(from: QueryIR[`from`]): string {\n  return getFromSources(from)[0]?.alias ?? ``\n}\n\nfunction findProjectedSourceIncludePaths(\n  select: Record<string, any>,\n  sourceAlias: string,\n  sourcePath: Array<string>,\n): Array<ProjectedSourceIncludePath> {\n  const targetPath = [sourceAlias, ...sourcePath]\n  return findProjectedIncludePaths(select, targetPath)\n}\n\nfunction findProjectedResultIncludePaths(\n  select: Record<string, any>,\n  resultPath: Array<string>,\n): Array<ProjectedSourceIncludePath> {\n  return findProjectedIncludePaths(select, resultPath)\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      const previousBranchGuards: Array<ConditionalSelectGuard> = []\n      for (const branch of value.branches) {\n        visitSelectValue(branch.value, path, [\n          ...guards,\n          ...previousBranchGuards,\n          { condition: branch.condition, expected: true },\n        ])\n        previousBranchGuards.push({\n          condition: branch.condition,\n          expected: false,\n        })\n      }\n      if (value.defaultValue !== undefined) {\n        visitSelectValue(value.defaultValue, path, [\n          ...guards,\n          ...previousBranchGuards,\n        ])\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 * Follows the given reference in a query\n * until its finds the root field the reference points to.\n * @returns The collection, its alias, and the path to the root field in this collection\n */\nexport function followRef(\n  query: QueryIR,\n  ref: PropRef<any>,\n  collection: Collection,\n): { collection: Collection; path: Array<string> } | void {\n  if (ref.path.length === 0) {\n    return\n  }\n\n  if (ref.path.length === 1) {\n    // This field should be part of this collection\n    const field = ref.path[0]!\n    // is it part of the select clause?\n    if (query.select) {\n      const selectedField = query.select[field]\n      if (selectedField && selectedField.type === `ref`) {\n        return followRef(query, selectedField, collection)\n      }\n    }\n\n    // Either this field is not part of the select clause\n    // and thus it must be part of the collection itself\n    // or it is part of the select but is not a reference\n    // so we can stop here and don't have to follow it\n    return { collection, path: [field] }\n  }\n\n  if (ref.path.length > 1) {\n    // This is a nested field\n    const [alias, ...rest] = ref.path\n    const aliasRef = getRefFromAlias(query, alias!)\n    if (!aliasRef) {\n      return\n    }\n\n    if (aliasRef.type === `queryRef`) {\n      return followRef(aliasRef.query, new PropRef(rest), collection)\n    } else {\n      // This is a reference to a collection\n      // we can't follow it further\n      // so the field must be on the collection itself\n      return { collection: aliasRef.collection, path: rest }\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 (value instanceof IncludesSubquery) {\n      results.push({\n        key: getIncludesRoutingKey([key], results),\n        path: [key],\n        subquery: value,\n        guards: [],\n      })\n    } else if (value instanceof ConditionalSelect) {\n      collectIncludesFromConditionalSelect(value, [key], [], results)\n    } else if (isNestedSelectObject(value)) {\n      // Check nested objects for IncludesSubquery — not supported yet\n      assertNoNestedIncludes(value, key)\n    }\n  }\n  return results\n}\n\nfunction collectIncludesFromConditionalSelect(\n  conditional: ConditionalSelect,\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  const previousBranchGuards: Array<ConditionalSelectGuard> = []\n  for (const branch of conditional.branches) {\n    collectIncludesFromSelectValue(\n      branch.value,\n      prefixPath,\n      [\n        ...guards,\n        ...previousBranchGuards,\n        { condition: branch.condition, expected: true },\n      ],\n      results,\n    )\n    previousBranchGuards.push({\n      condition: branch.condition,\n      expected: false,\n    })\n  }\n\n  if (conditional.defaultValue !== undefined) {\n    collectIncludesFromSelectValue(\n      conditional.defaultValue,\n      prefixPath,\n      [...guards, ...previousBranchGuards],\n      results,\n    )\n  }\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 = getIncludesRoutingKey(prefixPath, results)\n    results.push({ key, path: prefixPath, subquery: value, guards })\n    return\n  }\n\n  if (value instanceof ConditionalSelect) {\n    collectIncludesFromConditionalSelect(value, prefixPath, guards, results)\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 getIncludesRoutingKey(\n  path: Array<string>,\n  entries: Array<{ key: string }>,\n): string {\n  return getUniqueIncludesRoutingKey(path.join(`.`), entries)\n}\n\nfunction getUniqueIncludesRoutingKey(\n  baseKey: string,\n  entries: Array<{ key?: string; fieldName?: string }>,\n): string {\n  const hasKey = (key: string) =>\n    entries.some((entry) => (entry.key ?? entry.fieldName) === key)\n\n  if (!hasKey(baseKey)) {\n    return baseKey\n  }\n\n  let suffix = entries.length\n  let key = `${baseKey}#${suffix}`\n  while (hasKey(key)) {\n    suffix++\n    key = `${baseKey}#${suffix}`\n  }\n  return key\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  )\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        `Includes subqueries must be at the top level of select(). ` +\n          `Found nested includes at \"${parentPath}.${key}\".`,\n      )\n    }\n    if (isNestedSelectObject(value)) {\n      assertNoNestedIncludes(value, `${parentPath}.${key}`)\n    }\n  }\n}\n\n/**\n * Replaces an IncludesSubquery entry in the select object with a null Value placeholder.\n * This ensures processSelect() doesn't encounter it.\n */\nfunction replaceIncludesInSelect(\n  select: Record<string, any>,\n  path: Array<string>,\n): Record<string, any> {\n  return replaceIncludesInSelectValue(select, path, new ValClass(null)).value\n}\n\nfunction replaceIncludesInSelectValue(\n  value: any,\n  path: Array<string>,\n  replacement: ValClass,\n): { value: any; replaced: boolean } {\n  if (path.length === 0) {\n    return replaceIncludesValue(value, replacement)\n  }\n\n  if (value instanceof ConditionalSelect) {\n    return replaceIncludesInConditionalSelect(value, path, replacement)\n  }\n\n  if (!isNestedSelectObject(value)) {\n    return { value, replaced: false }\n  }\n\n  if (path.length === 1) {\n    const field = path[0]!\n    const result = replaceIncludesValue(value[field], replacement)\n    if (!result.replaced) {\n      return { value, replaced: false }\n    }\n    return {\n      value: {\n        ...value,\n        [field]: result.value,\n      },\n      replaced: true,\n    }\n  }\n\n  const [head, ...rest] = path\n  const result = replaceIncludesInSelectValue(value[head!], rest, replacement)\n  if (!result.replaced) {\n    return { value, replaced: false }\n  }\n  return {\n    value: {\n      ...value,\n      [head!]: result.value,\n    },\n    replaced: true,\n  }\n}\n\nfunction replaceIncludesValue(\n  value: any,\n  replacement: ValClass,\n): { value: any; replaced: boolean } {\n  if (value instanceof IncludesSubquery) {\n    return { value: replacement, replaced: true }\n  }\n\n  if (value instanceof ConditionalSelect) {\n    return replaceIncludesInConditionalSelect(value, [], replacement)\n  }\n\n  return { value, replaced: false }\n}\n\nfunction replaceIncludesInConditionalSelect(\n  conditional: ConditionalSelect,\n  path: Array<string>,\n  replacement: ValClass,\n): { value: ConditionalSelect; replaced: boolean } {\n  let replaced = false\n  const branches = conditional.branches.map((branch) => {\n    const result =\n      path.length === 0\n        ? replaceIncludesValue(branch.value, replacement)\n        : replaceIncludesInSelectValue(branch.value, path, replacement)\n    if (!result.replaced) {\n      return branch\n    }\n    replaced = true\n    return { ...branch, value: result.value }\n  })\n\n  let defaultValue = conditional.defaultValue\n  if (conditional.defaultValue !== undefined) {\n    const result =\n      path.length === 0\n        ? replaceIncludesValue(conditional.defaultValue, replacement)\n        : replaceIncludesInSelectValue(\n            conditional.defaultValue,\n            path,\n            replacement,\n          )\n    if (result.replaced) {\n      replaced = true\n      defaultValue = result.value\n    }\n  }\n\n  if (!replaced) {\n    return { value: conditional, replaced: false }\n  }\n\n  return {\n    value: new ConditionalSelect(branches, defaultValue),\n    replaced: true,\n  }\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\nfunction matchesConditionalSelectGuards(\n  guards: Array<{\n    condition: (row: any) => any\n    expected: boolean\n  }>,\n  row: any,\n): boolean {\n  return guards.every(\n    (guard) => isCaseWhenConditionTrue(guard.condition(row)) === guard.expected,\n  )\n}\n\nexport type CompileQueryFn = typeof compileQuery\n"],"names":["optimizeQuery","map","joinOperator","filter","processJoins","getWhereExpression","compileExpression","toBooleanPredicate","reduce","lazyTargets","getLazyLoadTargets","ensureIndexForField","tap","PropRef","inArray","DistinctRequiresSelectError","FnSelectWithGroupByError","processSelect","processGroupBy","containsAggregate","HavingRequiresGroupByError","distinct","processOrderBy","resultPipeline","result","compilationResult","LimitOffsetRequireOrderByError","DuplicateAliasInSubqueryError","sourceIncludes","UnsupportedFromTypeError","concatOperator","CollectionInputNotFoundError","ValClass","VIRTUAL_PROP_NAMES","select","ConditionalSelect","IncludesSubquery","key","isExpressionLike","isCaseWhenConditionTrue"],"mappings":";;;;;;;;;;;;;;;AA+DO,MAAM,0CAA0B,iBAAiB;AACjD,MAAM,yCAAyB,eAAe;AACrD,MAAM,sCAAsB,aAAa;AAgGlC,SAAS,aACd,UACA,QACA,aACA,eACA,WACA,aACA,+BACA,aACA,QAAoB,oBAAI,WACxB,mCAAiC,QAAA,GAEjC,iBACA,uBACmB;AAEnB,QAAM,eAAe,MAAM,IAAI,QAAQ;AACvC,MAAI,cAAc;AAChB,WAAO;AAAA,EACT;AAKA,yBAAuB,QAAQ;AAG/B,QAAM,EAAE,gBAAgB,uBAAuBA,UAAAA,cAAc,QAAQ;AAErE,MAAI,QAAQ;AAGZ,eAAa,IAAI,OAAO,QAAQ;AAChC,mBAAiB,OAAO,UAAU,YAAY;AAG9C,QAAM,YAAY,EAAE,GAAG,OAAA;AAIvB,QAAM,sBAA8C,CAAA;AAKpD,QAAM,iBAAyC,CAAA;AAM/C,QAAM,UAAuC,CAAA;AAG7C,QAAM;AAAA,IACJ,OAAO;AAAA,IACP,cAAc;AAAA,IACd,UAAU;AAAA,IACV,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,EAAA,IACE;AAAA,IACF,MAAM;AA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