@ahoo-wang/wow-client 10.0.0-alpha.7 → 10.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/README.md +8 -5
  2. package/README.zh-CN.md +4 -3
  3. package/dist/commands.cjs +1 -1
  4. package/dist/commands.cjs.map +1 -1
  5. package/dist/commands.d.cts +9 -13
  6. package/dist/commands.d.ts +9 -13
  7. package/dist/commands.es.js +60 -54
  8. package/dist/commands.es.js.map +1 -1
  9. package/dist/dsl/aggregation/admit.cjs +1 -1
  10. package/dist/dsl/aggregation/admit.cjs.map +1 -1
  11. package/dist/dsl/aggregation/admit.es.js +73 -69
  12. package/dist/dsl/aggregation/admit.es.js.map +1 -1
  13. package/dist/dsl/aggregation/aliases.cjs +2 -0
  14. package/dist/dsl/aggregation/aliases.cjs.map +1 -0
  15. package/dist/dsl/aggregation/aliases.d.cts +2 -0
  16. package/dist/dsl/aggregation/aliases.d.ts +2 -0
  17. package/dist/dsl/aggregation/aliases.es.js +13 -0
  18. package/dist/dsl/aggregation/aliases.es.js.map +1 -0
  19. package/dist/dsl/aggregation/builders.cjs +1 -1
  20. package/dist/dsl/aggregation/builders.cjs.map +1 -1
  21. package/dist/dsl/aggregation/builders.d.cts +17 -243
  22. package/dist/dsl/aggregation/builders.d.ts +17 -243
  23. package/dist/dsl/aggregation/builders.es.js +36 -171
  24. package/dist/dsl/aggregation/builders.es.js.map +1 -1
  25. package/dist/dsl/aggregation/derived.cjs +1 -1
  26. package/dist/dsl/aggregation/derived.cjs.map +1 -1
  27. package/dist/dsl/aggregation/derived.d.cts +123 -1
  28. package/dist/dsl/aggregation/derived.d.ts +123 -1
  29. package/dist/dsl/aggregation/derived.es.js +43 -28
  30. package/dist/dsl/aggregation/derived.es.js.map +1 -1
  31. package/dist/dsl/aggregation/groups.cjs +2 -0
  32. package/dist/dsl/aggregation/groups.cjs.map +1 -0
  33. package/dist/dsl/aggregation/groups.d.cts +325 -0
  34. package/dist/dsl/aggregation/groups.d.ts +325 -0
  35. package/dist/dsl/aggregation/groups.es.js +80 -0
  36. package/dist/dsl/aggregation/groups.es.js.map +1 -0
  37. package/dist/dsl/aggregation/having.cjs +1 -1
  38. package/dist/dsl/aggregation/having.cjs.map +1 -1
  39. package/dist/dsl/aggregation/having.d.cts +63 -1
  40. package/dist/dsl/aggregation/having.d.ts +63 -1
  41. package/dist/dsl/aggregation/having.es.js +33 -30
  42. package/dist/dsl/aggregation/having.es.js.map +1 -1
  43. package/dist/dsl/aggregation/index.d.cts +4 -2
  44. package/dist/dsl/aggregation/index.d.ts +4 -2
  45. package/dist/dsl/aggregation/metrics.cjs +2 -0
  46. package/dist/dsl/aggregation/metrics.cjs.map +1 -0
  47. package/dist/dsl/aggregation/metrics.d.cts +279 -0
  48. package/dist/dsl/aggregation/metrics.d.ts +279 -0
  49. package/dist/dsl/aggregation/metrics.es.js +75 -0
  50. package/dist/dsl/aggregation/metrics.es.js.map +1 -0
  51. package/dist/dsl/aggregation/types.cjs +1 -1
  52. package/dist/dsl/aggregation/types.cjs.map +1 -1
  53. package/dist/dsl/aggregation/types.d.cts +4 -524
  54. package/dist/dsl/aggregation/types.d.ts +4 -524
  55. package/dist/dsl/aggregation/types.es.js +5 -25
  56. package/dist/dsl/aggregation/types.es.js.map +1 -1
  57. package/dist/dsl/cursorQuery.cjs +1 -1
  58. package/dist/dsl/cursorQuery.cjs.map +1 -1
  59. package/dist/dsl/cursorQuery.d.cts +18 -7
  60. package/dist/dsl/cursorQuery.d.ts +18 -7
  61. package/dist/dsl/cursorQuery.es.js +13 -12
  62. package/dist/dsl/cursorQuery.es.js.map +1 -1
  63. package/dist/dsl/descriptor.cjs +1 -1
  64. package/dist/dsl/descriptor.cjs.map +1 -1
  65. package/dist/dsl/descriptor.d.cts +24 -379
  66. package/dist/dsl/descriptor.d.ts +24 -379
  67. package/dist/dsl/descriptor.es.js +6 -32
  68. package/dist/dsl/descriptor.es.js.map +1 -1
  69. package/dist/dsl/fieldDescriptor.cjs +2 -0
  70. package/dist/dsl/fieldDescriptor.cjs.map +1 -0
  71. package/dist/dsl/fieldDescriptor.d.cts +246 -0
  72. package/dist/dsl/fieldDescriptor.d.ts +246 -0
  73. package/dist/dsl/fieldDescriptor.es.js +24 -0
  74. package/dist/dsl/fieldDescriptor.es.js.map +1 -0
  75. package/dist/dsl/filter/builders.cjs +1 -1
  76. package/dist/dsl/filter/builders.cjs.map +1 -1
  77. package/dist/dsl/filter/builders.d.cts +7 -949
  78. package/dist/dsl/filter/builders.d.ts +7 -949
  79. package/dist/dsl/filter/builders.es.js +14 -285
  80. package/dist/dsl/filter/builders.es.js.map +1 -1
  81. package/dist/dsl/filter/expressionFilter.cjs +2 -0
  82. package/dist/dsl/filter/expressionFilter.cjs.map +1 -0
  83. package/dist/dsl/filter/expressionFilter.d.cts +35 -0
  84. package/dist/dsl/filter/expressionFilter.d.ts +35 -0
  85. package/dist/dsl/filter/expressionFilter.es.js +18 -0
  86. package/dist/dsl/filter/expressionFilter.es.js.map +1 -0
  87. package/dist/dsl/filter/fieldFilters.cjs +2 -0
  88. package/dist/dsl/filter/fieldFilters.cjs.map +1 -0
  89. package/dist/dsl/filter/fieldFilters.d.cts +297 -0
  90. package/dist/dsl/filter/fieldFilters.d.ts +297 -0
  91. package/dist/dsl/filter/fieldFilters.es.js +110 -0
  92. package/dist/dsl/filter/fieldFilters.es.js.map +1 -0
  93. package/dist/dsl/filter/index.d.cts +2 -1
  94. package/dist/dsl/filter/index.d.ts +2 -1
  95. package/dist/dsl/filter/logicalFilters.cjs +2 -0
  96. package/dist/dsl/filter/logicalFilters.cjs.map +1 -0
  97. package/dist/dsl/filter/logicalFilters.d.cts +109 -0
  98. package/dist/dsl/filter/logicalFilters.d.ts +109 -0
  99. package/dist/dsl/filter/logicalFilters.es.js +36 -0
  100. package/dist/dsl/filter/logicalFilters.es.js.map +1 -0
  101. package/dist/dsl/filter/metadataFilters.cjs +2 -0
  102. package/dist/dsl/filter/metadataFilters.cjs.map +1 -0
  103. package/dist/dsl/filter/metadataFilters.d.cts +132 -0
  104. package/dist/dsl/filter/metadataFilters.d.ts +132 -0
  105. package/dist/dsl/filter/metadataFilters.es.js +56 -0
  106. package/dist/dsl/filter/metadataFilters.es.js.map +1 -0
  107. package/dist/dsl/filter/operator.cjs +1 -1
  108. package/dist/dsl/filter/operator.cjs.map +1 -1
  109. package/dist/dsl/filter/operator.d.cts +11 -9
  110. package/dist/dsl/filter/operator.d.ts +11 -9
  111. package/dist/dsl/filter/operator.es.js +1 -1
  112. package/dist/dsl/filter/operator.es.js.map +1 -1
  113. package/dist/dsl/filter/searchFilter.cjs +2 -0
  114. package/dist/dsl/filter/searchFilter.cjs.map +1 -0
  115. package/dist/dsl/filter/searchFilter.d.cts +39 -0
  116. package/dist/dsl/filter/searchFilter.d.ts +39 -0
  117. package/dist/dsl/filter/searchFilter.es.js +19 -0
  118. package/dist/dsl/filter/searchFilter.es.js.map +1 -0
  119. package/dist/dsl/filter/timeFilters.cjs +2 -0
  120. package/dist/dsl/filter/timeFilters.cjs.map +1 -0
  121. package/dist/dsl/filter/timeFilters.d.cts +290 -0
  122. package/dist/dsl/filter/timeFilters.d.ts +290 -0
  123. package/dist/dsl/filter/timeFilters.es.js +89 -0
  124. package/dist/dsl/filter/timeFilters.es.js.map +1 -0
  125. package/dist/dsl/filter/types.d.cts +4 -14
  126. package/dist/dsl/filter/types.d.ts +4 -14
  127. package/dist/dsl/filter/validate.cjs +1 -1
  128. package/dist/dsl/filter/validate.cjs.map +1 -1
  129. package/dist/dsl/filter/validate.d.cts +2 -4
  130. package/dist/dsl/filter/validate.d.ts +2 -4
  131. package/dist/dsl/filter/validate.es.js +25 -31
  132. package/dist/dsl/filter/validate.es.js.map +1 -1
  133. package/dist/dsl/queryErrorCodes.cjs +1 -1
  134. package/dist/dsl/queryErrorCodes.cjs.map +1 -1
  135. package/dist/dsl/queryErrorCodes.d.cts +0 -2
  136. package/dist/dsl/queryErrorCodes.d.ts +0 -2
  137. package/dist/dsl/queryErrorCodes.es.js +0 -1
  138. package/dist/dsl/queryErrorCodes.es.js.map +1 -1
  139. package/dist/dsl/queryFilter.cjs +2 -0
  140. package/dist/dsl/queryFilter.cjs.map +1 -0
  141. package/dist/dsl/queryFilter.d.cts +3 -0
  142. package/dist/dsl/queryFilter.d.ts +3 -0
  143. package/dist/dsl/queryFilter.es.js +9 -0
  144. package/dist/dsl/queryFilter.es.js.map +1 -0
  145. package/dist/dsl/queryable.cjs +1 -1
  146. package/dist/dsl/queryable.cjs.map +1 -1
  147. package/dist/dsl/queryable.es.js +12 -16
  148. package/dist/dsl/queryable.es.js.map +1 -1
  149. package/dist/dsl/semanticTypes.cjs +2 -0
  150. package/dist/dsl/semanticTypes.cjs.map +1 -0
  151. package/dist/dsl/semanticTypes.d.cts +128 -0
  152. package/dist/dsl/semanticTypes.d.ts +128 -0
  153. package/dist/dsl/semanticTypes.es.js +13 -0
  154. package/dist/dsl/semanticTypes.es.js.map +1 -0
  155. package/dist/dsl.cjs +1 -1
  156. package/dist/dsl.d.cts +2 -0
  157. package/dist/dsl.d.ts +2 -0
  158. package/dist/dsl.es.js +14 -8
  159. package/dist/exactJson.cjs +2 -2
  160. package/dist/exactJson.cjs.map +1 -1
  161. package/dist/exactJson.d.cts +41 -16
  162. package/dist/exactJson.d.ts +41 -16
  163. package/dist/exactJson.es.js +104 -102
  164. package/dist/exactJson.es.js.map +1 -1
  165. package/dist/frameworkErrors.cjs.map +1 -1
  166. package/dist/frameworkErrors.d.cts +5 -5
  167. package/dist/frameworkErrors.d.ts +5 -5
  168. package/dist/frameworkErrors.es.js.map +1 -1
  169. package/dist/http.cjs +1 -1
  170. package/dist/http.cjs.map +1 -1
  171. package/dist/http.d.cts +29 -9
  172. package/dist/http.d.ts +29 -9
  173. package/dist/http.es.js +24 -19
  174. package/dist/http.es.js.map +1 -1
  175. package/dist/index.cjs +1 -1
  176. package/dist/index.d.cts +3 -3
  177. package/dist/index.d.ts +3 -3
  178. package/dist/index.es.js +12 -12
  179. package/dist/manifest.cjs +1 -1
  180. package/dist/manifest.cjs.map +1 -1
  181. package/dist/manifest.d.cts +30 -2
  182. package/dist/manifest.d.ts +30 -2
  183. package/dist/manifest.es.js +34 -6
  184. package/dist/manifest.es.js.map +1 -1
  185. package/dist/manifestTypes.d.cts +21 -4
  186. package/dist/manifestTypes.d.ts +21 -4
  187. package/dist/queries.cjs +1 -1
  188. package/dist/queries.cjs.map +1 -1
  189. package/dist/queries.d.cts +18 -8
  190. package/dist/queries.d.ts +18 -8
  191. package/dist/queries.es.js +46 -35
  192. package/dist/queries.es.js.map +1 -1
  193. package/dist/routes.cjs +1 -1
  194. package/dist/routes.cjs.map +1 -1
  195. package/dist/routes.d.cts +16 -3
  196. package/dist/routes.d.ts +16 -3
  197. package/dist/routes.es.js +24 -25
  198. package/dist/routes.es.js.map +1 -1
  199. package/dist/state.cjs +1 -1
  200. package/dist/state.cjs.map +1 -1
  201. package/dist/state.d.cts +21 -19
  202. package/dist/state.d.ts +21 -19
  203. package/dist/state.es.js +27 -22
  204. package/dist/state.es.js.map +1 -1
  205. package/dist/streams.cjs +1 -1
  206. package/dist/streams.cjs.map +1 -1
  207. package/dist/streams.d.cts +14 -7
  208. package/dist/streams.d.ts +14 -7
  209. package/dist/streams.es.js +65 -50
  210. package/dist/streams.es.js.map +1 -1
  211. package/dist/testing/wire.cjs +1 -1
  212. package/dist/testing/wire.cjs.map +1 -1
  213. package/dist/testing/wire.es.js +1 -1
  214. package/dist/testing/wire.es.js.map +1 -1
  215. package/dist/wait.cjs +1 -1
  216. package/dist/wait.cjs.map +1 -1
  217. package/dist/wait.d.cts +18 -5
  218. package/dist/wait.d.ts +18 -5
  219. package/dist/wait.es.js +36 -34
  220. package/dist/wait.es.js.map +1 -1
  221. package/dist/wire.cjs +1 -1
  222. package/dist/wire.cjs.map +1 -1
  223. package/dist/wire.d.cts +76 -31
  224. package/dist/wire.d.ts +76 -31
  225. package/dist/wire.es.js +1 -3
  226. package/dist/wire.es.js.map +1 -1
  227. package/package.json +5 -5
  228. package/dist/dsl/filter/datePattern.cjs +0 -2
  229. package/dist/dsl/filter/datePattern.cjs.map +0 -1
  230. package/dist/dsl/filter/datePattern.d.cts +0 -8
  231. package/dist/dsl/filter/datePattern.d.ts +0 -8
  232. package/dist/dsl/filter/datePattern.es.js +0 -96
  233. package/dist/dsl/filter/datePattern.es.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"admit.es.js","names":["requireAtMost","items","max","name","noun","validateMetricFilter","filter","FilterOperator","validateExpressions","requireValidExpressionTrees","metrics","metric","AggregationMetricType","groupBy","group","AggregationGroupType","constantName","AggregationGroupScope","NON_NUMERIC","validateDerivedMetrics","declared","derived","counter","validateDerivedExpression","pending","depth","AGGREGATION_LIMITS","expression","DerivedExpressionType","reference","nonNumeric","requireWindowMetric","target","window","alias","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","HavingExpressionType","operand","validateSort","sort","fields","entry","aliases","field","effectiveSort","requireRootGroupsFirst","root","query","order","firstElement","admitAggregationQuery","elements"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { constantName } from '../constantName.js';\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n AGGREGATION_LIMITS,\n AggregationGroupScope,\n AggregationGroupType,\n AggregationMetricType,\n DerivedExpressionType,\n HavingExpressionType,\n type AggregationGroup,\n type AggregationMetric,\n type AggregationQuery,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DerivedWindow,\n type HavingExpression,\n} from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${constantName(group.type)} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n if (group.scope === AggregationGroupScope.ROOT && group.expression) {\n throw new TypeError(\n `${constantName(group.type)} with a ROOT scope requires a field input.`,\n );\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n const derived = new Set<string>();\n const counter = { nodes: 0, windows: 0 };\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n validateDerivedExpression(metric, declared, derived, counter);\n derived.add(metric.alias);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n counter: { nodes: number; windows: number },\n): void {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n counter.nodes++;\n if (counter.nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${constantName(nonNumeric)} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n case DerivedExpressionType.TOTAL:\n case DerivedExpressionType.RUNNING:\n case DerivedExpressionType.PREVIOUS:\n case DerivedExpressionType.RANK:\n counter.windows++;\n if (counter.windows > AGGREGATION_LIMITS.MAX_WINDOWS) {\n throw new TypeError(\n `an aggregation must compute at most ${AGGREGATION_LIMITS.MAX_WINDOWS} windows.`,\n );\n }\n requireWindowMetric(metric.alias, expression, declared, derived);\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\n/**\n * A window reads a non-derived numeric metric declared before the derived\n * one; the rest of its rules (which metrics add up, which groups it names)\n * the server checks against the whole query.\n */\nfunction requireWindowMetric(\n alias: string,\n window: DerivedWindow,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n): void {\n const target = window.metric;\n if (!declared.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a metric declared before it, but was [${target}].`,\n );\n }\n if (declared.get(target) !== undefined || derived.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a non-derived numeric metric, but was [${target}].`,\n );\n }\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${constantName(expression.type)} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * With elements, the groups of a ROOT scope lead the effective sort: a storage\n * reads the root records' keys before the keys of their elements.\n */\nfunction requireRootGroupsFirst(\n query: Pick<AggregationQuery<string, string>, 'groupBy' | 'sort'>,\n): void {\n const root = new Map(\n (query.groupBy ?? []).map(group => [\n group.alias,\n group.scope === AggregationGroupScope.ROOT,\n ]),\n );\n const order = effectiveSort(query).flatMap(entry =>\n root.has(entry.field) ? [root.get(entry.field)] : [],\n );\n const firstElement = order.indexOf(false);\n if (firstElement >= 0 && order.slice(firstElement).includes(true)) {\n throw new TypeError(\n 'groups with a ROOT scope must sort before the element groups.',\n );\n }\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${constantName(group.type)} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n if (elements.length > 0) requireRootGroupsFirst(query);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\n"],"mappings":";;;;;;AAqCA,SAASA,EACP,GACA,GACA,GACA,GACM;CACN,IAAIC,EAAM,SAASC,GACjB,MAAU,UAAU,GAAGC,EAAK,wBAAwBD,EAAI,GAAGE,EAAK,EAAE;AAEtE;AAWA,SAASC,EAAqB,GAAgC;CAC5D,QAAQC,EAAO,IAAf;EACE,KAAKC,EAAe,QAClB,MAAU,UACR,2DACF;EACF,KAAKA,EAAe,eAClB,MAAU,UACR,4DACF;EACF,KAAKA,EAAe;EACpB,KAAKA,EAAe;EACpB,KAAKA,EAAe,KAClB,EAAO,SAAS,QAAQF,CAAoB;CAEhD;AACF;AAMA,SAASG,EACP,GACA,GACM;CAUN,AATAC,EACEC,EAAQ,SAAQ,MACdC,EAAO,SAASC,EAAsB,WACtCD,EAAO,SAASC,EAAsB,kBACtCD,EAAO,SAASC,EAAsB,aAClC,CAACD,EAAO,UAAU,IAClB,CAAC,CACP,CACF,GACAE,EAAQ,SAAQ,MAAS;EACvB,IACEC,EAAM,SAASC,EAAqB,SACpCD,EAAM,SAASC,EAAqB,WAGtC;OAAKD,EAAM,UAAU,KAAA,MAAgBA,EAAM,eAAe,KAAA,IACxD,MAAU,UACR,GAAGE,EAAa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,EAAM,SAASC,EAAqB,kBACnCD,EAAM,SAASC,EAAqB,cACtCD,EAAM,UAAU,MAChBD,EAAQ,WAAW,GAEnB,MAAU,UACR,kBAAkBG,EAAaF,EAAM,IAAI,EAAE,yBAC7C;CAEJ,CAAC;CAED,IAAMiC,IAAU,CACd,GAAGlC,EAAQ,KAAI,MAASC,EAAM,KAAK,GACnC,GAAGJ,EAAQ,KAAI,MAAUC,EAAO,KAAK,CACvC;CACA,IAAI,IAAI,IAAIoC,CAAO,CAAC,CAAC,SAASA,EAAQ,QACpC,MAAU,UAAU,qCAAqC;CAK3D,OAHAJ,EAAaC,GAAM/B,GAASkC,CAAO,GAC/BS,EAAS,SAAS,KAAGN,EAAuBE,CAAK,GAE9C;EACL,GAAGA;EACH,SAAS,CAAC,GAAG1C,CAAO;CACtB;AACF"}
1
+ {"version":3,"file":"admit.es.js","names":["requireAtMost","items","max","name","noun","validateMetricFilter","filter","FilterOperator","validateExpressions","requireValidExpressionTrees","metrics","metric","AggregationMetricType","groupBy","group","AggregationGroupType","constantName","AggregationGroupScope","NON_NUMERIC","validateDerivedMetrics","declared","derived","counter","validateDerivedExpression","pending","depth","AGGREGATION_LIMITS","expression","DerivedExpressionType","reference","nonNumeric","requireWindowMetric","target","window","alias","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","HavingExpressionType","operand","validateSort","sort","fields","entry","aliases","field","effectiveSort","requireRootGroupsFirst","root","query","order","firstElement","admitAggregationQuery","elements"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { constantName } from '../constantName.js';\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n DerivedExpressionType,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DerivedWindow,\n} from './derived.js';\nimport {\n AggregationGroupScope,\n AggregationGroupType,\n type AggregationGroup,\n} from './groups.js';\nimport { HavingExpressionType, type HavingExpression } from './having.js';\nimport { AggregationMetricType, type AggregationMetric } from './metrics.js';\nimport { AGGREGATION_LIMITS, type AggregationQuery } from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${constantName(group.type)} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n if (group.scope === AggregationGroupScope.ROOT && group.expression) {\n throw new TypeError(\n `${constantName(group.type)} with a ROOT scope requires a field input.`,\n );\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n const derived = new Set<string>();\n const counter = { nodes: 0, windows: 0 };\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n validateDerivedExpression(metric, declared, derived, counter);\n derived.add(metric.alias);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n counter: { nodes: number; windows: number },\n): void {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n counter.nodes++;\n if (counter.nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${constantName(nonNumeric)} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n case DerivedExpressionType.TOTAL:\n case DerivedExpressionType.RUNNING:\n case DerivedExpressionType.PREVIOUS:\n case DerivedExpressionType.RANK:\n counter.windows++;\n if (counter.windows > AGGREGATION_LIMITS.MAX_WINDOWS) {\n throw new TypeError(\n `an aggregation must compute at most ${AGGREGATION_LIMITS.MAX_WINDOWS} windows.`,\n );\n }\n requireWindowMetric(metric.alias, expression, declared, derived);\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\n/**\n * A window reads a non-derived numeric metric declared before the derived\n * one; the rest of its rules (which metrics add up, which groups it names)\n * the server checks against the whole query.\n */\nfunction requireWindowMetric(\n alias: string,\n window: DerivedWindow,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n): void {\n const target = window.metric;\n if (!declared.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a metric declared before it, but was [${target}].`,\n );\n }\n if (declared.get(target) !== undefined || derived.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a non-derived numeric metric, but was [${target}].`,\n );\n }\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${constantName(expression.type)} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * With elements, the groups of a ROOT scope lead the effective sort: a storage\n * reads the root records' keys before the keys of their elements.\n */\nfunction requireRootGroupsFirst(\n query: Pick<AggregationQuery<string, string>, 'groupBy' | 'sort'>,\n): void {\n const root = new Map(\n (query.groupBy ?? []).map(group => [\n group.alias,\n group.scope === AggregationGroupScope.ROOT,\n ]),\n );\n const order = effectiveSort(query).flatMap(entry =>\n root.has(entry.field) ? [root.get(entry.field)] : [],\n );\n const firstElement = order.indexOf(false);\n if (firstElement >= 0 && order.slice(firstElement).includes(true)) {\n throw new TypeError(\n 'groups with a ROOT scope must sort before the element groups.',\n );\n }\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${constantName(group.type)} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n if (elements.length > 0) requireRootGroupsFirst(query);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\n"],"mappings":";;;;;;;;;;AAoCA,SAASA,EACP,GACA,GACA,GACA,GACM;CACN,IAAIC,EAAM,SAASC,GACjB,MAAU,UAAU,GAAGC,EAAK,wBAAwBD,EAAI,GAAGE,EAAK,EAAE;AAEtE;AAWA,SAASC,EAAqB,GAAgC;CAC5D,QAAQC,EAAO,IAAf;EACE,KAAKC,EAAe,QAClB,MAAU,UACR,2DACF;EACF,KAAKA,EAAe,eAClB,MAAU,UACR,4DACF;EACF,KAAKA,EAAe;EACpB,KAAKA,EAAe;EACpB,KAAKA,EAAe,KAClB,EAAO,SAAS,QAAQF,CAAoB;CAEhD;AACF;AAMA,SAASG,EACP,GACA,GACM;CAUN,AATAC,EACEC,EAAQ,SAAQ,MACdC,EAAO,SAASC,EAA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ACR,+BAA+BA,EAAmB,UAAU,EAC9D;CAgBJ,AAZAlB,EAAoBE,GAASG,CAAO,GACpCM,EAAuBT,CAAO,GAC9B6B,EAAea,EAAM,QAAQvC,GAASH,CAAO,GAC7CA,EAAQ,SAAQ,MAAU;EACxB,AAAI,YAAYC,KAAUA,EAAO,UAC/BN,EAAqBM,EAAO,MAAM;CACtC,CAAC,GAMDE,EAAQ,SAAQ,MAAS;EACvB,KACGC,EAAM,SAASC,EAAqB,kBACnCD,EAAM,SAASC,EAAqB,cACtCD,EAAM,UAAU,MAChBD,EAAQ,WAAW,GAEnB,MAAU,UACR,kBAAkBG,EAAaF,EAAM,IAAI,EAAE,yBAC7C;CAEJ,CAAC;CAED,IAAMiC,IAAU,CACd,GAAGlC,EAAQ,KAAI,MAASC,EAAM,KAAK,GACnC,GAAGJ,EAAQ,KAAI,MAAUC,EAAO,KAAK,CACvC;CACA,IAAI,IAAI,IAAIoC,CAAO,CAAC,CAAC,SAASA,EAAQ,QACpC,MAAU,UAAU,qCAAqC;CAK3D,OAHAJ,EAAaC,GAAM/B,GAASkC,CAAO,GAC/BS,EAAS,SAAS,KAAGN,EAAuBE,CAAK,GAE9C;EACL,GAAGA;EACH,SAAS,CAAC,GAAG1C,CAAO;CACtB;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../field.cjs");function t(t){return e.queryField(t)}function n(e){if(t(e),e.includes(`.`))throw TypeError(`aggregation alias must contain one segment.`);if(e.startsWith(`__wow`))throw TypeError(`aggregation alias must not use the reserved __wow prefix.`);return e}exports.aggregationAlias=n,exports.aggregationField=t;
2
+ //# sourceMappingURL=aliases.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aliases.cjs","names":["queryField","require_field","aggregationField","field","aggregationAlias","alias"],"sources":["../../../src/dsl/aggregation/aliases.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { queryField } from '../field.js';\n\n// Internal: how the parts of an aggregation name their fields and their\n// columns. index.ts does not re-export this file.\n\nexport function aggregationField<FIELDS extends string>(field: FIELDS): FIELDS {\n return queryField(field);\n}\n\nexport function aggregationAlias(alias: string): string {\n aggregationField(alias);\n if (alias.includes('.')) {\n throw new TypeError('aggregation alias must contain one segment.');\n }\n if (alias.startsWith('__wow')) {\n throw new TypeError(\n 'aggregation alias must not use the reserved __wow prefix.',\n );\n }\n return alias;\n}\n"],"mappings":"A,gCAkBA,SAAgBE,EAAwC,EAAuB,CAC7E,OAAOF,EAAAA,WAAWG,CAAK,CACzB,CAEA,SAAgBC,EAAiB,EAAuB,CAEtD,GADAF,EAAiBG,CAAK,EAClBA,EAAM,SAAS,GAAG,EACpB,MAAU,UAAU,6CAA6C,EAEnE,GAAIA,EAAM,WAAW,OAAO,EAC1B,MAAU,UACR,2DACF,EAEF,OAAOA,CACT,C"}
@@ -0,0 +1,2 @@
1
+ export declare function aggregationField<FIELDS extends string>(field: FIELDS): FIELDS;
2
+ export declare function aggregationAlias(alias: string): string;
@@ -0,0 +1,2 @@
1
+ export declare function aggregationField<FIELDS extends string>(field: FIELDS): FIELDS;
2
+ export declare function aggregationAlias(alias: string): string;
@@ -0,0 +1,13 @@
1
+ import { queryField as e } from "../field.es.js";
2
+ // src/dsl/aggregation/aliases.ts
3
+ function t(t) {
4
+ return e(t);
5
+ }
6
+ function n(e) {
7
+ if (t(e), e.includes(".")) throw TypeError("aggregation alias must contain one segment.");
8
+ if (e.startsWith("__wow")) throw TypeError("aggregation alias must not use the reserved __wow prefix.");
9
+ return e;
10
+ }
11
+ export { n as aggregationAlias, t as aggregationField };
12
+
13
+ //# sourceMappingURL=aliases.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aliases.es.js","names":["aggregationField","queryField","field","aggregationAlias","alias"],"sources":["../../../src/dsl/aggregation/aliases.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { queryField } from '../field.js';\n\n// Internal: how the parts of an aggregation name their fields and their\n// columns. index.ts does not re-export this file.\n\nexport function aggregationField<FIELDS extends string>(field: FIELDS): FIELDS {\n return queryField(field);\n}\n\nexport function aggregationAlias(alias: string): string {\n aggregationField(alias);\n if (alias.includes('.')) {\n throw new TypeError('aggregation alias must contain one segment.');\n }\n if (alias.startsWith('__wow')) {\n throw new TypeError(\n 'aggregation alias must not use the reserved __wow prefix.',\n );\n }\n return alias;\n}\n"],"mappings":";;AAkBA,SAAgBA,EAAwC,GAAuB;CAC7E,OAAOC,EAAWC,CAAK;AACzB;AAEA,SAAgBC,EAAiB,GAAuB;CAEtD,IADAH,EAAiBI,CAAK,GAClBA,EAAM,SAAS,GAAG,GACpB,MAAU,UAAU,6CAA6C;CAEnE,IAAIA,EAAM,WAAW,OAAO,GAC1B,MAAU,UACR,2DACF;CAEF,OAAOA;AACT"}
@@ -1,2 +1,2 @@
1
- const e=require("../constantName.cjs"),t=require("./types.cjs"),n=require("./expressionTrees.cjs"),r=require("../field.cjs"),i=require("../filter/scope.cjs"),a=require("./admit.cjs"),o=require("./derived.cjs"),s=require("./having.cjs");function c(e){return r.queryField(e)}function l(e){if(c(e),e.includes(`.`))throw TypeError(`aggregation alias must contain one segment.`);if(e.startsWith(`__wow`))throw TypeError(`aggregation alias must not use the reserved __wow prefix.`);return e}function u(e,n,r){return{type:t.AggregationExpressionType.BINARY,operator:e,left:n,right:r}}function d(e,n,r,{filter:i}={}){return{type:t.AggregationMetricType.NUMERIC,...i===void 0?{}:{filter:i},function:e,expression:n,alias:l(r)}}function f(e,t,n,{orderBy:r,filter:i}){return{type:e,field:c(t),alias:l(n),...r===void 0?{}:{orderBy:c(r)},...i===void 0?{}:{filter:i}}}function p(t,r){if(typeof t==`string`)return{field:c(t)};if(typeof t!=`object`||!t)throw TypeError(`${e.constantName(r)} group requires exactly one of field and expression.`);return n.requireValidExpressionTrees([t]),{expression:t}}function m(n,r,i){if(n===void 0)return{};if(!Object.values(t.AggregationGroupScope).includes(n))throw TypeError(`${e.constantName(r)} group scope is invalid.`);if(n===t.AggregationGroupScope.ROOT&&i.expression)throw TypeError(`${e.constantName(r)} with a ROOT scope requires a field input.`);return{scope:n}}var h={element(e,t){let n=c(e);return t===void 0?{path:n}:(i.requireElementScopedFilter(t,`Aggregation element filter`,!1),{path:n,filter:t})},field(e){return{type:t.AggregationExpressionType.FIELD,field:c(e)}},constant(e){if(!Number.isFinite(e))throw TypeError(`aggregation constant must be finite.`);return{type:t.AggregationExpressionType.CONSTANT,value:e}},dateDiff(e,n,r){if(!Object.values(t.DateDiffUnit).includes(r))throw TypeError(`date diff unit is invalid.`);return{type:t.AggregationExpressionType.DATE_DIFF,from:c(e),to:c(n),unit:r}},add:(e,n)=>u(t.AggregationExpressionOperator.ADD,e,n),subtract:(e,n)=>u(t.AggregationExpressionOperator.SUBTRACT,e,n),multiply:(e,n)=>u(t.AggregationExpressionOperator.MULTIPLY,e,n),divide:(e,n)=>u(t.AggregationExpressionOperator.DIVIDE,e,n),terms(e,n,{missingKey:r,scope:i}={}){if(r!==void 0&&(typeof r!=`string`||!r.trim()))throw TypeError(`terms missingKey must not be blank.`);let a=p(e,`terms`);if(r!==void 0&&a.expression)throw TypeError(`terms missingKey requires a field input.`);return{type:t.AggregationGroupType.TERMS,...r===void 0?{}:{missingKey:r},...a,...m(i,`terms`,a),alias:l(n)}},histogram(e,n,{interval:r,scope:i}){if(!Number.isFinite(r)||r<=0)throw TypeError(`histogram interval must be finite and greater than 0.`);let a=p(e,`histogram`);return{type:t.AggregationGroupType.HISTOGRAM,...a,...m(i,`histogram`,a),interval:r,alias:l(n)}},dateHistogram(e,n,{unit:r,timeZone:i=`UTC`,dense:a,scope:o}){if(a!==void 0&&typeof a!=`boolean`)throw TypeError(`date histogram dense must be boolean.`);if(!Object.values(t.AggregationDateUnit).includes(r))throw TypeError(`date histogram unit is invalid.`);if(typeof i!=`string`||!i.trim())throw TypeError(`date histogram timeZone cannot be blank.`);return{type:t.AggregationGroupType.DATE_HISTOGRAM,...a===void 0?{}:{dense:a},field:c(e),...m(o,`date-histogram`,{}),unit:r,alias:l(n),timeZone:i}},datePart(e,n,{part:r,timeZone:i=`UTC`,dense:a,scope:o}){if(a!==void 0&&typeof a!=`boolean`)throw TypeError(`date part dense must be boolean.`);if(!Object.values(t.AggregationDatePart).includes(r))throw TypeError(`date part is invalid.`);if(typeof i!=`string`||!i.trim())throw TypeError(`date part timeZone cannot be blank.`);return{type:t.AggregationGroupType.DATE_PART,...a===void 0?{}:{dense:a},field:c(e),...m(o,`date-part`,{}),part:r,alias:l(n),timeZone:i}},any(e,n,{filter:r}={}){return{type:t.AggregationMetricType.ANY,...r===void 0?{}:{filter:r},field:c(e),alias:l(n)}},first(e,n,r={}){return f(t.AggregationMetricType.FIRST,e,n,r)},last(e,n,r={}){return f(t.AggregationMetricType.LAST,e,n,r)},count(e,{filter:n}={}){return{type:t.AggregationMetricType.COUNT,...n===void 0?{}:{filter:n},alias:l(e)}},sum:(e,n,r)=>d(t.AggregationFunction.SUM,e,n,r),avg:(e,n,r)=>d(t.AggregationFunction.AVG,e,n,r),min:(e,n,r)=>d(t.AggregationFunction.MIN,e,n,r),max:(e,n,r)=>d(t.AggregationFunction.MAX,e,n,r),stddev:(e,n,r)=>d(t.AggregationFunction.STDDEV,e,n,r),variance:(e,n,r)=>d(t.AggregationFunction.VARIANCE,e,n,r),distinctCount(e,n,{filter:r}={}){return{type:t.AggregationMetricType.DISTINCT_COUNT,expression:e,alias:l(n),...r===void 0?{}:{filter:r}}},percentile(e,n,{percentile:r,filter:i}){if(!Number.isFinite(r)||r<=0||r>=100)throw TypeError(`percentile must be finite and within (0, 100).`);return{type:t.AggregationMetricType.PERCENTILE,expression:e,percentile:r,alias:l(n),...i===void 0?{}:{filter:i}}},derived(e,n){return{type:t.AggregationMetricType.DERIVED,expression:typeof e==`function`?e(o.derivedExpressionDsl):e,alias:l(n)}},having:s.havingDsl,query(e){return a.admitAggregationQuery(e)}};exports.aggregation=h;
1
+ const e=require("./types.cjs"),t=require("../filter/scope.cjs"),n=require("./aliases.cjs"),r=require("./groups.cjs"),i=require("./metrics.cjs"),a=require("./derived.cjs"),o=require("./having.cjs"),s=require("./admit.cjs");function c(t,n,r){return{type:e.AggregationExpressionType.BINARY,operator:t,left:n,right:r}}var l={element(e,r){let i=n.aggregationField(e);return r===void 0?{path:i}:(t.requireElementScopedFilter(r,`Aggregation element filter`,!1),{path:i,filter:r})},field(t){return{type:e.AggregationExpressionType.FIELD,field:n.aggregationField(t)}},constant(t){if(!Number.isFinite(t))throw TypeError(`aggregation constant must be finite.`);return{type:e.AggregationExpressionType.CONSTANT,value:t}},dateDiff(t,r,i){if(!Object.values(e.DateDiffUnit).includes(i))throw TypeError(`date diff unit is invalid.`);return{type:e.AggregationExpressionType.DATE_DIFF,from:n.aggregationField(t),to:n.aggregationField(r),unit:i}},add:(t,n)=>c(e.AggregationExpressionOperator.ADD,t,n),subtract:(t,n)=>c(e.AggregationExpressionOperator.SUBTRACT,t,n),multiply:(t,n)=>c(e.AggregationExpressionOperator.MULTIPLY,t,n),divide:(t,n)=>c(e.AggregationExpressionOperator.DIVIDE,t,n),query(e){return s.admitAggregationQuery(e)}},u={...l,...r.groupBuilders,...i.metricBuilders,...a.derivedBuilders,...o.havingBuilders};exports.aggregation=u,exports.queryBuilders=l;
2
2
  //# sourceMappingURL=builders.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"builders.cjs","names":["queryField","AggregationExpressionType","AggregationMetricType","constantName","AggregationGroupScope","DateDiffUnit","AggregationExpressionOperator","AggregationGroupType","AggregationDateUnit","AggregationDatePart","AggregationFunction","derivedExpressionDsl","havingDsl","admitAggregationQuery","require_constantName","require_types","require_expressionTrees","require_field","require_scope","require_admit","require_derived","require_having","aggregationField","field","aggregationAlias","alias","binary","numeric","predicate","fn","edge","orderBy","groupInput","input","type","groupScope","scope","source","aggregation","validPath","path","value","unit","from","to","left","right","missingKey","interval","dense","timeZone","part","options","expression","percentile","query"],"sources":["../../../src/dsl/aggregation/builders.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { constantName } from '../constantName.js';\nimport { queryField } from '../field.js';\nimport type {\n ElementFilterExpression,\n ExpressionFilter,\n} from '../filter/index.js';\nimport { requireElementScopedFilter } from '../filter/scope.js';\nimport { admitAggregationQuery } from './admit.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { derivedExpressionDsl, type DerivedExpressionDsl } from './derived.js';\nimport { havingDsl } from './having.js';\nimport {\n DateDiffUnit,\n AggregationDatePart,\n AggregationDateUnit,\n AggregationExpressionOperator,\n AggregationExpressionType,\n AggregationFunction,\n AggregationGroupScope,\n AggregationGroupType,\n AggregationMetricType,\n type AggregationElement,\n type AggregationExpression,\n type AggregationGroupInput,\n type DateDiffAggregationExpression,\n type AggregationMetricOptions,\n type AggregationQuery,\n type AnyAggregationMetric,\n type EdgeAggregationMetric,\n type EdgeAggregationOptions,\n type BinaryAggregationExpression,\n type ConstantAggregationExpression,\n type CountAggregationMetric,\n type DateHistogramAggregationGroup,\n type DateHistogramAggregationOptions,\n type DatePartAggregationGroup,\n type DatePartAggregationOptions,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DistinctCountAggregationMetric,\n type FieldAggregationExpression,\n type HistogramAggregationGroup,\n type HistogramAggregationOptions,\n type NumericAggregationMetric,\n type PercentileAggregationMetric,\n type PercentileAggregationOptions,\n type TermsAggregationGroup,\n type TermsAggregationOptions,\n} from './types.js';\n\nfunction aggregationField<FIELDS extends string>(field: FIELDS): FIELDS {\n return queryField(field);\n}\n\nfunction aggregationAlias(alias: string): string {\n aggregationField(alias);\n if (alias.includes('.')) {\n throw new TypeError('aggregation alias must contain one segment.');\n }\n if (alias.startsWith('__wow')) {\n throw new TypeError(\n 'aggregation alias must not use the reserved __wow prefix.',\n );\n }\n return alias;\n}\n\nfunction binary<FIELDS extends string>(\n operator: AggregationExpressionOperator,\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n): BinaryAggregationExpression<FIELDS> {\n return { type: AggregationExpressionType.BINARY, operator, left, right };\n}\n\nfunction numeric<FIELDS extends string>(\n fn: AggregationFunction,\n expression: AggregationExpression<FIELDS>,\n alias: string,\n { filter: predicate }: AggregationMetricOptions<FIELDS> = {},\n): NumericAggregationMetric<FIELDS> {\n return {\n type: AggregationMetricType.NUMERIC,\n ...(predicate === undefined ? {} : { filter: predicate }),\n function: fn,\n expression,\n alias: aggregationAlias(alias),\n };\n}\n\n/** Builds a `FIRST` or `LAST` metric; {@link aggregation.first}. */\nfunction edge<FIELDS extends string>(\n type: AggregationMetricType.FIRST | AggregationMetricType.LAST,\n field: FIELDS,\n alias: string,\n { orderBy, filter: predicate }: EdgeAggregationOptions<FIELDS>,\n): EdgeAggregationMetric<FIELDS> {\n return {\n type,\n field: aggregationField(field),\n alias: aggregationAlias(alias),\n ...(orderBy === undefined ? {} : { orderBy: aggregationField(orderBy) }),\n ...(predicate === undefined ? {} : { filter: predicate }),\n };\n}\n\n/**\n * The input of a TERMS or HISTOGRAM group: a field path, or an expression in\n * its place, never both, as Wow's `requireGroupInput` has it.\n */\nfunction groupInput<FIELDS extends string>(\n input: FIELDS | AggregationExpression<FIELDS>,\n type: string,\n): AggregationGroupInput<FIELDS> {\n if (typeof input === 'string') return { field: aggregationField(input) };\n if (input === null || typeof input !== 'object') {\n throw new TypeError(\n `${constantName(type)} group requires exactly one of field and expression.`,\n );\n }\n requireValidExpressionTrees([input]);\n return { expression: input };\n}\n\n/** A group's `scope`, sent only when given; `ROOT` needs a field input. */\nfunction groupScope(\n scope: AggregationGroupScope | undefined,\n type: string,\n source: { expression?: unknown },\n): { scope?: AggregationGroupScope } {\n if (scope === undefined) return {};\n if (!Object.values(AggregationGroupScope).includes(scope)) {\n throw new TypeError(`${constantName(type)} group scope is invalid.`);\n }\n if (scope === AggregationGroupScope.ROOT && source.expression) {\n throw new TypeError(\n `${constantName(type)} with a ROOT scope requires a field input.`,\n );\n }\n return { scope };\n}\n\n/**\n * Builders of an `AggregationQuery`: its elements, groups, metrics and the\n * arithmetic expressions metrics compute over. Each builder checks its own\n * part and throws a `TypeError` naming what is wrong; {@link aggregation.query}\n * checks the parts against each other.\n *\n * Every group and metric takes its target first, its alias second, and any\n * further options as a trailing object.\n */\nexport const aggregation = {\n /**\n * Aggregates over the elements of an array field instead of the root\n * documents. `{ path, filter? }`.\n *\n * @param path - The array field, a query field path.\n * @param predicate - Keeps only the elements that match; may not contain\n * root filters (id, owner, tenant, space, deletion) or any search, even\n * one that names its fields. An `EXPRESSION` filter is allowed.\n * @throws TypeError when `path` is not a valid field path or `predicate`\n * contains a root filter.\n * @example\n * ```typescript\n * aggregation.element('items', filter.gt('quantity', 0));\n * ```\n */\n element(\n path: string,\n predicate?: ElementFilterExpression | ExpressionFilter,\n ): AggregationElement {\n const validPath = aggregationField(path);\n if (predicate === undefined) return { path: validPath };\n requireElementScopedFilter(predicate, 'Aggregation element filter', false);\n return { path: validPath, filter: predicate };\n },\n /**\n * The value of a field, as an operand. `{ type: 'field', field }`.\n *\n * @throws TypeError when `field` is not a valid field path.\n * @example\n * ```typescript\n * aggregation.sum(aggregation.field('state.amount'), 'amount');\n * ```\n */\n field<FIELDS extends string>(\n field: FIELDS,\n ): FieldAggregationExpression<FIELDS> {\n return {\n type: AggregationExpressionType.FIELD,\n field: aggregationField(field),\n };\n },\n /**\n * A number, as an operand. `{ type: 'constant', value }`.\n *\n * @throws TypeError when `value` is not finite.\n * @example\n * ```typescript\n * aggregation.multiply(aggregation.field('price'), aggregation.constant(100));\n * ```\n */\n constant(value: number): ConstantAggregationExpression {\n if (!Number.isFinite(value)) {\n throw new TypeError('aggregation constant must be finite.');\n }\n return { type: AggregationExpressionType.CONSTANT, value };\n },\n /**\n * The time from the instant in `from` to the instant in `to`, `to − from`,\n * in `unit`, as a signed decimal: negative when `to` is earlier, and no\n * value when either instant is absent. A `DAY` is exactly 24 hours.\n * `{ type: 'date-diff', from, to, unit }`. Both fields must be\n * single-valued time fields, those whose `aggregate.groups` list\n * `DATE_HISTOGRAM` in the descriptor, and `unit` one of its\n * `analysis.dateDiffUnits`. Wow 9.2 and later.\n *\n * @throws TypeError when `from` or `to` is not a valid field path, or\n * `unit` is not a {@link DateDiffUnit}.\n * @example\n * ```typescript\n * // Hours from payment to shipping, averaged per warehouse.\n * aggregation.avg(\n * aggregation.dateDiff('state.paidAt', 'state.shippedAt', DateDiffUnit.HOUR),\n * 'hoursToShip',\n * );\n * ```\n */\n dateDiff<FIELDS extends string>(\n from: FIELDS,\n to: FIELDS,\n unit: DateDiffUnit,\n ): DateDiffAggregationExpression<FIELDS> {\n if (!Object.values(DateDiffUnit).includes(unit)) {\n throw new TypeError('date diff unit is invalid.');\n }\n return {\n type: AggregationExpressionType.DATE_DIFF,\n from: aggregationField(from),\n to: aggregationField(to),\n unit,\n };\n },\n /** `left + right`. `{ type: 'binary', operator: 'add', left, right }`. */\n add: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.ADD, left, right),\n /** `left - right`. `{ type: 'binary', operator: 'subtract', left, right }`. */\n subtract: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.SUBTRACT, left, right),\n /** `left * right`. `{ type: 'binary', operator: 'multiply', left, right }`. */\n multiply: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.MULTIPLY, left, right),\n /** `left / right`. `{ type: 'binary', operator: 'divide', left, right }`. */\n divide: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.DIVIDE, left, right),\n /**\n * Groups by each distinct value of a field, or of a computed expression.\n * `{ type: 'terms', field, alias, missingKey? }`, or\n * `{ type: 'terms', expression, alias }`.\n *\n * @param input - The field to group by, or an expression in its place\n * (Wow 9.2 and later, an expensive computation).\n * @param alias - The name of the group column in the result rows.\n * @param options.missingKey - The key of the rows without a value; only\n * with a field.\n * @param options.scope - What the field is relative to when the query\n * expands elements: `ROOT` groups the elements by a field of their root\n * record. Wow 9.9 and later.\n * @throws TypeError when `input` or `alias` is invalid, `missingKey` is\n * blank, or `missingKey` is given with an expression.\n * @example\n * ```typescript\n * aggregation.terms('state.status', 'status', { missingKey: 'NONE' });\n * aggregation.terms(\n * aggregation.dateDiff('state.paidAt', 'state.shippedAt', DateDiffUnit.DAY),\n * 'daysToShip',\n * );\n * ```\n */\n terms<FIELDS extends string>(\n input: FIELDS | AggregationExpression<FIELDS>,\n alias: string,\n { missingKey, scope }: TermsAggregationOptions = {},\n ): TermsAggregationGroup<FIELDS> {\n if (\n missingKey !== undefined &&\n (typeof missingKey !== 'string' || !missingKey.trim())\n ) {\n throw new TypeError('terms missingKey must not be blank.');\n }\n const source = groupInput(input, 'terms');\n if (missingKey !== undefined && source.expression) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n return {\n type: AggregationGroupType.TERMS,\n ...(missingKey === undefined ? {} : { missingKey }),\n ...source,\n ...groupScope(scope, 'terms', source),\n alias: aggregationAlias(alias),\n };\n },\n /**\n * Groups a number field, or a computed expression, into buckets of equal\n * width. `{ type: 'histogram', field | expression, interval, alias }`.\n *\n * @param input - The number field to bucket, or an expression in its\n * place (Wow 9.2 and later, an expensive computation).\n * @param alias - The name of the bucket column in the result rows.\n * @param options.interval - The bucket width.\n * @param options.scope - What the field is relative to when the query\n * expands elements: `ROOT` groups the elements by a field of their root\n * record. Wow 9.9 and later.\n * @throws TypeError when `interval` is not finite and greater than 0, or\n * `field` or `alias` is invalid.\n * @example\n * ```typescript\n * aggregation.histogram('state.amount', 'amountBand', { interval: 100 });\n * ```\n */\n histogram<FIELDS extends string>(\n input: FIELDS | AggregationExpression<FIELDS>,\n alias: string,\n { interval, scope }: HistogramAggregationOptions,\n ): HistogramAggregationGroup<FIELDS> {\n if (!Number.isFinite(interval) || interval <= 0) {\n throw new TypeError(\n 'histogram interval must be finite and greater than 0.',\n );\n }\n const source = groupInput(input, 'histogram');\n return {\n type: AggregationGroupType.HISTOGRAM,\n ...source,\n ...groupScope(scope, 'histogram', source),\n interval,\n alias: aggregationAlias(alias),\n };\n },\n /**\n * Groups a time field into calendar buckets.\n * `{ type: 'date-histogram', field, unit, alias, timeZone, dense? }`.\n *\n * @param field - The time field (epoch milliseconds) to bucket.\n * @param alias - The name of the bucket column in the result rows.\n * @param options.unit - The calendar unit of a bucket.\n * @param options.timeZone - The zone buckets are cut in. Defaults to `UTC`.\n * @param options.dense - Whether the empty buckets of the range are filled\n * in.\n * @param options.scope - What the field is relative to when the query\n * expands elements: `ROOT` groups the elements by a field of their root\n * record. Wow 9.9 and later.\n * @throws TypeError when `unit` is not an `AggregationDateUnit`,\n * `timeZone` is blank, `dense` is not a boolean, or `field` or `alias` is\n * invalid.\n * @example\n * ```typescript\n * aggregation.dateHistogram('createTime', 'day', {\n * unit: AggregationDateUnit.DAY,\n * timeZone: 'Asia/Shanghai',\n * });\n * ```\n */\n dateHistogram<FIELDS extends string>(\n field: FIELDS,\n alias: string,\n { unit, timeZone = 'UTC', dense, scope }: DateHistogramAggregationOptions,\n ): DateHistogramAggregationGroup<FIELDS> {\n if (dense !== undefined && typeof dense !== 'boolean') {\n throw new TypeError('date histogram dense must be boolean.');\n }\n if (!Object.values(AggregationDateUnit).includes(unit)) {\n throw new TypeError('date histogram unit is invalid.');\n }\n if (typeof timeZone !== 'string' || !timeZone.trim()) {\n throw new TypeError('date histogram timeZone cannot be blank.');\n }\n return {\n type: AggregationGroupType.DATE_HISTOGRAM,\n ...(dense === undefined ? {} : { dense }),\n field: aggregationField(field),\n ...groupScope(scope, 'date-histogram', {}),\n unit,\n alias: aggregationAlias(alias),\n timeZone,\n };\n },\n /**\n * Groups a time field by one calendar part of each instant, such as the\n * weekday or the hour, so records from different days share a bucket.\n * `{ type: 'date-part', field, part, alias, timeZone, dense? }`.\n *\n * The group's keys in the result rows are integers: `DAY_OF_WEEK` is the\n * ISO weekday, 1 (Monday) to 7 (Sunday); `DAY_OF_MONTH` 1 to 31;\n * `HOUR_OF_DAY` 0 to 23 on the wall clock of `timeZone`; `MONTH_OF_YEAR`\n * 1 to 12. With `dense`, every key of that domain comes back, those\n * without records carrying each metric's empty value; `dense` needs the\n * group to be the query's only one. Wow 9.2 and later.\n *\n * @param field - The time field (epoch milliseconds) to read the part of.\n * @param alias - The name of the part column in the result rows.\n * @param options.part - The calendar part to group by.\n * @param options.timeZone - The zone the part is read in. Defaults to\n * `UTC`.\n * @param options.dense - Whether every key of the part's domain is\n * returned.\n * @param options.scope - What the field is relative to when the query\n * expands elements: `ROOT` groups the elements by a field of their root\n * record. Wow 9.9 and later.\n * @throws TypeError when `part` is not an `AggregationDatePart`,\n * `timeZone` is blank, `dense` is not a boolean, or `field` or `alias` is\n * invalid.\n * @example\n * ```typescript\n * aggregation.datePart('createTime', 'weekday', {\n * part: AggregationDatePart.DAY_OF_WEEK,\n * timeZone: 'Asia/Shanghai',\n * });\n * ```\n */\n datePart<FIELDS extends string>(\n field: FIELDS,\n alias: string,\n { part, timeZone = 'UTC', dense, scope }: DatePartAggregationOptions,\n ): DatePartAggregationGroup<FIELDS> {\n if (dense !== undefined && typeof dense !== 'boolean') {\n throw new TypeError('date part dense must be boolean.');\n }\n if (!Object.values(AggregationDatePart).includes(part)) {\n throw new TypeError('date part is invalid.');\n }\n if (typeof timeZone !== 'string' || !timeZone.trim()) {\n throw new TypeError('date part timeZone cannot be blank.');\n }\n return {\n type: AggregationGroupType.DATE_PART,\n ...(dense === undefined ? {} : { dense }),\n field: aggregationField(field),\n ...groupScope(scope, 'date-part', {}),\n part,\n alias: aggregationAlias(alias),\n timeZone,\n };\n },\n /**\n * Any one value of a field within each group, of any type.\n * `{ type: 'any', field, alias, filter? }`.\n *\n * @throws TypeError when `field` or `alias` is invalid.\n * @example\n * ```typescript\n * aggregation.any('state.customerName', 'customer');\n * ```\n */\n any<FIELDS extends string>(\n field: FIELDS,\n alias: string,\n { filter: predicate }: AggregationMetricOptions<FIELDS> = {},\n ): AnyAggregationMetric<FIELDS> {\n return {\n type: AggregationMetricType.ANY,\n ...(predicate === undefined ? {} : { filter: predicate }),\n field: aggregationField(field),\n alias: aggregationAlias(alias),\n };\n },\n /**\n * The value of `field` on each group's earliest record by `orderBy`.\n * `{ type: 'first', field, alias, orderBy?, filter? }`.\n *\n * The value comes back in the field's own type, or `null` when no record\n * of the group has both a value and an `orderBy` position. Without\n * `orderBy` the server orders by the model's event time, which the\n * descriptor names as `analysis.firstLastOrderBy`. Neither a derived\n * metric nor `having` may refer to it. Wow 9.2 and later.\n *\n * @throws TypeError when `field`, `orderBy` or `alias` is invalid.\n * @example\n * ```typescript\n * aggregation.first('state.price', 'open', { orderBy: 'createTime' });\n * ```\n */\n first<FIELDS extends string>(\n field: FIELDS,\n alias: string,\n options: EdgeAggregationOptions<FIELDS> = {},\n ): EdgeAggregationMetric<FIELDS> {\n return edge(AggregationMetricType.FIRST, field, alias, options);\n },\n /**\n * The value of `field` on each group's latest record by `orderBy`.\n * `{ type: 'last', field, alias, orderBy?, filter? }`. As\n * {@link aggregation.first}, from the other end.\n *\n * @throws TypeError when `field`, `orderBy` or `alias` is invalid.\n * @example\n * ```typescript\n * aggregation.last('state.price', 'close', { orderBy: 'createTime' });\n * ```\n */\n last<FIELDS extends string>(\n field: FIELDS,\n alias: string,\n options: EdgeAggregationOptions<FIELDS> = {},\n ): EdgeAggregationMetric<FIELDS> {\n return edge(AggregationMetricType.LAST, field, alias, options);\n },\n /**\n * The number of rows in each group. `{ type: 'count', alias, filter? }`.\n *\n * @param alias - The name of the metric column in the result rows.\n * @param options.filter - Counts only the rows that match.\n * @throws TypeError when `alias` is invalid.\n * @example\n * ```typescript\n * aggregation.count('paid', { filter: filter.eq('state.status', 'PAID') });\n * ```\n */\n count<FIELDS extends string = string>(\n alias: string,\n { filter: predicate }: AggregationMetricOptions<FIELDS> = {},\n ): CountAggregationMetric<FIELDS> {\n return {\n type: AggregationMetricType.COUNT,\n ...(predicate === undefined ? {} : { filter: predicate }),\n alias: aggregationAlias(alias),\n };\n },\n /**\n * The sum of an expression. `{ type: 'numeric', function: 'sum',\n * expression, alias, filter? }`.\n *\n * @example\n * ```typescript\n * aggregation.sum(aggregation.field('state.amount'), 'revenue');\n * ```\n */\n sum: <FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n options?: AggregationMetricOptions<FIELDS>,\n ) => numeric(AggregationFunction.SUM, expression, alias, options),\n /** The average of an expression; see {@link aggregation.sum}. */\n avg: <FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n options?: AggregationMetricOptions<FIELDS>,\n ) => numeric(AggregationFunction.AVG, expression, alias, options),\n /** The least value of an expression; see {@link aggregation.sum}. */\n min: <FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n options?: AggregationMetricOptions<FIELDS>,\n ) => numeric(AggregationFunction.MIN, expression, alias, options),\n /** The greatest value of an expression; see {@link aggregation.sum}. */\n max: <FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n options?: AggregationMetricOptions<FIELDS>,\n ) => numeric(AggregationFunction.MAX, expression, alias, options),\n /** The standard deviation of an expression; see {@link aggregation.sum}. */\n stddev: <FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n options?: AggregationMetricOptions<FIELDS>,\n ) => numeric(AggregationFunction.STDDEV, expression, alias, options),\n /** The variance of an expression; see {@link aggregation.sum}. */\n variance: <FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n options?: AggregationMetricOptions<FIELDS>,\n ) => numeric(AggregationFunction.VARIANCE, expression, alias, options),\n /**\n * The number of distinct values of an expression.\n * `{ type: 'distinct-count', expression, alias, filter? }`.\n *\n * @example\n * ```typescript\n * aggregation.distinctCount(aggregation.field('ownerId'), 'customers');\n * ```\n */\n distinctCount<FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n { filter: predicate }: AggregationMetricOptions<FIELDS> = {},\n ): DistinctCountAggregationMetric<FIELDS> {\n return {\n type: AggregationMetricType.DISTINCT_COUNT,\n expression,\n alias: aggregationAlias(alias),\n ...(predicate === undefined ? {} : { filter: predicate }),\n };\n },\n /**\n * A percentile of an expression.\n * `{ type: 'percentile', expression, percentile, alias, filter? }`.\n *\n * @param options.percentile - Which percentile, within (0, 100).\n * @throws TypeError when `percentile` is not finite and within (0, 100), or\n * `alias` is invalid.\n * @example\n * ```typescript\n * aggregation.percentile(aggregation.field('latency'), 'p95', { percentile: 95 });\n * ```\n */\n percentile<FIELDS extends string>(\n expression: AggregationExpression<FIELDS>,\n alias: string,\n { percentile, filter: predicate }: PercentileAggregationOptions<FIELDS>,\n ): PercentileAggregationMetric<FIELDS> {\n if (!Number.isFinite(percentile) || percentile <= 0 || percentile >= 100) {\n throw new TypeError('percentile must be finite and within (0, 100).');\n }\n return {\n type: AggregationMetricType.PERCENTILE,\n expression,\n percentile,\n alias: aggregationAlias(alias),\n ...(predicate === undefined ? {} : { filter: predicate }),\n };\n },\n /**\n * A metric computed from other metrics of the same row, by their aliases.\n * `{ type: 'derived', expression, alias }`. `aggregation.query()` checks\n * that it refers only to metrics declared before it.\n *\n * @param expression - The arithmetic: a callback that builds it from the\n * {@link DerivedExpressionDsl} it is handed (`ref`, `constant`, `add`,\n * `subtract`, `multiply`, `divide`), or an already-built tree.\n * @throws TypeError when `alias` is invalid, or a `constant` is not finite.\n * @example\n * ```typescript\n * aggregation.derived(\n * d => d.divide(d.ref('revenue'), d.ref('orders')),\n * 'averageOrder',\n * );\n * ```\n */\n derived(\n expression:\n DerivedExpression | ((d: DerivedExpressionDsl) => DerivedExpression),\n alias: string,\n ): DerivedAggregationMetric {\n return {\n type: AggregationMetricType.DERIVED,\n expression:\n typeof expression === 'function'\n ? expression(derivedExpressionDsl)\n : expression,\n alias: aggregationAlias(alias),\n };\n },\n /**\n * The builders of the query's `having`: conditions on the metric columns of\n * the grouped rows (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `between`, `isIn`,\n * `isNull`, `isNotNull`) and their `and`/`or`. See `HavingDsl`.\n *\n * @example\n * ```typescript\n * aggregation.query({\n * groupBy: [aggregation.terms('state.status', 'status')],\n * metrics: [aggregation.count('orders')],\n * having: aggregation.having.gt('orders', 10),\n * });\n * ```\n */\n having: havingDsl,\n\n /**\n * Admits a whole aggregation query against the rules Wow enforces on arrival.\n *\n * The factories above each check their own part; only the assembled query\n * can answer the questions that span parts — whether two aliases collide,\n * whether a sort names one of them, whether `having` has rows to filter.\n * Wow checks all of it in `AggregationQuery`'s constructor and answers a\n * query that fails with a 400, so the same rules run here against the object\n * about to be sent.\n */\n query<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n >(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n ): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n return admitAggregationQuery(query);\n },\n};\n"],"mappings":"A,4OA+DA,SAASsB,EAAwC,EAAuB,CACtE,OAAOtB,EAAAA,WAAWuB,CAAK,CACzB,CAEA,SAASC,EAAiB,EAAuB,CAE/C,GADAF,EAAiBG,CAAK,EAClBA,EAAM,SAAS,GAAG,EACpB,MAAU,UAAU,6CAA6C,EAEnE,GAAIA,EAAM,WAAW,OAAO,EAC1B,MAAU,UACR,2DACF,EAEF,OAAOA,CACT,CAEA,SAASC,EACP,EACA,EACA,EACqC,CACrC,MAAO,CAAE,KAAMzB,EAAAA,0BAA0B,OAAQ,WAAU,OAAM,OAAM,CACzE,CAEA,SAAS0B,EACP,EACA,EACA,EACA,CAAE,OAAQC,GAAgD,CAAC,EACzB,CAClC,MAAO,CACL,KAAM1B,EAAAA,sBAAsB,QAC5B,GAAI0B,IAAc,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQA,CAAU,EACvD,SAAUC,EACV,aACA,MAAOL,EAAiBC,CAAK,CAC/B,CACF,CAGA,SAASK,EACP,EACA,EACA,EACA,CAAE,UAAS,OAAQF,GACY,CAC/B,MAAO,CACL,OACA,MAAON,EAAiBC,CAAK,EAC7B,MAAOC,EAAiBC,CAAK,EAC7B,GAAIM,IAAY,IAAA,GAAY,CAAC,EAAI,CAAE,QAAST,EAAiBS,CAAO,CAAE,EACtE,GAAIH,IAAc,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQA,CAAU,CACzD,CACF,CAMA,SAASI,EACP,EACA,EAC+B,CAC/B,GAAI,OAAOC,GAAU,SAAU,MAAO,CAAE,MAAOX,EAAiBW,CAAK,CAAE,EACvE,GAAsB,OA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,CAAC,EAAI,CAAE,OAAQA,CAAU,CACzD,CACF,EAkBA,QACE,EAEA,EAC0B,CAC1B,MAAO,CACL,KAAM1B,EAAAA,sBAAsB,QAC5B,WACE,OAAOmD,GAAe,WAClBA,EAAW1C,EAAAA,oBAAoB,EAC/B0C,EACN,MAAO7B,EAAiBC,CAAK,CAC/B,CACF,EAeA,OAAQb,EAAAA,UAYR,MAIE,EACmD,CACnD,OAAOC,EAAAA,sBAAsB0C,CAAK,CACpC,CACF,E"}
1
+ {"version":3,"file":"builders.cjs","names":["AggregationExpressionType","aggregationField","DateDiffUnit","AggregationExpressionOperator","admitAggregationQuery","groupBuilders","metricBuilders","derivedBuilders","havingBuilders","require_types","require_scope","require_aliases","require_groups","require_metrics","require_derived","require_having","require_admit","binary","queryBuilders","validPath","path","predicate","field","value","unit","from","to","left","right","query","aggregation"],"sources":["../../../src/dsl/aggregation/builders.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ElementFilterExpression,\n ExpressionFilter,\n} from '../filter/index.js';\nimport { requireElementScopedFilter } from '../filter/scope.js';\nimport { admitAggregationQuery } from './admit.js';\nimport { aggregationField } from './aliases.js';\nimport {\n DateDiffUnit,\n AggregationExpressionOperator,\n AggregationExpressionType,\n type AggregationElement,\n type AggregationExpression,\n type DateDiffAggregationExpression,\n type AggregationQuery,\n type BinaryAggregationExpression,\n type ConstantAggregationExpression,\n type FieldAggregationExpression,\n} from './types.js';\nimport { derivedBuilders } from './derived.js';\nimport { groupBuilders } from './groups.js';\nimport { havingBuilders } from './having.js';\nimport { metricBuilders } from './metrics.js';\n\nfunction binary<FIELDS extends string>(\n operator: AggregationExpressionOperator,\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n): BinaryAggregationExpression<FIELDS> {\n return { type: AggregationExpressionType.BINARY, operator, left, right };\n}\n\n/** The builders of an aggregation query's elements and expressions, and of the query itself. */\nexport const queryBuilders = {\n /**\n * Aggregates over the elements of an array field instead of the root\n * documents. `{ path, filter? }`.\n *\n * @param path - The array field, a query field path.\n * @param predicate - Keeps only the elements that match; may not contain\n * root filters (id, owner, tenant, space, deletion) or any search, even\n * one that names its fields. An `EXPRESSION` filter is allowed.\n * @throws TypeError when `path` is not a valid field path or `predicate`\n * contains a root filter.\n * @example\n * ```typescript\n * aggregation.element('items', filter.gt('quantity', 0));\n * ```\n */\n element(\n path: string,\n predicate?: ElementFilterExpression | ExpressionFilter,\n ): AggregationElement {\n const validPath = aggregationField(path);\n if (predicate === undefined) return { path: validPath };\n requireElementScopedFilter(predicate, 'Aggregation element filter', false);\n return { path: validPath, filter: predicate };\n },\n /**\n * The value of a field, as an operand. `{ type: 'field', field }`.\n *\n * @throws TypeError when `field` is not a valid field path.\n * @example\n * ```typescript\n * aggregation.sum(aggregation.field('state.amount'), 'amount');\n * ```\n */\n field<FIELDS extends string>(\n field: FIELDS,\n ): FieldAggregationExpression<FIELDS> {\n return {\n type: AggregationExpressionType.FIELD,\n field: aggregationField(field),\n };\n },\n /**\n * A number, as an operand. `{ type: 'constant', value }`.\n *\n * @throws TypeError when `value` is not finite.\n * @example\n * ```typescript\n * aggregation.multiply(aggregation.field('price'), aggregation.constant(100));\n * ```\n */\n constant(value: number): ConstantAggregationExpression {\n if (!Number.isFinite(value)) {\n throw new TypeError('aggregation constant must be finite.');\n }\n return { type: AggregationExpressionType.CONSTANT, value };\n },\n /**\n * The time from the instant in `from` to the instant in `to`, `to − from`,\n * in `unit`, as a signed decimal: negative when `to` is earlier, and no\n * value when either instant is absent. A `DAY` is exactly 24 hours.\n * `{ type: 'date-diff', from, to, unit }`. Both fields must be\n * single-valued time fields, those whose `aggregate.groups` list\n * `DATE_HISTOGRAM` in the descriptor, and `unit` one of its\n * `analysis.dateDiffUnits`. Wow 9.2 and later.\n *\n * @throws TypeError when `from` or `to` is not a valid field path, or\n * `unit` is not a {@link DateDiffUnit}.\n * @example\n * ```typescript\n * // Hours from payment to shipping, averaged per warehouse.\n * aggregation.avg(\n * aggregation.dateDiff('state.paidAt', 'state.shippedAt', DateDiffUnit.HOUR),\n * 'hoursToShip',\n * );\n * ```\n */\n dateDiff<FIELDS extends string>(\n from: FIELDS,\n to: FIELDS,\n unit: DateDiffUnit,\n ): DateDiffAggregationExpression<FIELDS> {\n if (!Object.values(DateDiffUnit).includes(unit)) {\n throw new TypeError('date diff unit is invalid.');\n }\n return {\n type: AggregationExpressionType.DATE_DIFF,\n from: aggregationField(from),\n to: aggregationField(to),\n unit,\n };\n },\n /** `left + right`. `{ type: 'binary', operator: 'add', left, right }`. */\n add: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.ADD, left, right),\n /** `left - right`. `{ type: 'binary', operator: 'subtract', left, right }`. */\n subtract: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.SUBTRACT, left, right),\n /** `left * right`. `{ type: 'binary', operator: 'multiply', left, right }`. */\n multiply: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.MULTIPLY, left, right),\n /** `left / right`. `{ type: 'binary', operator: 'divide', left, right }`. */\n divide: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.DIVIDE, left, right),\n /**\n * Admits a whole aggregation query against the rules Wow enforces on arrival.\n *\n * The factories above each check their own part; only the assembled query\n * can answer the questions that span parts — whether two aliases collide,\n * whether a sort names one of them, whether `having` has rows to filter.\n * Wow checks all of it in `AggregationQuery`'s constructor and answers a\n * query that fails with a 400, so the same rules run here against the object\n * about to be sent.\n */\n query<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n >(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n ): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n return admitAggregationQuery(query);\n },\n};\n\n/**\n * Builders of an `AggregationQuery`: its elements, groups, metrics and the\n * arithmetic expressions metrics compute over. Each builder checks its own\n * part and throws a `TypeError` naming what is wrong; {@link aggregation.query}\n * checks the parts against each other.\n *\n * Every group and metric takes its target first, its alias second, and any\n * further options as a trailing object.\n */\nexport const aggregation: typeof queryBuilders &\n typeof groupBuilders &\n typeof metricBuilders &\n typeof derivedBuilders &\n typeof havingBuilders = {\n ...queryBuilders,\n ...groupBuilders,\n ...metricBuilders,\n ...derivedBuilders,\n ...havingBuilders,\n};\n"],"mappings":"A,8NAqCA,SAASiB,EACP,EACA,EACA,EACqC,CACrC,MAAO,CAAE,KAAMjB,EAAAA,0BAA0B,OAAQ,WAAU,OAAM,OAAM,CACzE,CAGA,IAAakB,EAAgB,CAgB3B,QACE,EACA,EACoB,CACpB,IAAMC,EAAYlB,EAAAA,iBAAiBmB,CAAI,EAGvC,OAFIC,IAAc,IAAA,GAAkB,CAAE,KAAMF,CAAU,GACtDT,EAAA,2BAA2BW,EAAW,6BAA8B,EAAK,EAClE,CAAE,KAAMF,EAAW,OAAQE,CAAU,EAC9C,EAUA,MACE,EACoC,CACpC,MAAO,CACL,KAAMrB,EAAAA,0BAA0B,MAChC,MAAOC,EAAAA,iBAAiBqB,CAAK,CAC/B,CACF,EAUA,SAAS,EAA8C,CACrD,GAAI,CAAC,OAAO,SAASC,CAAK,EACxB,MAAU,UAAU,sCAAsC,EAE5D,MAAO,CAAE,KAAMvB,EAAAA,0BAA0B,SAAU,OAAM,CAC3D,EAqBA,SACE,EACA,EACA,EACuC,CACvC,GAAI,CAAC,OAAO,OAAOE,EAAAA,YAAY,CAAC,CAAC,SAASsB,CAAI,EAC5C,MAAU,UAAU,4BAA4B,EAElD,MAAO,CACL,KAAMxB,EAAAA,0BAA0B,UAChC,KAAMC,EAAAA,iBAAiBwB,CAAI,EAC3B,GAAIxB,EAAAA,iBAAiByB,CAAE,EACvB,MACF,CACF,EAEA,KACE,EACA,IACGT,EAAOd,EAAAA,8BAA8B,IAAKwB,EAAMC,CAAK,EAE1D,UACE,EACA,IACGX,EAAOd,EAAAA,8BAA8B,SAAUwB,EAAMC,CAAK,EAE/D,UACE,EACA,IACGX,EAAOd,EAAAA,8BAA8B,SAAUwB,EAAMC,CAAK,EAE/D,QACE,EACA,IACGX,EAAOd,EAAAA,8BAA8B,OAAQwB,EAAMC,CAAK,EAW7D,MAIE,EACmD,CACnD,OAAOxB,EAAAA,sBAAsByB,CAAK,CACpC,CACF,EAWaC,EAIa,CACxB,GAAGZ,EACH,GAAGb,EAAAA,cACH,GAAGC,EAAAA,eACH,GAAGC,EAAAA,gBACH,GAAGC,EAAAA,cACL,E"}
@@ -1,16 +1,11 @@
1
1
  import { ElementFilterExpression, ExpressionFilter } from '../filter/index.cjs';
2
- import { DerivedExpressionDsl } from './derived.cjs';
3
- import { DateDiffUnit, AggregationElement, AggregationExpression, DateDiffAggregationExpression, AggregationMetricOptions, AggregationQuery, AnyAggregationMetric, EdgeAggregationMetric, EdgeAggregationOptions, BinaryAggregationExpression, ConstantAggregationExpression, CountAggregationMetric, DateHistogramAggregationGroup, DateHistogramAggregationOptions, DatePartAggregationGroup, DatePartAggregationOptions, DerivedAggregationMetric, DerivedExpression, DistinctCountAggregationMetric, FieldAggregationExpression, HistogramAggregationGroup, HistogramAggregationOptions, NumericAggregationMetric, PercentileAggregationMetric, PercentileAggregationOptions, TermsAggregationGroup, TermsAggregationOptions } from './types.cjs';
4
- /**
5
- * Builders of an `AggregationQuery`: its elements, groups, metrics and the
6
- * arithmetic expressions metrics compute over. Each builder checks its own
7
- * part and throws a `TypeError` naming what is wrong; {@link aggregation.query}
8
- * checks the parts against each other.
9
- *
10
- * Every group and metric takes its target first, its alias second, and any
11
- * further options as a trailing object.
12
- */
13
- export declare const aggregation: {
2
+ import { DateDiffUnit, AggregationElement, AggregationExpression, DateDiffAggregationExpression, AggregationQuery, BinaryAggregationExpression, ConstantAggregationExpression, FieldAggregationExpression } from './types.cjs';
3
+ import { derivedBuilders } from './derived.cjs';
4
+ import { groupBuilders } from './groups.cjs';
5
+ import { havingBuilders } from './having.cjs';
6
+ import { metricBuilders } from './metrics.cjs';
7
+ /** The builders of an aggregation query's elements and expressions, and of the query itself. */
8
+ export declare const queryBuilders: {
14
9
  /**
15
10
  * Aggregates over the elements of an array field instead of the root
16
11
  * documents. `{ path, filter? }`.
@@ -76,237 +71,6 @@ export declare const aggregation: {
76
71
  multiply: <FIELDS extends string>(left: AggregationExpression<FIELDS>, right: AggregationExpression<FIELDS>) => BinaryAggregationExpression<FIELDS>;
77
72
  /** `left / right`. `{ type: 'binary', operator: 'divide', left, right }`. */
78
73
  divide: <FIELDS extends string>(left: AggregationExpression<FIELDS>, right: AggregationExpression<FIELDS>) => BinaryAggregationExpression<FIELDS>;
79
- /**
80
- * Groups by each distinct value of a field, or of a computed expression.
81
- * `{ type: 'terms', field, alias, missingKey? }`, or
82
- * `{ type: 'terms', expression, alias }`.
83
- *
84
- * @param input - The field to group by, or an expression in its place
85
- * (Wow 9.2 and later, an expensive computation).
86
- * @param alias - The name of the group column in the result rows.
87
- * @param options.missingKey - The key of the rows without a value; only
88
- * with a field.
89
- * @param options.scope - What the field is relative to when the query
90
- * expands elements: `ROOT` groups the elements by a field of their root
91
- * record. Wow 9.9 and later.
92
- * @throws TypeError when `input` or `alias` is invalid, `missingKey` is
93
- * blank, or `missingKey` is given with an expression.
94
- * @example
95
- * ```typescript
96
- * aggregation.terms('state.status', 'status', { missingKey: 'NONE' });
97
- * aggregation.terms(
98
- * aggregation.dateDiff('state.paidAt', 'state.shippedAt', DateDiffUnit.DAY),
99
- * 'daysToShip',
100
- * );
101
- * ```
102
- */
103
- terms<FIELDS extends string>(input: FIELDS | AggregationExpression<FIELDS>, alias: string, { missingKey, scope }?: TermsAggregationOptions): TermsAggregationGroup<FIELDS>;
104
- /**
105
- * Groups a number field, or a computed expression, into buckets of equal
106
- * width. `{ type: 'histogram', field | expression, interval, alias }`.
107
- *
108
- * @param input - The number field to bucket, or an expression in its
109
- * place (Wow 9.2 and later, an expensive computation).
110
- * @param alias - The name of the bucket column in the result rows.
111
- * @param options.interval - The bucket width.
112
- * @param options.scope - What the field is relative to when the query
113
- * expands elements: `ROOT` groups the elements by a field of their root
114
- * record. Wow 9.9 and later.
115
- * @throws TypeError when `interval` is not finite and greater than 0, or
116
- * `field` or `alias` is invalid.
117
- * @example
118
- * ```typescript
119
- * aggregation.histogram('state.amount', 'amountBand', { interval: 100 });
120
- * ```
121
- */
122
- histogram<FIELDS extends string>(input: FIELDS | AggregationExpression<FIELDS>, alias: string, { interval, scope }: HistogramAggregationOptions): HistogramAggregationGroup<FIELDS>;
123
- /**
124
- * Groups a time field into calendar buckets.
125
- * `{ type: 'date-histogram', field, unit, alias, timeZone, dense? }`.
126
- *
127
- * @param field - The time field (epoch milliseconds) to bucket.
128
- * @param alias - The name of the bucket column in the result rows.
129
- * @param options.unit - The calendar unit of a bucket.
130
- * @param options.timeZone - The zone buckets are cut in. Defaults to `UTC`.
131
- * @param options.dense - Whether the empty buckets of the range are filled
132
- * in.
133
- * @param options.scope - What the field is relative to when the query
134
- * expands elements: `ROOT` groups the elements by a field of their root
135
- * record. Wow 9.9 and later.
136
- * @throws TypeError when `unit` is not an `AggregationDateUnit`,
137
- * `timeZone` is blank, `dense` is not a boolean, or `field` or `alias` is
138
- * invalid.
139
- * @example
140
- * ```typescript
141
- * aggregation.dateHistogram('createTime', 'day', {
142
- * unit: AggregationDateUnit.DAY,
143
- * timeZone: 'Asia/Shanghai',
144
- * });
145
- * ```
146
- */
147
- dateHistogram<FIELDS extends string>(field: FIELDS, alias: string, { unit, timeZone, dense, scope }: DateHistogramAggregationOptions): DateHistogramAggregationGroup<FIELDS>;
148
- /**
149
- * Groups a time field by one calendar part of each instant, such as the
150
- * weekday or the hour, so records from different days share a bucket.
151
- * `{ type: 'date-part', field, part, alias, timeZone, dense? }`.
152
- *
153
- * The group's keys in the result rows are integers: `DAY_OF_WEEK` is the
154
- * ISO weekday, 1 (Monday) to 7 (Sunday); `DAY_OF_MONTH` 1 to 31;
155
- * `HOUR_OF_DAY` 0 to 23 on the wall clock of `timeZone`; `MONTH_OF_YEAR`
156
- * 1 to 12. With `dense`, every key of that domain comes back, those
157
- * without records carrying each metric's empty value; `dense` needs the
158
- * group to be the query's only one. Wow 9.2 and later.
159
- *
160
- * @param field - The time field (epoch milliseconds) to read the part of.
161
- * @param alias - The name of the part column in the result rows.
162
- * @param options.part - The calendar part to group by.
163
- * @param options.timeZone - The zone the part is read in. Defaults to
164
- * `UTC`.
165
- * @param options.dense - Whether every key of the part's domain is
166
- * returned.
167
- * @param options.scope - What the field is relative to when the query
168
- * expands elements: `ROOT` groups the elements by a field of their root
169
- * record. Wow 9.9 and later.
170
- * @throws TypeError when `part` is not an `AggregationDatePart`,
171
- * `timeZone` is blank, `dense` is not a boolean, or `field` or `alias` is
172
- * invalid.
173
- * @example
174
- * ```typescript
175
- * aggregation.datePart('createTime', 'weekday', {
176
- * part: AggregationDatePart.DAY_OF_WEEK,
177
- * timeZone: 'Asia/Shanghai',
178
- * });
179
- * ```
180
- */
181
- datePart<FIELDS extends string>(field: FIELDS, alias: string, { part, timeZone, dense, scope }: DatePartAggregationOptions): DatePartAggregationGroup<FIELDS>;
182
- /**
183
- * Any one value of a field within each group, of any type.
184
- * `{ type: 'any', field, alias, filter? }`.
185
- *
186
- * @throws TypeError when `field` or `alias` is invalid.
187
- * @example
188
- * ```typescript
189
- * aggregation.any('state.customerName', 'customer');
190
- * ```
191
- */
192
- any<FIELDS extends string>(field: FIELDS, alias: string, { filter: predicate }?: AggregationMetricOptions<FIELDS>): AnyAggregationMetric<FIELDS>;
193
- /**
194
- * The value of `field` on each group's earliest record by `orderBy`.
195
- * `{ type: 'first', field, alias, orderBy?, filter? }`.
196
- *
197
- * The value comes back in the field's own type, or `null` when no record
198
- * of the group has both a value and an `orderBy` position. Without
199
- * `orderBy` the server orders by the model's event time, which the
200
- * descriptor names as `analysis.firstLastOrderBy`. Neither a derived
201
- * metric nor `having` may refer to it. Wow 9.2 and later.
202
- *
203
- * @throws TypeError when `field`, `orderBy` or `alias` is invalid.
204
- * @example
205
- * ```typescript
206
- * aggregation.first('state.price', 'open', { orderBy: 'createTime' });
207
- * ```
208
- */
209
- first<FIELDS extends string>(field: FIELDS, alias: string, options?: EdgeAggregationOptions<FIELDS>): EdgeAggregationMetric<FIELDS>;
210
- /**
211
- * The value of `field` on each group's latest record by `orderBy`.
212
- * `{ type: 'last', field, alias, orderBy?, filter? }`. As
213
- * {@link aggregation.first}, from the other end.
214
- *
215
- * @throws TypeError when `field`, `orderBy` or `alias` is invalid.
216
- * @example
217
- * ```typescript
218
- * aggregation.last('state.price', 'close', { orderBy: 'createTime' });
219
- * ```
220
- */
221
- last<FIELDS extends string>(field: FIELDS, alias: string, options?: EdgeAggregationOptions<FIELDS>): EdgeAggregationMetric<FIELDS>;
222
- /**
223
- * The number of rows in each group. `{ type: 'count', alias, filter? }`.
224
- *
225
- * @param alias - The name of the metric column in the result rows.
226
- * @param options.filter - Counts only the rows that match.
227
- * @throws TypeError when `alias` is invalid.
228
- * @example
229
- * ```typescript
230
- * aggregation.count('paid', { filter: filter.eq('state.status', 'PAID') });
231
- * ```
232
- */
233
- count<FIELDS extends string = string>(alias: string, { filter: predicate }?: AggregationMetricOptions<FIELDS>): CountAggregationMetric<FIELDS>;
234
- /**
235
- * The sum of an expression. `{ type: 'numeric', function: 'sum',
236
- * expression, alias, filter? }`.
237
- *
238
- * @example
239
- * ```typescript
240
- * aggregation.sum(aggregation.field('state.amount'), 'revenue');
241
- * ```
242
- */
243
- sum: <FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, options?: AggregationMetricOptions<FIELDS>) => NumericAggregationMetric<FIELDS>;
244
- /** The average of an expression; see {@link aggregation.sum}. */
245
- avg: <FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, options?: AggregationMetricOptions<FIELDS>) => NumericAggregationMetric<FIELDS>;
246
- /** The least value of an expression; see {@link aggregation.sum}. */
247
- min: <FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, options?: AggregationMetricOptions<FIELDS>) => NumericAggregationMetric<FIELDS>;
248
- /** The greatest value of an expression; see {@link aggregation.sum}. */
249
- max: <FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, options?: AggregationMetricOptions<FIELDS>) => NumericAggregationMetric<FIELDS>;
250
- /** The standard deviation of an expression; see {@link aggregation.sum}. */
251
- stddev: <FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, options?: AggregationMetricOptions<FIELDS>) => NumericAggregationMetric<FIELDS>;
252
- /** The variance of an expression; see {@link aggregation.sum}. */
253
- variance: <FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, options?: AggregationMetricOptions<FIELDS>) => NumericAggregationMetric<FIELDS>;
254
- /**
255
- * The number of distinct values of an expression.
256
- * `{ type: 'distinct-count', expression, alias, filter? }`.
257
- *
258
- * @example
259
- * ```typescript
260
- * aggregation.distinctCount(aggregation.field('ownerId'), 'customers');
261
- * ```
262
- */
263
- distinctCount<FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, { filter: predicate }?: AggregationMetricOptions<FIELDS>): DistinctCountAggregationMetric<FIELDS>;
264
- /**
265
- * A percentile of an expression.
266
- * `{ type: 'percentile', expression, percentile, alias, filter? }`.
267
- *
268
- * @param options.percentile - Which percentile, within (0, 100).
269
- * @throws TypeError when `percentile` is not finite and within (0, 100), or
270
- * `alias` is invalid.
271
- * @example
272
- * ```typescript
273
- * aggregation.percentile(aggregation.field('latency'), 'p95', { percentile: 95 });
274
- * ```
275
- */
276
- percentile<FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, { percentile, filter: predicate }: PercentileAggregationOptions<FIELDS>): PercentileAggregationMetric<FIELDS>;
277
- /**
278
- * A metric computed from other metrics of the same row, by their aliases.
279
- * `{ type: 'derived', expression, alias }`. `aggregation.query()` checks
280
- * that it refers only to metrics declared before it.
281
- *
282
- * @param expression - The arithmetic: a callback that builds it from the
283
- * {@link DerivedExpressionDsl} it is handed (`ref`, `constant`, `add`,
284
- * `subtract`, `multiply`, `divide`), or an already-built tree.
285
- * @throws TypeError when `alias` is invalid, or a `constant` is not finite.
286
- * @example
287
- * ```typescript
288
- * aggregation.derived(
289
- * d => d.divide(d.ref('revenue'), d.ref('orders')),
290
- * 'averageOrder',
291
- * );
292
- * ```
293
- */
294
- derived(expression: DerivedExpression | ((d: DerivedExpressionDsl) => DerivedExpression), alias: string): DerivedAggregationMetric;
295
- /**
296
- * The builders of the query's `having`: conditions on the metric columns of
297
- * the grouped rows (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `between`, `isIn`,
298
- * `isNull`, `isNotNull`) and their `and`/`or`. See `HavingDsl`.
299
- *
300
- * @example
301
- * ```typescript
302
- * aggregation.query({
303
- * groupBy: [aggregation.terms('state.status', 'status')],
304
- * metrics: [aggregation.count('orders')],
305
- * having: aggregation.having.gt('orders', 10),
306
- * });
307
- * ```
308
- */
309
- having: import('./having.cjs').HavingDsl;
310
74
  /**
311
75
  * Admits a whole aggregation query against the rules Wow enforces on arrival.
312
76
  *
@@ -319,3 +83,13 @@ export declare const aggregation: {
319
83
  */
320
84
  query<ROOT_FIELDS extends string = string, AGGREGATION_FIELDS extends string = ROOT_FIELDS>(query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>;
321
85
  };
86
+ /**
87
+ * Builders of an `AggregationQuery`: its elements, groups, metrics and the
88
+ * arithmetic expressions metrics compute over. Each builder checks its own
89
+ * part and throws a `TypeError` naming what is wrong; {@link aggregation.query}
90
+ * checks the parts against each other.
91
+ *
92
+ * Every group and metric takes its target first, its alias second, and any
93
+ * further options as a trailing object.
94
+ */
95
+ export declare const aggregation: typeof queryBuilders & typeof groupBuilders & typeof metricBuilders & typeof derivedBuilders & typeof havingBuilders;