{"version":3,"file":"group-by.cjs","names":["getEqualityValueIdentity","normalizedKey","serializeValue","INCLUDES_PUBLIC_KEY","isTemporal","getNamespacedRouteMetadata","getParentContextIdentity","getParentContextValue","NonAggregateExpressionNotInGroupByError","compileExpression","groupBy","map","getHavingExpression","filter","toBooleanPredicate","stripInternalCallbackMetadata","isExpressionLike","deepEquals","groupByOperators","UnsupportedAggregateFunctionError","PropRef","AggregateFunctionNotInSelectError","Func","UnknownHavingExpressionTypeError","ConditionalSelect","isCaseWhenConditionTrue","isRefProxy"],"sources":["../../../../src/query/compiler/group-by.ts"],"sourcesContent":["import {\n  filter,\n  groupBy,\n  groupByOperators,\n  map,\n  serializeValue,\n} from '@tanstack/db-ivm'\nimport {\n  ConditionalSelect,\n  Func,\n  PropRef,\n  getHavingExpression,\n  isExpressionLike,\n} from '../ir.js'\nimport { isRefProxy } from '../builder/ref-proxy-identity.js'\nimport { deepEquals, isTemporal } from '../../utils.js'\nimport { normalizedKey } from '../../utils/comparison.js'\nimport {\n  AggregateFunctionNotInSelectError,\n  NonAggregateExpressionNotInGroupByError,\n  UnknownHavingExpressionTypeError,\n  UnsupportedAggregateFunctionError,\n} from '../../errors.js'\nimport {\n  getEqualityValueIdentity,\n  getParentContextIdentity,\n  getParentContextValue,\n} from '../equality-value-identity.js'\nimport {\n  compileExpression,\n  isCaseWhenConditionTrue,\n  toBooleanPredicate,\n} from './evaluators.js'\nimport {\n  INCLUDES_PUBLIC_KEY,\n  attachRouteMetadata,\n  getNamespacedRouteMetadata,\n  stripInternalCallbackMetadata,\n} from './route-metadata.js'\nimport type { ValueIdentity } from '../equality-value-identity.js'\nimport type { RouteMetadata } from './route-metadata.js'\nimport type {\n  Aggregate,\n  BasicExpression,\n  GroupBy,\n  Having,\n  Select,\n  SelectValueExpression,\n} from '../ir.js'\nimport type { NamespacedAndKeyedStream, NamespacedRow } from '../../types.js'\n\nconst RAW_REPRESENTATIVE = Symbol(`raw_group_representative`)\n\ntype InternalGroupFields = ReturnType<typeof createInternalGroupFields>\n\nfunction createInternalGroupFields(groupCount: number, selectClause?: Select) {\n  const aliases = Object.keys(selectClause ?? {})\n  let prefix = `__tanstack_group_`\n  while (aliases.some((alias) => alias.startsWith(prefix))) prefix += `_`\n\n  return {\n    route: `${prefix}route`,\n    exactInputs: `${prefix}exact_inputs`,\n    correlationIdentity: `${prefix}correlation_identity`,\n    parentContextIdentity: `${prefix}parent_context_identity`,\n    singleGroup: `${prefix}single_group`,\n    aggregatePrefix: `${prefix}aggregate_`,\n    groupKeys: Array.from(\n      { length: groupCount },\n      (_, i) => `${prefix}key_${i}`,\n    ),\n    groupValues: Array.from(\n      { length: groupCount },\n      (_, i) => `${prefix}value_${i}`,\n    ),\n    groupKeyRefs: Array.from(\n      { length: groupCount },\n      (_, i) => `${prefix}key_ref_${i}`,\n    ),\n  }\n}\n\ntype Representative<T> = {\n  key: string\n  [RAW_REPRESENTATIVE]: T\n}\n\nfunction createPublicGroupKey(values: Array<unknown>): unknown {\n  const identities = values.map(getEqualityValueIdentity)\n  if (identities.length === 1) {\n    const identity = identities[0]\n    if (typeof identity === `string` || typeof identity === `number`) {\n      return identity\n    }\n    // Collection keys are strings or numbers. Another primitive group value,\n    // such as `null`, `undefined`, or a boolean, keys its group in the\n    // namespace that `normalizeValue` reserves. No string group value\n    // occupies that namespace, so the key cannot collide with one.\n    if (\n      identity == null ||\n      (typeof identity !== `object` &&\n        typeof identity !== `function` &&\n        typeof identity !== `symbol`)\n    ) {\n      return normalizedKey(typeof identity, String(identity))\n    }\n  }\n  return serializeValue(identities)\n}\n\nfunction attachPublicGroupKey(\n  row: Record<string, any>,\n  publicKey: unknown,\n): void {\n  const keyedRow = row as Record<PropertyKey, unknown>\n  keyedRow[INCLUDES_PUBLIC_KEY] = publicKey\n}\n\nfunction createRepresentative<T>(\n  value: T,\n  identity: unknown,\n): Representative<T> {\n  // Encode once per contribution, not once per member on every group change.\n  // D2 consolidates contributions that hash equal (groupBy finds them by an\n  // identity string that is equal for exactly those). The identity must\n  // therefore separate every exactly different value, so a merged\n  // contribution never projects a value that no positive member holds.\n  const representative = {\n    key: serializeValue(identity),\n  } as Representative<T>\n  Object.defineProperty(representative, RAW_REPRESENTATIVE, { value })\n  return representative\n}\n\n/**\n * Members equal under query equality supply the value with the smallest exact\n * value: another primitive before -0, and every primitive before an object.\n * Objects are ordered by an explicit type tag, so the order survives\n * minification. Members of one tag are equal in content, so the smallest row\n * key decides among them: the choice does not depend on arrival order, and\n * the instance comes from a current member. Equal primitives share a key and\n * consolidate.\n *\n * The key is compared as a serialized string. Its first two parts have a\n * fixed format (a one-digit rank and a quoted tag), so the string order\n * matches the order above; the last part only breaks ties.\n */\nfunction exactValueKey(\n  value: unknown,\n  rowKey: string,\n  valueIdentity: ValueIdentity,\n): unknown {\n  if (Object.is(value, -0)) return [1, ``, ``]\n  if (value === null || typeof value !== `object`) {\n    return [0, ``, valueIdentity.exact(value)]\n  }\n  return [2, exactObjectTag(value), rowKey]\n}\n\nfunction exactObjectTag(value: object): string {\n  if (value instanceof Date) return `Date`\n  if (isTemporal(value)) return (value as any)[Symbol.toStringTag]\n  if (typeof Buffer !== `undefined` && value instanceof Buffer) return `Buffer`\n  return value instanceof Uint8Array ? `Uint8Array` : `Object`\n}\n\nfunction getRepresentative<T>(\n  values: Array<[Representative<T>, number]>,\n): Representative<T> | undefined {\n  let selected: Representative<T> | undefined\n  for (const [candidate, multiplicity] of values) {\n    if (multiplicity <= 0) continue\n    if (selected === undefined || candidate.key < selected.key) {\n      selected = candidate\n    }\n  }\n  return selected\n}\n\nfunction unwrapRepresentative<T>(\n  value: Representative<T> | undefined,\n): T | undefined {\n  return value?.[RAW_REPRESENTATIVE]\n}\n\nfunction addCorrelationRouteIdentityToGroupKey(\n  key: Record<string, unknown>,\n  row: NamespacedRow,\n  mainSource: string,\n  fields: InternalGroupFields,\n  valueIdentity: ValueIdentity,\n): void {\n  const route = getNamespacedRouteMetadata(row, mainSource)\n  key[fields.correlationIdentity] = valueIdentity.equality(\n    route?.correlationKey,\n  )\n  if (route?.parentContext != null) {\n    key[fields.parentContextIdentity] = getParentContextIdentity(\n      route.parentContext,\n    )\n  }\n}\n\n/** One representative carries the whole route so both parts come from one row. */\nfunction addCorrelationRouteAggregate(\n  aggregates: Record<string, any>,\n  mainSource: string,\n  fields: InternalGroupFields,\n  valueIdentity: ValueIdentity,\n): void {\n  aggregates[fields.route] = {\n    preMap: ([, row]: [string, NamespacedRow]) => {\n      const route = getNamespacedRouteMetadata(row, mainSource)\n      // Members of one route share its correlation key and parent context\n      // instances, so they consolidate into one contribution. A changed\n      // parent builds a new context, which stays separate.\n      return createRepresentative(route, [\n        valueIdentity.exact(route?.correlationKey),\n        valueIdentity.exact(route?.parentContext),\n      ])\n    },\n    reduce: getRepresentative,\n    postMap: unwrapRepresentative,\n  }\n}\n\nfunction getGroupRoute(\n  aggregatedRow: Record<string, unknown>,\n  fields: InternalGroupFields,\n): RouteMetadata | undefined {\n  return aggregatedRow[fields.route] as RouteMetadata | undefined\n}\n\nfunction getCorrelationRouteIdentity(\n  aggregatedRow: Record<string, unknown>,\n  fields: InternalGroupFields,\n): unknown {\n  return getGroupRoute(aggregatedRow, fields)?.parentContext == null\n    ? aggregatedRow[fields.correlationIdentity]\n    : [\n        aggregatedRow[fields.correlationIdentity],\n        aggregatedRow[fields.parentContextIdentity],\n      ]\n}\n\nfunction getGroupEvaluationRow(\n  row: Record<string, unknown>,\n  fields: InternalGroupFields,\n  selected = row.$selected as Record<string, unknown>,\n): NamespacedRow {\n  return {\n    ...getParentContextValue(getGroupRoute(row, fields)?.parentContext),\n    $selected: selected,\n  }\n}\n\n/**\n * Processes the GROUP BY clause with optional HAVING and SELECT\n * Works with the new $selected structure from early SELECT processing\n */\nexport function processGroupBy(\n  pipeline: NamespacedAndKeyedStream,\n  groupByClause: GroupBy,\n  valueIdentity: ValueIdentity,\n  /** Whether a ref reads a field of the query's own rows. */\n  isSourceRef: (ref: PropRef) => boolean,\n  havingClauses?: Array<Having>,\n  selectClause?: Select,\n  fnHavingClauses?: Array<(row: any) => any>,\n  mainSource?: string,\n  sanitizeCallbackRows = false,\n): NamespacedAndKeyedStream {\n  const fields = createInternalGroupFields(groupByClause.length, selectClause)\n  const aggregates: Record<string, any> = {}\n\n  if (mainSource) {\n    addCorrelationRouteAggregate(aggregates, mainSource, fields, valueIdentity)\n  }\n\n  const singleGroup = groupByClause.length === 0\n  // Outside its aggregates, a select value has a value for the group only\n  // when it is constant within it: a literal, a group key, or a parent field,\n  // which the route fixes. A field of the query's own sources has none, and\n  // neither does a spread: a route's parent context holds only the parent\n  // fields the query names.\n  if (selectClause) {\n    for (const [alias, expr] of Object.entries(selectClause)) {\n      if (lacksGroupValue(alias, expr, isSourceRef, groupByClause))\n        throw new NonAggregateExpressionNotInGroupByError(\n          alias.startsWith(SPREAD_SENTINEL) ? `...${spreadPath(alias)}` : alias,\n        )\n    }\n  }\n\n  // Pre-compile groupBy expressions\n  const compiledGroupByExpressions = groupByClause.map((e) =>\n    compileExpression(e),\n  )\n\n  // Include the complete route so distinct parent inputs stay apart.\n  const keyExtractor = ([, row]: [\n    string,\n    NamespacedRow & { $selected?: any },\n  ]) => {\n    // Use the original namespaced row for GROUP BY expressions, not $selected\n    const namespacedRow = singleGroup ? row : { ...row }\n    if (!singleGroup) delete namespacedRow.$selected\n\n    const key: Record<string, unknown> = singleGroup\n      ? { [fields.singleGroup]: true }\n      : {}\n\n    // D2 must key groups by the same relation as the query evaluator. The raw\n    // representative is retained separately as an aggregate for projection.\n    for (let i = 0; i < groupByClause.length; i++) {\n      const compiledExpr = compiledGroupByExpressions[i]!\n      const value = compiledExpr(namespacedRow)\n      key[fields.groupKeys[i]!] = valueIdentity.equality(value)\n    }\n\n    if (mainSource) {\n      addCorrelationRouteIdentityToGroupKey(\n        key,\n        row,\n        mainSource,\n        fields,\n        valueIdentity,\n      )\n    }\n\n    return key\n  }\n\n  // Create aggregate functions for any aggregated columns in the SELECT clause\n  const wrappedAggExprs: Record<string, (data: any) => any> = {}\n  const aggCounter = { value: 0 }\n\n  for (let i = 0; i < compiledGroupByExpressions.length; i++) {\n    const compiledExpr = compiledGroupByExpressions[i]!\n    aggregates[fields.groupValues[i]!] = {\n      preMap: ([rowKey, row]: [string, NamespacedRow]) => {\n        const value = compiledExpr(row)\n        return createRepresentative(\n          value,\n          exactValueKey(value, rowKey, valueIdentity),\n        )\n      },\n      reduce: getRepresentative,\n      postMap: unwrapRepresentative,\n    }\n  }\n\n  // D2 consolidates contributions that hash equal, and the hash treats -0 as 0\n  // and equal Dates as one value. Today it keeps the instance it was last given;\n  // db-ivm's groupBy tests assert that as current behavior, not as a promise. A min\n  // or max returns one of its inputs, so each contribution carries the exact key\n  // of the value it compares, as a group value does. A primitive's key is its\n  // exact value, so equal primitives still consolidate. An object's key holds its\n  // row key, so a retraction cancels its insert even when the argument builds a\n  // new instance each time, and a merged contribution never keeps a deleted row's\n  // instance. A sum, avg, or count only adds its coerced numbers, so merging\n  // equal inputs cannot change its result.\n  const exactInputs: Array<(entry: [string, NamespacedRow]) => unknown> = []\n  const addAggregate = (alias: string, aggExpr: Aggregate) => {\n    aggregates[alias] = getAggregateFunction(aggExpr)\n    const name = aggExpr.name.toLowerCase()\n    if (name === `min` || name === `max`) {\n      exactInputs.push(minMaxInput(compileExpression(aggExpr.args[0]!)))\n    }\n  }\n\n  if (selectClause) {\n    // Scan the SELECT clause for aggregate functions\n    for (const [alias, expr] of Object.entries(selectClause)) {\n      if (expr.type === `agg`) {\n        addAggregate(alias, expr)\n      } else {\n        // Every other value reads the group's key values, the route's parent\n        // context, and the aggregates it wraps.\n        const { transformed, extracted } = extractAndReplaceAggregates(\n          expr as SelectValueExpression,\n          aggCounter,\n          fields.aggregatePrefix,\n        )\n        for (const [syntheticAlias, aggExpr] of Object.entries(extracted)) {\n          addAggregate(syntheticAlias, aggExpr)\n        }\n        wrappedAggExprs[alias] = compileGroupedSelectValue(\n          replaceGroupByRefsInSelectValue(\n            transformed,\n            groupByClause,\n            fields.groupKeyRefs,\n          ),\n        )\n      }\n    }\n  }\n\n  if (exactInputs.length > 0) {\n    aggregates[fields.exactInputs] = {\n      preMap: (entry: [string, NamespacedRow]) =>\n        exactInputs.map((input) =>\n          exactValueKey(input(entry), entry[0], valueIdentity),\n        ),\n      reduce: () => undefined,\n    }\n  }\n\n  // Apply the groupBy operator\n  pipeline = pipeline.pipe(groupBy(keyExtractor, aggregates))\n\n  // Update $selected to handle GROUP BY results\n  pipeline = pipeline.pipe(\n    map(([, aggregatedRow]) => {\n      const finalResults: Record<string, any> = {}\n\n      if (selectClause) {\n        // Every field takes its place in select order. Plain aggregates are\n        // filled first; every other value reads them, the group keys, and\n        // the route's parent context.\n        for (const [alias, expr] of Object.entries(selectClause)) {\n          finalResults[alias] =\n            expr.type === `agg` ? aggregatedRow[alias] : undefined\n        }\n        evaluateWrappedAggregates(\n          finalResults,\n          aggregatedRow as Record<string, any>,\n          wrappedAggExprs,\n          fields,\n        )\n      } else {\n        // No SELECT clause - just use the group keys\n        for (let i = 0; i < groupByClause.length; i++) {\n          finalResults[`__key_${i}`] = aggregatedRow[fields.groupValues[i]!]\n        }\n      }\n\n      // Generate a simple key for the live collection using group values.\n      // In includes mode, add the complete route so correlated groups do not\n      // collide.\n      const route = mainSource\n        ? getGroupRoute(aggregatedRow, fields)\n        : undefined\n      const correlationKey = route?.correlationKey\n      const correlationRoute = mainSource\n        ? getCorrelationRouteIdentity(aggregatedRow, fields)\n        : undefined\n      const keyParts: Array<unknown> = []\n      const publicKeyParts: Array<unknown> = []\n      for (let i = 0; i < groupByClause.length; i++) {\n        keyParts.push(aggregatedRow[fields.groupKeys[i]!])\n        publicKeyParts.push(aggregatedRow[fields.groupValues[i]!])\n      }\n      if (correlationRoute !== undefined) {\n        keyParts.push(correlationRoute)\n      }\n      const finalKey = singleGroup\n        ? correlationRoute !== undefined\n          ? `single_group_${serializeValue(correlationRoute)}`\n          : `single_group`\n        : keyParts.length === 1\n          ? keyParts[0]\n          : serializeValue(keyParts)\n      const publicKey = singleGroup\n        ? `single_group`\n        : createPublicGroupKey(publicKeyParts)\n\n      // When in includes mode, restore route metadata for output routing.\n      const resultRow: Record<string, any> = {\n        ...(aggregatedRow as Record<string, any>),\n        $selected: finalResults,\n      }\n      resultRow.$key = publicKey\n      if (mainSource && correlationKey !== undefined) {\n        attachPublicGroupKey(resultRow, publicKey)\n        attachRouteMetadata(\n          resultRow,\n          correlationKey,\n          route?.parentContext ?? null,\n        )\n      }\n      return [mainSource ? finalKey : publicKey, resultRow] as [\n        unknown,\n        Record<string, any>,\n      ]\n    }),\n  )\n\n  // Apply HAVING clauses if present\n  if (havingClauses && havingClauses.length > 0) {\n    for (const havingClause of havingClauses) {\n      const havingExpression = getHavingExpression(havingClause)\n      // HAVING follows the select rule, and reads group keys the same way.\n      if (lacksGroupValue(``, havingExpression, isSourceRef, groupByClause))\n        throw new NonAggregateExpressionNotInGroupByError(`HAVING`)\n      const transformedHavingClause = replaceGroupByRefsInExpression(\n        replaceAggregatesByRefs(havingExpression, selectClause || {}),\n        groupByClause,\n        fields.groupKeyRefs,\n      )\n      const compiledHaving = compileExpression(transformedHavingClause)\n\n      pipeline = pipeline.pipe(\n        filter(([, row]) => {\n          let selected = row.$selected as Record<string, unknown>\n          if (fields.groupKeyRefs.length > 0) {\n            const withKeys: Record<string, unknown> = { ...selected }\n            fields.groupKeyRefs.forEach((ref, i) => {\n              withKeys[ref] = row[fields.groupValues[i]!]\n            })\n            selected = withKeys\n          }\n          const namespacedRow = getGroupEvaluationRow(row, fields, selected)\n          const result = compiledHaving(namespacedRow)\n          // Preserve each path's coercion for unchecked nonboolean IR values.\n          return singleGroup ? toBooleanPredicate(result) : result\n        }),\n      )\n    }\n  }\n\n  // Apply functional HAVING clauses if present\n  if (fnHavingClauses && fnHavingClauses.length > 0) {\n    for (const fnHaving of fnHavingClauses) {\n      pipeline = pipeline.pipe(\n        filter(([, row]) => {\n          const namespacedRow = getGroupEvaluationRow(row, fields)\n          const callbackRow = sanitizeCallbackRows\n            ? stripInternalCallbackMetadata(namespacedRow)\n            : namespacedRow\n          return toBooleanPredicate(fnHaving(callbackRow))\n        }),\n      )\n    }\n  }\n\n  return pipeline\n}\n\nconst SPREAD_SENTINEL = `__SPREAD_SENTINEL__`\n\n/** The path a spread sentinel key names, as `__SPREAD_SENTINEL__<path>__<id>`. */\nfunction spreadPath(key: string): string {\n  const rest = key.slice(SPREAD_SENTINEL.length)\n  const idIndex = rest.lastIndexOf(`__`)\n  return idIndex >= 0 ? rest.slice(0, idIndex) : rest\n}\n\n/**\n * Whether a select value has no single value for an aggregate's group: it\n * spreads a row, or reads a field of one of `sources` outside an aggregate.\n * It walks only select and expression nodes.\n */\nfunction lacksGroupValue(\n  key: string,\n  value: unknown,\n  isSourceRef: (ref: PropRef) => boolean,\n  groupKeys: GroupBy,\n): boolean {\n  if (key.startsWith(SPREAD_SENTINEL)) return true\n  if (groupKeys.some((groupKey) => expressionsEqual(value, groupKey)))\n    return false\n  if (isConditionalSelect(value))\n    return (\n      value.branches.some(\n        (branch) =>\n          lacksGroupValue(``, branch.condition, isSourceRef, groupKeys) ||\n          lacksGroupValue(``, branch.value, isSourceRef, groupKeys),\n      ) || lacksGroupValue(``, value.defaultValue, isSourceRef, groupKeys)\n    )\n  if (isExpressionLike(value)) {\n    const node = value as BasicExpression\n    if (node.type === `ref`) return isSourceRef(node)\n    if (node.type === `func`)\n      return node.args.some((arg) =>\n        lacksGroupValue(``, arg, isSourceRef, groupKeys),\n      )\n    return false\n  }\n  if (!isNestedSelectObject(value)) return false\n  return Object.entries(value).some(([childKey, child]) =>\n    lacksGroupValue(childKey, child, isSourceRef, groupKeys),\n  )\n}\n\n/**\n * Helper function to check if two expressions are equal\n */\nfunction expressionsEqual(expr1: any, expr2: any): boolean {\n  if (!expr1 || !expr2) return false\n  if (expr1.type !== expr2.type) return false\n\n  switch (expr1.type) {\n    case `ref`:\n      // Identical paths in different lexical scopes name different values.\n      if (expr1.bindingId !== expr2.bindingId) return false\n      if (!expr1.path || !expr2.path) return false\n      if (expr1.path.length !== expr2.path.length) return false\n      return expr1.path.every(\n        (segment: string, i: number) => segment === expr2.path[i],\n      )\n    case `val`:\n      // Equal literals are separate objects; -0 and 0 can give different\n      // results.\n      return typeof expr1.value === `number`\n        ? Object.is(expr1.value, expr2.value)\n        : deepEquals(expr1.value, expr2.value)\n    case `func`:\n      return (\n        expr1.name === expr2.name &&\n        expr1.args?.length === expr2.args?.length &&\n        (expr1.args || []).every((arg: any, i: number) =>\n          expressionsEqual(arg, expr2.args[i]),\n        )\n      )\n    case `agg`:\n      return (\n        expr1.name === expr2.name &&\n        expr1.args?.length === expr2.args?.length &&\n        (expr1.args || []).every((arg: any, i: number) =>\n          expressionsEqual(arg, expr2.args[i]),\n        )\n      )\n    default:\n      return false\n  }\n}\n\n/** The value a min or max compares: strings, numbers, Dates, and bigints keep\n * their type, and anything else becomes a number. */\nfunction minMaxInput(\n  compiledExpr: (row: NamespacedRow) => unknown,\n): (entry: [string, NamespacedRow]) => string | number | bigint | Date {\n  return ([, namespacedRow]) => {\n    const value = compiledExpr(namespacedRow)\n    if (\n      typeof value === `number` ||\n      typeof value === `string` ||\n      typeof value === `bigint` ||\n      value instanceof Date\n    ) {\n      return value\n    }\n    return value != null ? Number(value) : 0\n  }\n}\n\n/**\n * Helper function to get an aggregate function based on the Agg expression\n */\nfunction getAggregateFunction(aggExpr: Aggregate) {\n  // Pre-compile the value extractor expression\n  const compiledExpr = compileExpression(aggExpr.args[0]!)\n\n  // Create a value extractor function for the expression to aggregate\n  const valueExtractor = ([, namespacedRow]: [string, NamespacedRow]) => {\n    const value = compiledExpr(namespacedRow)\n    // Ensure we return a number for numeric aggregate functions\n    if (typeof value === `number`) {\n      return value\n    }\n    return value != null ? Number(value) : 0\n  }\n\n  const valueExtractorForMinMax = minMaxInput(compiledExpr)\n\n  // Create a raw value extractor function for the expression to aggregate\n  const rawValueExtractor = ([, namespacedRow]: [string, NamespacedRow]) => {\n    return compiledExpr(namespacedRow)\n  }\n\n  // Read the operators here: a top-level destructure counts as a side\n  // effect and would keep them in bundles that never aggregate.\n  const { sum, count, avg, min, max } = groupByOperators\n\n  // Return the appropriate aggregate function\n  switch (aggExpr.name.toLowerCase()) {\n    case `sum`:\n      return sum(valueExtractor)\n    case `count`:\n      return count(rawValueExtractor)\n    case `avg`:\n      return avg(valueExtractor)\n    case `min`:\n      return min(valueExtractorForMinMax)\n    case `max`:\n      return max(valueExtractorForMinMax)\n    default:\n      throw new UnsupportedAggregateFunctionError(aggExpr.name)\n  }\n}\n\n/**\n * Transforms expressions to replace aggregate functions with references to computed values.\n *\n * For aggregate expressions, finds matching aggregates in the SELECT clause and replaces them\n * with PropRef([resultAlias, alias]) to reference the computed aggregate value.\n *\n * Ref expressions (table columns and $selected fields) and value expressions are passed through unchanged.\n * Function expressions are recursively transformed.\n *\n * @param havingExpr - The expression to transform (can be aggregate, ref, func, or val)\n * @param selectClause - The SELECT clause containing aliases and aggregate definitions\n * @param resultAlias - The namespace alias for SELECT results (default: '$selected')\n * @returns A transformed BasicExpression that references computed values instead of raw expressions\n */\nexport function replaceAggregatesByRefs(\n  havingExpr: BasicExpression | Aggregate,\n  selectClause: Select,\n  resultAlias: string = `$selected`,\n): BasicExpression {\n  switch (havingExpr.type) {\n    case `agg`: {\n      const aggExpr = havingExpr\n      // Find matching aggregate in SELECT clause\n      for (const [alias, selectExpr] of Object.entries(selectClause)) {\n        if (selectExpr.type === `agg` && aggregatesEqual(aggExpr, selectExpr)) {\n          // Replace with a reference to the computed aggregate\n          return new PropRef([resultAlias, alias], resultAlias)\n        }\n      }\n      // If no matching aggregate found in SELECT, throw error\n      throw new AggregateFunctionNotInSelectError(aggExpr.name)\n    }\n\n    case `func`: {\n      const funcExpr = havingExpr\n      // Transform function arguments recursively\n      const transformedArgs = funcExpr.args.map(\n        (arg: BasicExpression | Aggregate) =>\n          replaceAggregatesByRefs(arg, selectClause),\n      )\n      return new Func(funcExpr.name, transformedArgs)\n    }\n\n    case `ref`:\n      // Ref expressions are passed through unchanged - they reference either:\n      // - $selected fields (which are already in the correct namespace)\n      // - Table column references (which remain valid)\n      return havingExpr as BasicExpression\n\n    case `val`:\n      // Return as-is\n      return havingExpr as BasicExpression\n\n    default:\n      throw new UnknownHavingExpressionTypeError((havingExpr as any).type)\n  }\n}\n\n/**\n * Evaluates wrapped-aggregate expressions against the aggregated row.\n * Copies synthetic __agg_N values into finalResults so the compiled wrapper\n * expressions can reference them, evaluates each wrapper, then removes the\n * synthetic keys so they don't leak onto user-visible result rows.\n */\nfunction evaluateWrappedAggregates(\n  finalResults: Record<string, any>,\n  aggregatedRow: Record<string, any>,\n  wrappedAggExprs: Record<string, (data: any) => any>,\n  fields: InternalGroupFields,\n): void {\n  for (const key of Object.keys(aggregatedRow)) {\n    if (key.startsWith(fields.aggregatePrefix)) {\n      finalResults[key] = aggregatedRow[key]\n    }\n  }\n  for (let i = 0; i < fields.groupKeyRefs.length; i++) {\n    finalResults[fields.groupKeyRefs[i]!] =\n      aggregatedRow[fields.groupValues[i]!]\n  }\n  // Every evaluator reads the same row; its `$selected` is `finalResults`.\n  const evaluationRow = getGroupEvaluationRow(\n    aggregatedRow,\n    fields,\n    finalResults,\n  )\n  for (const [alias, evaluator] of Object.entries(wrappedAggExprs)) {\n    finalResults[alias] = evaluator(evaluationRow)\n  }\n  for (const key of Object.keys(finalResults)) {\n    if (\n      key.startsWith(fields.aggregatePrefix) ||\n      fields.groupKeyRefs.includes(key)\n    ) {\n      delete finalResults[key]\n    }\n  }\n}\n\n/**\n * Walks an expression tree containing nested aggregates.\n * Each Aggregate node is extracted, assigned a synthetic alias (__agg_N),\n * and replaced with PropRef([\"$selected\", \"__agg_N\"]) so the wrapper\n * expression can be compiled as a pure BasicExpression after groupBy\n * populates the synthetic values.\n */\nfunction extractAndReplaceAggregates(\n  expr: SelectValueExpression,\n  counter: { value: number },\n  aggregatePrefix: string,\n): {\n  transformed: SelectValueExpression\n  extracted: Record<string, Aggregate>\n} {\n  if (expr.type === `agg`) {\n    const alias = `${aggregatePrefix}${counter.value++}`\n    return {\n      transformed: new PropRef([`$selected`, alias], `$selected`),\n      extracted: { [alias]: expr },\n    }\n  }\n\n  if (expr.type === `func`) {\n    const allExtracted: Record<string, Aggregate> = {}\n    const newArgs = expr.args.map((arg: BasicExpression | Aggregate) => {\n      const result = extractAndReplaceAggregates(arg, counter, aggregatePrefix)\n      Object.assign(allExtracted, result.extracted)\n      return result.transformed as BasicExpression\n    })\n    return {\n      transformed: new Func(expr.name, newArgs),\n      extracted: allExtracted,\n    }\n  }\n\n  if (isConditionalSelect(expr)) {\n    const allExtracted: Record<string, Aggregate> = {}\n    const branches = expr.branches.map((branch) => {\n      const condition = extractAndReplaceAggregates(\n        branch.condition,\n        counter,\n        aggregatePrefix,\n      )\n      const value = extractAndReplaceAggregates(\n        branch.value,\n        counter,\n        aggregatePrefix,\n      )\n      Object.assign(allExtracted, condition.extracted, value.extracted)\n      return {\n        condition: condition.transformed as BasicExpression,\n        value: value.transformed,\n      }\n    })\n    const defaultValue =\n      expr.defaultValue === undefined\n        ? undefined\n        : extractAndReplaceAggregates(\n            expr.defaultValue,\n            counter,\n            aggregatePrefix,\n          )\n\n    if (defaultValue) {\n      Object.assign(allExtracted, defaultValue.extracted)\n    }\n\n    return {\n      transformed: new ConditionalSelect(branches, defaultValue?.transformed),\n      extracted: allExtracted,\n    }\n  }\n\n  if (isNestedSelectObject(expr)) {\n    const allExtracted: Record<string, Aggregate> = {}\n    const transformed: Select = {}\n\n    for (const [key, value] of Object.entries(expr)) {\n      const result = extractAndReplaceAggregates(\n        value as SelectValueExpression,\n        counter,\n        aggregatePrefix,\n      )\n      Object.assign(allExtracted, result.extracted)\n      transformed[key] = result.transformed\n    }\n\n    return { transformed, extracted: allExtracted }\n  }\n\n  // ref / val – pass through unchanged\n  return { transformed: expr, extracted: {} }\n}\n\nfunction replaceGroupByRefsInSelectValue(\n  value: SelectValueExpression,\n  groupByClause: GroupBy,\n  groupKeyRefs: Array<string>,\n): SelectValueExpression {\n  if (isConditionalSelect(value)) {\n    return new ConditionalSelect(\n      value.branches.map((branch) => ({\n        condition: replaceGroupByRefsInExpression(\n          branch.condition,\n          groupByClause,\n          groupKeyRefs,\n        ),\n        value: replaceGroupByRefsInSelectValue(\n          branch.value,\n          groupByClause,\n          groupKeyRefs,\n        ),\n      })),\n      value.defaultValue === undefined\n        ? undefined\n        : replaceGroupByRefsInSelectValue(\n            value.defaultValue,\n            groupByClause,\n            groupKeyRefs,\n          ),\n    )\n  }\n\n  if (isNestedSelectObject(value)) {\n    const transformed: Select = {}\n    for (const [key, entry] of Object.entries(value)) {\n      transformed[key] = replaceGroupByRefsInSelectValue(\n        entry as SelectValueExpression,\n        groupByClause,\n        groupKeyRefs,\n      )\n    }\n    return transformed\n  }\n\n  if (!isExpressionLike(value)) {\n    return value\n  }\n\n  if (value.type === `includesSubquery` || value.type === `agg`) {\n    return value\n  }\n\n  return replaceGroupByRefsInExpression(value, groupByClause, groupKeyRefs)\n}\n\nfunction replaceGroupByRefsInExpression(\n  expr: BasicExpression,\n  groupByClause: GroupBy,\n  groupKeyRefs: Array<string>,\n): BasicExpression {\n  // A group expression, a ref or a computed one, reads the group's value.\n  const groupIndex = groupByClause.findIndex((groupExpr) =>\n    expressionsEqual(expr, groupExpr),\n  )\n  if (groupIndex !== -1)\n    return new PropRef([`$selected`, groupKeyRefs[groupIndex]!], `$selected`)\n\n  if (expr.type === `func`) {\n    return new Func(\n      expr.name,\n      expr.args.map((arg) =>\n        replaceGroupByRefsInExpression(arg, groupByClause, groupKeyRefs),\n      ),\n    )\n  }\n\n  return expr\n}\n\nfunction compileGroupedSelectValue(\n  value: SelectValueExpression,\n): (row: NamespacedRow) => any {\n  if (isConditionalSelect(value)) {\n    return compileGroupedConditionalSelect(value)\n  }\n\n  if (isNestedSelectObject(value)) {\n    return compileGroupedSelectObject(value)\n  }\n\n  if (!isExpressionLike(value)) {\n    return () => value\n  }\n\n  return compileExpression(value as BasicExpression)\n}\n\n/** Spreads and nested includes were rejected before compilation. */\nfunction compileGroupedSelectObject(\n  obj: Select,\n): (row: NamespacedRow) => Record<string, any> {\n  const entries = Object.entries(obj).map(\n    ([key, value]) =>\n      [key, compileGroupedSelectValue(value as SelectValueExpression)] as const,\n  )\n  return (row) => {\n    const result: Record<string, any> = {}\n    for (const [key, value] of entries) result[key] = value(row)\n    return result\n  }\n}\n\nfunction compileGroupedConditionalSelect(\n  conditional: ConditionalSelect,\n): (row: NamespacedRow) => any {\n  const branches = conditional.branches.map((branch) => ({\n    condition: compileExpression(branch.condition),\n    value: compileGroupedSelectValue(branch.value),\n  }))\n  const defaultValue =\n    conditional.defaultValue === undefined\n      ? undefined\n      : compileGroupedSelectValue(conditional.defaultValue)\n\n  return (row) => {\n    for (const branch of branches) {\n      if (isCaseWhenConditionTrue(branch.condition(row))) {\n        return branch.value(row)\n      }\n    }\n\n    return defaultValue !== undefined ? defaultValue(row) : null\n  }\n}\n\nfunction isNestedSelectObject(value: unknown): value is Select {\n  return (\n    value != null &&\n    typeof value === `object` &&\n    !Array.isArray(value) &&\n    !isRefProxy(value) &&\n    !isExpressionLike(value)\n  )\n}\n\nfunction isConditionalSelect(value: unknown): value is ConditionalSelect {\n  return (\n    value instanceof ConditionalSelect ||\n    (value != null &&\n      typeof value === `object` &&\n      (value as { type?: string }).type === `conditionalSelect`)\n  )\n}\n\n/**\n * Checks if two aggregate expressions are equal\n */\nfunction aggregatesEqual(agg1: Aggregate, agg2: Aggregate): boolean {\n  return (\n    agg1.name === agg2.name &&\n    agg1.args.length === agg2.args.length &&\n    agg1.args.every((arg, i) => expressionsEqual(arg, agg2.args[i]))\n  )\n}\n"],"mappings":";;;;;;;;;AAmDA,IAAM,qBAAqB,uBAAO,0BAA0B;AAI5D,SAAS,0BAA0B,YAAoB,cAAuB;CAC5E,MAAM,UAAU,OAAO,KAAK,gBAAgB,CAAC,CAAC;CAC9C,IAAI,SAAS;CACb,OAAO,QAAQ,MAAM,UA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