@ahoo-wang/wow-client 10.0.0-alpha.5 → 10.0.0-alpha.7
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.
- package/README.md +76 -23
- package/README.zh-CN.md +66 -19
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +131 -61
- package/dist/commands.d.ts +131 -61
- package/dist/commands.es.js +117 -59
- package/dist/commands.es.js.map +1 -1
- package/dist/developmentCaller.cjs +2 -0
- package/dist/developmentCaller.cjs.map +1 -0
- package/dist/developmentCaller.d.cts +61 -0
- package/dist/developmentCaller.d.ts +61 -0
- package/dist/developmentCaller.es.js +26 -0
- package/dist/developmentCaller.es.js.map +1 -0
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +93 -93
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +20 -20
- package/dist/dsl/aggregation/builders.d.ts +20 -20
- package/dist/dsl/aggregation/builders.es.js +88 -88
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +8 -8
- package/dist/dsl/aggregation/derived.d.ts +8 -8
- package/dist/dsl/aggregation/derived.es.js +1 -2
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.cjs.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.es.js +1 -2
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.d.cts +12 -12
- package/dist/dsl/aggregation/having.d.ts +12 -12
- package/dist/dsl/aggregation/having.es.js +33 -33
- package/dist/dsl/aggregation/having.es.js.map +1 -1
- package/dist/dsl/aggregation/sort.cjs.map +1 -1
- package/dist/dsl/aggregation/sort.es.js +1 -2
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +69 -69
- package/dist/dsl/aggregation/types.d.ts +69 -69
- package/dist/dsl/aggregation/types.es.js +15 -16
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/constantName.cjs +2 -0
- package/dist/dsl/constantName.cjs.map +1 -0
- package/dist/dsl/constantName.d.cts +9 -0
- package/dist/dsl/constantName.d.ts +9 -0
- package/dist/dsl/constantName.es.js +7 -0
- package/dist/dsl/constantName.es.js.map +1 -0
- package/dist/dsl/cursorQuery.cjs.map +1 -1
- package/dist/dsl/cursorQuery.es.js +1 -2
- package/dist/dsl/deletionState.cjs +1 -1
- package/dist/dsl/deletionState.cjs.map +1 -1
- package/dist/dsl/deletionState.d.cts +3 -3
- package/dist/dsl/deletionState.d.ts +3 -3
- package/dist/dsl/deletionState.es.js +2 -3
- package/dist/dsl/deletionState.es.js.map +1 -1
- package/dist/dsl/descriptor.cjs +1 -1
- package/dist/dsl/descriptor.cjs.map +1 -1
- package/dist/dsl/descriptor.d.cts +92 -42
- package/dist/dsl/descriptor.d.ts +92 -42
- package/dist/dsl/descriptor.es.js +36 -29
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl/field.cjs.map +1 -1
- package/dist/dsl/field.es.js +1 -2
- package/dist/dsl/filter/builders.cjs +1 -1
- package/dist/dsl/filter/builders.cjs.map +1 -1
- package/dist/dsl/filter/builders.d.cts +53 -53
- package/dist/dsl/filter/builders.d.ts +53 -53
- package/dist/dsl/filter/builders.es.js +111 -111
- package/dist/dsl/filter/builders.es.js.map +1 -1
- package/dist/dsl/filter/datePattern.cjs.map +1 -1
- package/dist/dsl/filter/datePattern.es.js +1 -2
- package/dist/dsl/filter/operator.cjs +1 -1
- package/dist/dsl/filter/operator.cjs.map +1 -1
- package/dist/dsl/filter/operator.d.cts +57 -57
- package/dist/dsl/filter/operator.d.ts +57 -57
- package/dist/dsl/filter/operator.es.js +4 -5
- package/dist/dsl/filter/operator.es.js.map +1 -1
- package/dist/dsl/filter/scope.cjs +1 -1
- package/dist/dsl/filter/scope.cjs.map +1 -1
- package/dist/dsl/filter/scope.es.js +12 -12
- package/dist/dsl/filter/scope.es.js.map +1 -1
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.es.js +23 -23
- package/dist/dsl/filter/validate.es.js.map +1 -1
- package/dist/dsl/pagination.cjs.map +1 -1
- package/dist/dsl/pagination.es.js +1 -2
- package/dist/dsl/projection.cjs.map +1 -1
- package/dist/dsl/projection.d.cts +1 -1
- package/dist/dsl/projection.d.ts +1 -1
- package/dist/dsl/projection.es.js +1 -2
- package/dist/dsl/projection.es.js.map +1 -1
- package/dist/dsl/queryErrorCodes.cjs +1 -1
- package/dist/dsl/queryErrorCodes.cjs.map +1 -1
- package/dist/dsl/queryErrorCodes.d.cts +59 -48
- package/dist/dsl/queryErrorCodes.d.ts +59 -48
- package/dist/dsl/queryErrorCodes.es.js +51 -50
- package/dist/dsl/queryErrorCodes.es.js.map +1 -1
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.d.cts +25 -21
- package/dist/dsl/queryable.d.ts +25 -21
- package/dist/dsl/queryable.es.js +5 -5
- package/dist/dsl/queryable.es.js.map +1 -1
- package/dist/dsl/sort.cjs +1 -1
- package/dist/dsl/sort.cjs.map +1 -1
- package/dist/dsl/sort.d.cts +2 -2
- package/dist/dsl/sort.d.ts +2 -2
- package/dist/dsl/sort.es.js +4 -5
- package/dist/dsl/sort.es.js.map +1 -1
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.es.js +3 -3
- package/dist/exactJson.cjs.map +1 -1
- package/dist/exactJson.d.cts +4 -4
- package/dist/exactJson.d.ts +4 -4
- package/dist/exactJson.es.js +1 -2
- package/dist/exactJson.es.js.map +1 -1
- package/dist/frameworkErrors.cjs +2 -0
- package/dist/frameworkErrors.cjs.map +1 -0
- package/dist/frameworkErrors.d.cts +121 -0
- package/dist/frameworkErrors.d.ts +121 -0
- package/dist/frameworkErrors.es.js +95 -0
- package/dist/frameworkErrors.es.js.map +1 -0
- package/dist/http.cjs +1 -1
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +4 -7
- package/dist/http.d.ts +4 -7
- package/dist/http.es.js +12 -20
- package/dist/http.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -7
- package/dist/index.d.ts +9 -7
- package/dist/index.es.js +11 -9
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.d.cts +33 -95
- package/dist/manifest.d.ts +33 -95
- package/dist/manifest.es.js +12 -7
- package/dist/manifest.es.js.map +1 -1
- package/dist/manifestTypes.d.cts +193 -0
- package/dist/manifestTypes.d.ts +193 -0
- package/dist/problem.cjs +1 -1
- package/dist/problem.cjs.map +1 -1
- package/dist/problem.d.cts +76 -111
- package/dist/problem.d.ts +76 -111
- package/dist/problem.es.js +45 -78
- package/dist/problem.es.js.map +1 -1
- package/dist/queries.cjs +1 -1
- package/dist/queries.cjs.map +1 -1
- package/dist/queries.d.cts +28 -51
- package/dist/queries.d.ts +28 -51
- package/dist/queries.es.js +49 -40
- package/dist/queries.es.js.map +1 -1
- package/dist/routes.cjs +2 -0
- package/dist/routes.cjs.map +1 -0
- package/dist/routes.d.cts +49 -0
- package/dist/routes.d.ts +49 -0
- package/dist/routes.es.js +33 -0
- package/dist/routes.es.js.map +1 -0
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +56 -11
- package/dist/state.d.ts +56 -11
- package/dist/state.es.js +56 -21
- package/dist/state.es.js.map +1 -1
- package/dist/streams.cjs +1 -1
- package/dist/streams.cjs.map +1 -1
- package/dist/streams.d.cts +17 -13
- package/dist/streams.d.ts +17 -13
- package/dist/streams.es.js +50 -50
- package/dist/streams.es.js.map +1 -1
- package/dist/testing/wire.cjs +2 -0
- package/dist/testing/wire.cjs.map +1 -0
- package/dist/testing/wire.d.cts +29 -0
- package/dist/testing/wire.d.ts +29 -0
- package/dist/testing/wire.es.js +88 -0
- package/dist/testing/wire.es.js.map +1 -0
- package/dist/testing.cjs +1 -0
- package/dist/testing.d.cts +12 -0
- package/dist/testing.d.ts +12 -0
- package/dist/testing.es.js +3 -0
- package/dist/wait.cjs +1 -1
- package/dist/wait.cjs.map +1 -1
- package/dist/wait.d.cts +67 -18
- package/dist/wait.d.ts +67 -18
- package/dist/wait.es.js +59 -12
- package/dist/wait.es.js.map +1 -1
- package/dist/wire.cjs +1 -1
- package/dist/wire.cjs.map +1 -1
- package/dist/wire.d.cts +100 -50
- package/dist/wire.d.ts +100 -50
- package/dist/wire.es.js +17 -6
- package/dist/wire.es.js.map +1 -1
- package/package.json +26 -7
|
@@ -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","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 { 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 `${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 `${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 ${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 `${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 `${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 ${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 ${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,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AAZAjB,EAAoBE,GAASG,CAAO,GACpCK,EAAuBR,CAAO,GAC9B4B,EAAea,EAAM,QAAQtC,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,kBAAkBC,EAAM,KAAK,yBAC/B;CAEJ,CAAC;CAED,IAAMgC,IAAU,CACd,GAAGjC,EAAQ,KAAI,MAASC,EAAM,KAAK,GACnC,GAAGJ,EAAQ,KAAI,MAAUC,EAAO,KAAK,CACvC;CACA,IAAI,IAAI,IAAImC,CAAO,CAAC,CAAC,SAASA,EAAQ,QACpC,MAAU,UAAU,qCAAqC;CAK3D,OAHAJ,EAAaC,GAAM9B,GAASiC,CAAO,GAC/BS,EAAS,SAAS,KAAGN,EAAuBE,CAAK,GAE9C;EACL,GAAGA;EACH,SAAS,CAAC,GAAGzC,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 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,KA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ADAV,EAAc,WAAW,WAAWU,GAASgB,EAAmB,WAAW,GACvE0B,EAAM,UAAU,KAAA,MAEhB,CAAC,OAAO,UAAUA,EAAM,KAAK,KAC7BA,EAAM,QAAQ,KACdA,EAAM,QAAQ1B,EAAmB,YAEjC,MAAU,UACR,+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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./types.cjs"),
|
|
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;
|
|
2
2
|
//# sourceMappingURL=builders.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builders.cjs","names":["queryField","AggregationExpressionType","AggregationMetricType","AggregationGroupScope","DateDiffUnit","AggregationExpressionOperator","AggregationGroupType","AggregationDateUnit","AggregationDatePart","AggregationFunction","derivedExpressionDsl","havingDsl","admitAggregationQuery","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 { 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 `${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(`${type} group scope is invalid.`);\n }\n if (scope === AggregationGroupScope.ROOT && source.expression) {\n throw new TypeError(`${type} with a ROOT scope requires a field input.`);\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":"2MA8DA,SAASoB,EAAwC,EAAuB,CACtE,OAAOpB,EAAAA,WAAWqB,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,KAAMvB,EAAAA,0BAA0B,OAAQ,WAAU,OAAM,OAAM,CACzE,CAEA,SAASwB,EACP,EACA,EACA,EACA,CAAE,OAAQC,GAAgD,CAAC,EACzB,CAClC,MAAO,CACL,KAAMxB,EAAAA,sBAAsB,QAC5B,GAAIwB,IAAc,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQA,CAAU,EACvD,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AMxB,EAAAA,sBAAsB,eAC5B,aACA,MAAOoB,EAAiBC,CAAK,EAC7B,GAAIG,IAAc,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQA,CAAU,CACzD,CACF,EAaA,WACE,EACA,EACA,CAAE,aAAY,OAAQA,GACe,CACrC,GAAI,CAAC,OAAO,SAAS0B,CAAU,GAAKA,GAAc,GAAKA,GAAc,IACnE,MAAU,UAAU,gDAAgD,EAEtE,MAAO,CACL,KAAMlD,EAAAA,sBAAsB,WAC5B,aACA,aACA,MAAOoB,EAAiBC,CAAK,EAC7B,GAAIG,IAAc,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQA,CAAU,CACzD,CACF,EAkBA,QACE,EAEA,EAC0B,CAC1B,MAAO,CACL,KAAMxB,EAAAA,sBAAsB,QAC5B,WACE,OAAOiD,GAAe,WAClBA,EAAWzC,EAAAA,oBAAoB,EAC/ByC,EACN,MAAO7B,EAAiBC,CAAK,CAC/B,CACF,EAeA,OAAQZ,EAAAA,UAYR,MAIE,EACmD,CACnD,OAAOC,EAAAA,sBAAsByC,CAAK,CACpC,CACF"}
|
|
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,MAA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B,CAAO,EAEnE,UACE,EACA,EACA,IACGzB,EAAQjB,EAAAA,oBAAoB,SAAU2C,EAAY5B,EAAO2B,CAAO,EAUrE,cACE,EACA,EACA,CAAE,OAAQxB,GAAgD,CAAC,EACnB,CACxC,MAAO,CACL,KAAM1B,EAAAA,sBAAsB,eAC5B,aACA,MAAOsB,EAAiBC,CAAK,EAC7B,GAAIG,IAAc,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQA,CAAU,CACzD,CACF,EAaA,WACE,EACA,EACA,CAAE,aAAY,OAAQA,GACe,CACrC,GAAI,CAAC,OAAO,SAAS0B,CAAU,GAAKA,GAAc,GAAKA,GAAc,IACnE,MAAU,UAAU,gDAAgD,EAEtE,MAAO,CACL,KAAMpD,EAAAA,sBAAsB,WAC5B,aACA,aACA,MAAOsB,EAAiBC,CAAK,EAC7B,GAAIG,IAAc,IAAA,GAAY,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"}
|
|
@@ -28,7 +28,7 @@ export declare const aggregation: {
|
|
|
28
28
|
*/
|
|
29
29
|
element(path: string, predicate?: ElementFilterExpression | ExpressionFilter): AggregationElement;
|
|
30
30
|
/**
|
|
31
|
-
* The value of a field, as an operand. `{ type: '
|
|
31
|
+
* The value of a field, as an operand. `{ type: 'field', field }`.
|
|
32
32
|
*
|
|
33
33
|
* @throws TypeError when `field` is not a valid field path.
|
|
34
34
|
* @example
|
|
@@ -38,7 +38,7 @@ export declare const aggregation: {
|
|
|
38
38
|
*/
|
|
39
39
|
field<FIELDS extends string>(field: FIELDS): FieldAggregationExpression<FIELDS>;
|
|
40
40
|
/**
|
|
41
|
-
* A number, as an operand. `{ type: '
|
|
41
|
+
* A number, as an operand. `{ type: 'constant', value }`.
|
|
42
42
|
*
|
|
43
43
|
* @throws TypeError when `value` is not finite.
|
|
44
44
|
* @example
|
|
@@ -51,7 +51,7 @@ export declare const aggregation: {
|
|
|
51
51
|
* The time from the instant in `from` to the instant in `to`, `to − from`,
|
|
52
52
|
* in `unit`, as a signed decimal: negative when `to` is earlier, and no
|
|
53
53
|
* value when either instant is absent. A `DAY` is exactly 24 hours.
|
|
54
|
-
* `{ type: '
|
|
54
|
+
* `{ type: 'date-diff', from, to, unit }`. Both fields must be
|
|
55
55
|
* single-valued time fields, those whose `aggregate.groups` list
|
|
56
56
|
* `DATE_HISTOGRAM` in the descriptor, and `unit` one of its
|
|
57
57
|
* `analysis.dateDiffUnits`. Wow 9.2 and later.
|
|
@@ -68,18 +68,18 @@ export declare const aggregation: {
|
|
|
68
68
|
* ```
|
|
69
69
|
*/
|
|
70
70
|
dateDiff<FIELDS extends string>(from: FIELDS, to: FIELDS, unit: DateDiffUnit): DateDiffAggregationExpression<FIELDS>;
|
|
71
|
-
/** `left + right`. `{ type: '
|
|
71
|
+
/** `left + right`. `{ type: 'binary', operator: 'add', left, right }`. */
|
|
72
72
|
add: <FIELDS extends string>(left: AggregationExpression<FIELDS>, right: AggregationExpression<FIELDS>) => BinaryAggregationExpression<FIELDS>;
|
|
73
|
-
/** `left - right`. `{ type: '
|
|
73
|
+
/** `left - right`. `{ type: 'binary', operator: 'subtract', left, right }`. */
|
|
74
74
|
subtract: <FIELDS extends string>(left: AggregationExpression<FIELDS>, right: AggregationExpression<FIELDS>) => BinaryAggregationExpression<FIELDS>;
|
|
75
|
-
/** `left * right`. `{ type: '
|
|
75
|
+
/** `left * right`. `{ type: 'binary', operator: 'multiply', left, right }`. */
|
|
76
76
|
multiply: <FIELDS extends string>(left: AggregationExpression<FIELDS>, right: AggregationExpression<FIELDS>) => BinaryAggregationExpression<FIELDS>;
|
|
77
|
-
/** `left / right`. `{ type: '
|
|
77
|
+
/** `left / right`. `{ type: 'binary', operator: 'divide', left, right }`. */
|
|
78
78
|
divide: <FIELDS extends string>(left: AggregationExpression<FIELDS>, right: AggregationExpression<FIELDS>) => BinaryAggregationExpression<FIELDS>;
|
|
79
79
|
/**
|
|
80
80
|
* Groups by each distinct value of a field, or of a computed expression.
|
|
81
|
-
* `{ type: '
|
|
82
|
-
* `{ type: '
|
|
81
|
+
* `{ type: 'terms', field, alias, missingKey? }`, or
|
|
82
|
+
* `{ type: 'terms', expression, alias }`.
|
|
83
83
|
*
|
|
84
84
|
* @param input - The field to group by, or an expression in its place
|
|
85
85
|
* (Wow 9.2 and later, an expensive computation).
|
|
@@ -103,7 +103,7 @@ export declare const aggregation: {
|
|
|
103
103
|
terms<FIELDS extends string>(input: FIELDS | AggregationExpression<FIELDS>, alias: string, { missingKey, scope }?: TermsAggregationOptions): TermsAggregationGroup<FIELDS>;
|
|
104
104
|
/**
|
|
105
105
|
* Groups a number field, or a computed expression, into buckets of equal
|
|
106
|
-
* width. `{ type: '
|
|
106
|
+
* width. `{ type: 'histogram', field | expression, interval, alias }`.
|
|
107
107
|
*
|
|
108
108
|
* @param input - The number field to bucket, or an expression in its
|
|
109
109
|
* place (Wow 9.2 and later, an expensive computation).
|
|
@@ -122,7 +122,7 @@ export declare const aggregation: {
|
|
|
122
122
|
histogram<FIELDS extends string>(input: FIELDS | AggregationExpression<FIELDS>, alias: string, { interval, scope }: HistogramAggregationOptions): HistogramAggregationGroup<FIELDS>;
|
|
123
123
|
/**
|
|
124
124
|
* Groups a time field into calendar buckets.
|
|
125
|
-
* `{ type: '
|
|
125
|
+
* `{ type: 'date-histogram', field, unit, alias, timeZone, dense? }`.
|
|
126
126
|
*
|
|
127
127
|
* @param field - The time field (epoch milliseconds) to bucket.
|
|
128
128
|
* @param alias - The name of the bucket column in the result rows.
|
|
@@ -148,7 +148,7 @@ export declare const aggregation: {
|
|
|
148
148
|
/**
|
|
149
149
|
* Groups a time field by one calendar part of each instant, such as the
|
|
150
150
|
* weekday or the hour, so records from different days share a bucket.
|
|
151
|
-
* `{ type: '
|
|
151
|
+
* `{ type: 'date-part', field, part, alias, timeZone, dense? }`.
|
|
152
152
|
*
|
|
153
153
|
* The group's keys in the result rows are integers: `DAY_OF_WEEK` is the
|
|
154
154
|
* ISO weekday, 1 (Monday) to 7 (Sunday); `DAY_OF_MONTH` 1 to 31;
|
|
@@ -181,7 +181,7 @@ export declare const aggregation: {
|
|
|
181
181
|
datePart<FIELDS extends string>(field: FIELDS, alias: string, { part, timeZone, dense, scope }: DatePartAggregationOptions): DatePartAggregationGroup<FIELDS>;
|
|
182
182
|
/**
|
|
183
183
|
* Any one value of a field within each group, of any type.
|
|
184
|
-
* `{ type: '
|
|
184
|
+
* `{ type: 'any', field, alias, filter? }`.
|
|
185
185
|
*
|
|
186
186
|
* @throws TypeError when `field` or `alias` is invalid.
|
|
187
187
|
* @example
|
|
@@ -192,7 +192,7 @@ export declare const aggregation: {
|
|
|
192
192
|
any<FIELDS extends string>(field: FIELDS, alias: string, { filter: predicate }?: AggregationMetricOptions<FIELDS>): AnyAggregationMetric<FIELDS>;
|
|
193
193
|
/**
|
|
194
194
|
* The value of `field` on each group's earliest record by `orderBy`.
|
|
195
|
-
* `{ type: '
|
|
195
|
+
* `{ type: 'first', field, alias, orderBy?, filter? }`.
|
|
196
196
|
*
|
|
197
197
|
* The value comes back in the field's own type, or `null` when no record
|
|
198
198
|
* of the group has both a value and an `orderBy` position. Without
|
|
@@ -209,7 +209,7 @@ export declare const aggregation: {
|
|
|
209
209
|
first<FIELDS extends string>(field: FIELDS, alias: string, options?: EdgeAggregationOptions<FIELDS>): EdgeAggregationMetric<FIELDS>;
|
|
210
210
|
/**
|
|
211
211
|
* The value of `field` on each group's latest record by `orderBy`.
|
|
212
|
-
* `{ type: '
|
|
212
|
+
* `{ type: 'last', field, alias, orderBy?, filter? }`. As
|
|
213
213
|
* {@link aggregation.first}, from the other end.
|
|
214
214
|
*
|
|
215
215
|
* @throws TypeError when `field`, `orderBy` or `alias` is invalid.
|
|
@@ -220,7 +220,7 @@ export declare const aggregation: {
|
|
|
220
220
|
*/
|
|
221
221
|
last<FIELDS extends string>(field: FIELDS, alias: string, options?: EdgeAggregationOptions<FIELDS>): EdgeAggregationMetric<FIELDS>;
|
|
222
222
|
/**
|
|
223
|
-
* The number of rows in each group. `{ type: '
|
|
223
|
+
* The number of rows in each group. `{ type: 'count', alias, filter? }`.
|
|
224
224
|
*
|
|
225
225
|
* @param alias - The name of the metric column in the result rows.
|
|
226
226
|
* @param options.filter - Counts only the rows that match.
|
|
@@ -232,7 +232,7 @@ export declare const aggregation: {
|
|
|
232
232
|
*/
|
|
233
233
|
count<FIELDS extends string = string>(alias: string, { filter: predicate }?: AggregationMetricOptions<FIELDS>): CountAggregationMetric<FIELDS>;
|
|
234
234
|
/**
|
|
235
|
-
* The sum of an expression. `{ type: '
|
|
235
|
+
* The sum of an expression. `{ type: 'numeric', function: 'sum',
|
|
236
236
|
* expression, alias, filter? }`.
|
|
237
237
|
*
|
|
238
238
|
* @example
|
|
@@ -253,7 +253,7 @@ export declare const aggregation: {
|
|
|
253
253
|
variance: <FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, options?: AggregationMetricOptions<FIELDS>) => NumericAggregationMetric<FIELDS>;
|
|
254
254
|
/**
|
|
255
255
|
* The number of distinct values of an expression.
|
|
256
|
-
* `{ type: '
|
|
256
|
+
* `{ type: 'distinct-count', expression, alias, filter? }`.
|
|
257
257
|
*
|
|
258
258
|
* @example
|
|
259
259
|
* ```typescript
|
|
@@ -263,7 +263,7 @@ export declare const aggregation: {
|
|
|
263
263
|
distinctCount<FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, { filter: predicate }?: AggregationMetricOptions<FIELDS>): DistinctCountAggregationMetric<FIELDS>;
|
|
264
264
|
/**
|
|
265
265
|
* A percentile of an expression.
|
|
266
|
-
* `{ type: '
|
|
266
|
+
* `{ type: 'percentile', expression, percentile, alias, filter? }`.
|
|
267
267
|
*
|
|
268
268
|
* @param options.percentile - Which percentile, within (0, 100).
|
|
269
269
|
* @throws TypeError when `percentile` is not finite and within (0, 100), or
|
|
@@ -276,7 +276,7 @@ export declare const aggregation: {
|
|
|
276
276
|
percentile<FIELDS extends string>(expression: AggregationExpression<FIELDS>, alias: string, { percentile, filter: predicate }: PercentileAggregationOptions<FIELDS>): PercentileAggregationMetric<FIELDS>;
|
|
277
277
|
/**
|
|
278
278
|
* A metric computed from other metrics of the same row, by their aliases.
|
|
279
|
-
* `{ type: '
|
|
279
|
+
* `{ type: 'derived', expression, alias }`. `aggregation.query()` checks
|
|
280
280
|
* that it refers only to metrics declared before it.
|
|
281
281
|
*
|
|
282
282
|
* @param expression - The arithmetic: a callback that builds it from the
|