@hypequery/datasets 0.34.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/cache/protocol-cache-keys.d.ts.map +1 -1
  2. package/dist/cache/protocol-cache-keys.js +3 -65
  3. package/dist/client-contract/dataset-fields.d.ts.map +1 -1
  4. package/dist/client-contract/dataset-fields.js +2 -1
  5. package/dist/codegen/dataset-source.d.ts.map +1 -1
  6. package/dist/codegen/dataset-source.js +6 -0
  7. package/dist/execution-capabilities.d.ts +15 -3
  8. package/dist/execution-capabilities.d.ts.map +1 -1
  9. package/dist/execution-capabilities.js +4 -2
  10. package/dist/execution-capabilities.json +7 -8
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -0
  14. package/dist/protocol-adapter.js +2 -2
  15. package/dist/protocol-rehydrate.d.ts.map +1 -1
  16. package/dist/protocol-rehydrate.js +6 -8
  17. package/dist/semantic-planner.js +1 -1
  18. package/dist/semantic-query-schema.d.ts +18 -0
  19. package/dist/semantic-query-schema.d.ts.map +1 -1
  20. package/dist/semantic-query-schema.js +79 -55
  21. package/dist/tools.d.ts +6 -0
  22. package/dist/tools.d.ts.map +1 -1
  23. package/dist/types.d.ts +12 -3
  24. package/dist/types.d.ts.map +1 -1
  25. package/dist/utils/agent-catalog-projection.d.ts +0 -10
  26. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  27. package/dist/utils/agent-catalog-projection.js +13 -5
  28. package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
  29. package/dist/utils/dataset-definition-validation.js +5 -2
  30. package/dist/utils/dataset-validation.d.ts.map +1 -1
  31. package/dist/utils/dataset-validation.js +2 -1
  32. package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
  33. package/dist/utils/filtered-aggregation-sql.js +19 -1
  34. package/dist/utils/protocol-dataset-query.d.ts +19 -0
  35. package/dist/utils/protocol-dataset-query.d.ts.map +1 -0
  36. package/dist/utils/protocol-dataset-query.js +50 -0
  37. package/dist/utils/protocol-filter-nodes.d.ts +9 -0
  38. package/dist/utils/protocol-filter-nodes.d.ts.map +1 -0
  39. package/dist/utils/protocol-filter-nodes.js +68 -0
  40. package/dist/utils/protocol-metric-expressions.d.ts +9 -1
  41. package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
  42. package/dist/utils/protocol-metric-expressions.js +21 -1
  43. package/dist/utils/protocol-rehydrate-filters.d.ts +8 -1
  44. package/dist/utils/protocol-rehydrate-filters.d.ts.map +1 -1
  45. package/dist/utils/protocol-rehydrate-filters.js +18 -0
  46. package/dist/utils/protocol-rehydrate-time-keys.d.ts +2 -1
  47. package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -1
  48. package/dist/utils/protocol-rehydrate-time-keys.js +4 -2
  49. package/dist/utils/query-field-references.js +1 -1
  50. package/dist/utils/query-schema-calculations.d.ts +55 -0
  51. package/dist/utils/query-schema-calculations.d.ts.map +1 -0
  52. package/dist/utils/query-schema-calculations.js +150 -0
  53. package/dist/utils/query-schema-filters.d.ts +47 -0
  54. package/dist/utils/query-schema-filters.d.ts.map +1 -0
  55. package/dist/utils/query-schema-filters.js +132 -0
  56. package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
  57. package/dist/utils/relationship-measure-sql.js +2 -1
  58. package/dist/utils/relationship-measures.d.ts.map +1 -1
  59. package/dist/utils/relationship-measures.js +2 -1
  60. package/package.json +3 -3
@@ -0,0 +1,50 @@
1
+ import { protocolComparisonNode, protocolFilterNode } from './protocol-filter-nodes.js';
2
+ /**
3
+ * A dataset client query as an RFC 0003 dataset query envelope, the operation
4
+ * a semantic data plane validates (`validateProtocolSemanticQuery`) and runs.
5
+ *
6
+ * The inverse of what the portable runtime does with an operation it is
7
+ * handed: comparisons and `and`/`or`/`not` groups become `comparison` and
8
+ * `logical` predicates (RFC 0029), a filter calculation's `where` becomes
9
+ * comparisons (RFC 0026), and every other field is copied in document order.
10
+ * Nothing is dropped, so a field the receiving validator does not accept fails
11
+ * there rather than being silently ignored. A grain is the envelope's `by`.
12
+ *
13
+ * `inDateRange` is carried as written: the executor resolves it with its own
14
+ * clock and the query's timezone, never the caller's.
15
+ */
16
+ export function toProtocolDatasetQuery(dataset, query) {
17
+ const copy = (value) => (value === undefined ? undefined : structuredClone(value));
18
+ const entries = [
19
+ ['dimensions', copy(query.dimensions)],
20
+ ['measures', copy(query.measures)],
21
+ ['filters', query.filters?.map(protocolFilterNode)],
22
+ ['segments', copy(query.segments)],
23
+ ['calculations', query.calculations?.map(protocolCalculation)],
24
+ ['having', copy(query.having)],
25
+ ['limitBy', copy(query.limitBy)],
26
+ ['other', copy(query.other)],
27
+ ['orderBy', query.orderBy?.map(({ field, direction }) => ({ field, direction }))],
28
+ ['limit', query.limit],
29
+ ['offset', query.offset],
30
+ ['by', query.by],
31
+ ['timeKey', query.timeKey],
32
+ ['timezone', query.timezone],
33
+ ['fill', query.fill],
34
+ ['includeMeta', query.includeMeta],
35
+ ];
36
+ return {
37
+ kind: 'dataset',
38
+ dataset,
39
+ ...Object.fromEntries(entries.filter(([, value]) => value !== undefined)),
40
+ };
41
+ }
42
+ /** A calculation entry; only a filter calculation's `where` changes shape. */
43
+ function protocolCalculation(entry) {
44
+ if (!('filter' in entry) || entry.filter === undefined)
45
+ return structuredClone(entry);
46
+ return {
47
+ name: entry.name,
48
+ filter: { measure: entry.filter.measure, where: entry.filter.where.map(protocolComparisonNode) },
49
+ };
50
+ }
@@ -0,0 +1,9 @@
1
+ import type { DatasetFilterNode, MetricFilter } from '../types.js';
2
+ /** One comparison as a `comparison` node; a null check has no right operand (RFC 0023). */
3
+ export declare function protocolComparisonNode(filter: MetricFilter): Record<string, unknown>;
4
+ /**
5
+ * A caller filter as an RFC 0003 predicate: a group becomes a `logical` node
6
+ * (RFC 0029), a one-item group its item, since `and`/`or` take two or more.
7
+ */
8
+ export declare function protocolFilterNode(node: DatasetFilterNode): Record<string, unknown>;
9
+ //# sourceMappingURL=protocol-filter-nodes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol-filter-nodes.d.ts","sourceRoot":"","sources":["../../src/utils/protocol-filter-nodes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAgCnE,2FAA2F;AAC3F,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAoBpF;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CASnF"}
@@ -0,0 +1,68 @@
1
+ import { validateCanonicalValue } from '@hypequery/protocol';
2
+ import { isFilterGroup } from './filter-tree.js';
3
+ /**
4
+ * Dataset client filters as RFC 0003 predicates: the inverse of
5
+ * `operationFilter` in `portable-semantic-query.ts`.
6
+ */
7
+ function datetimeValue(value) {
8
+ return validateCanonicalValue({
9
+ $hypequery: {
10
+ type: 'datetime',
11
+ version: 1,
12
+ clickhouseType: 'DateTime64',
13
+ precision: 3,
14
+ timezone: 'UTC',
15
+ value: value.toISOString(),
16
+ },
17
+ });
18
+ }
19
+ /** A filter value as an RFC 0001 canonical value. Throws when it has none. */
20
+ function canonicalLiteral(value) {
21
+ if (value instanceof Date)
22
+ return datetimeValue(value);
23
+ if (Array.isArray(value)) {
24
+ return validateCanonicalValue({
25
+ $hypequery: { type: 'array', version: 1, values: value.map(canonicalLiteral) },
26
+ });
27
+ }
28
+ return validateCanonicalValue(value);
29
+ }
30
+ /** One comparison as a `comparison` node; a null check has no right operand (RFC 0023). */
31
+ export function protocolComparisonNode(filter) {
32
+ const left = { kind: 'reference', name: filter.field };
33
+ if (filter.operator === 'isNull' || filter.operator === 'isNotNull') {
34
+ return { kind: 'comparison', operator: filter.operator, left };
35
+ }
36
+ let literal;
37
+ if (filter.operator === 'between' && Array.isArray(filter.value)) {
38
+ // RFC 0003 bounds are a two-item tuple; in/notIn take an array.
39
+ literal = validateCanonicalValue({
40
+ $hypequery: { type: 'tuple', version: 1, values: filter.value.map(canonicalLiteral) },
41
+ });
42
+ }
43
+ else {
44
+ literal = canonicalLiteral(filter.value);
45
+ }
46
+ return {
47
+ kind: 'comparison',
48
+ operator: filter.operator,
49
+ left,
50
+ right: { kind: 'literal', value: literal },
51
+ };
52
+ }
53
+ /**
54
+ * A caller filter as an RFC 0003 predicate: a group becomes a `logical` node
55
+ * (RFC 0029), a one-item group its item, since `and`/`or` take two or more.
56
+ */
57
+ export function protocolFilterNode(node) {
58
+ if (!isFilterGroup(node))
59
+ return protocolComparisonNode(node);
60
+ if ('not' in node && node.not !== undefined) {
61
+ return { kind: 'logical', operator: 'not', operand: protocolFilterNode(node.not) };
62
+ }
63
+ const operator = 'and' in node && node.and !== undefined ? 'and' : 'or';
64
+ const items = (operator === 'and' ? node.and : node.or);
65
+ if (items.length === 1)
66
+ return protocolFilterNode(items[0]);
67
+ return { kind: 'logical', operator, operands: items.map(protocolFilterNode) };
68
+ }
@@ -1,6 +1,14 @@
1
1
  import { type ProtocolExpression, type ProtocolMetricDerivation } from '@hypequery/protocol';
2
- import type { AggregationSpec, DerivedMeasureDefinition, DerivedMetricSpec, MetricFilter } from '../types.js';
2
+ import type { AggregationSpec, DerivedMeasureDefinition, DerivedMetricSpec, MeasureFilterNode, MetricFilter } from '../types.js';
3
3
  export declare function filterExpression(filter: MetricFilter): ProtocolExpression;
4
+ /**
5
+ * A measure's fixed filter node as an RFC 0003 predicate: a comparison as
6
+ * `filterExpression` writes it, and an `and` / `or` / `not` group as the
7
+ * matching `logical` expression, in authored order. A one-item `and` or `or`
8
+ * means its item, and RFC 0003 requires two operands, so it publishes as the
9
+ * item; `renderMeasureFilterNode` renders it the same way.
10
+ */
11
+ export declare function measureFilterExpression(node: MeasureFilterNode): ProtocolExpression;
4
12
  /** The published form; aliases must satisfy the protocol identifier grammar. */
5
13
  export declare function derivedMeasureExpression(definition: DerivedMeasureDefinition): ProtocolExpression;
6
14
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"protocol-metric-expressions.d.ts","sourceRoot":"","sources":["../../src/utils/protocol-metric-expressions.ts"],"names":[],"mappings":"AAAA,OAAO,EAEgB,KAAK,kBAAkB,EAAE,KAAK,wBAAwB,EAC5E,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EAAE,eAAe,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAuC9G,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,YAAY,GAAG,kBAAkB,CAyBzE;AAsDD,gFAAgF;AAChF,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,wBAAwB,GAAG,kBAAkB,CAEjG;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAAC,UAAU,EAAE,wBAAwB,GAAG,kBAAkB,CAExG;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,eAAe,GAAG,iBAAiB,GAAG,kBAAkB,CAQ9F;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,iBAAiB,GAAG,wBAAwB,CASlF"}
1
+ {"version":3,"file":"protocol-metric-expressions.d.ts","sourceRoot":"","sources":["../../src/utils/protocol-metric-expressions.ts"],"names":[],"mappings":"AACA,OAAO,EAEgB,KAAK,kBAAkB,EAAE,KAAK,wBAAwB,EAC5E,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EAAE,eAAe,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAuCjI,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,YAAY,GAAG,kBAAkB,CAyBzE;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,iBAAiB,GAAG,kBAAkB,CASnF;AAsDD,gFAAgF;AAChF,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,wBAAwB,GAAG,kBAAkB,CAEjG;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAAC,UAAU,EAAE,wBAAwB,GAAG,kBAAkB,CAExG;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,eAAe,GAAG,iBAAiB,GAAG,kBAAkB,CAQ9F;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,iBAAiB,GAAG,wBAAwB,CASlF"}
@@ -1,3 +1,4 @@
1
+ import { isFilterGroup } from './filter-tree.js';
1
2
  import { parseProtocolIdentifier, parseProtocolQualifiedIdentifier, validateCanonicalValue, } from '@hypequery/protocol';
2
3
  import { requirePortableAggregation } from './portable-aggregations.js';
3
4
  function canonicalValue(input) {
@@ -55,6 +56,25 @@ export function filterExpression(filter) {
55
56
  };
56
57
  return result;
57
58
  }
59
+ /**
60
+ * A measure's fixed filter node as an RFC 0003 predicate: a comparison as
61
+ * `filterExpression` writes it, and an `and` / `or` / `not` group as the
62
+ * matching `logical` expression, in authored order. A one-item `and` or `or`
63
+ * means its item, and RFC 0003 requires two operands, so it publishes as the
64
+ * item; `renderMeasureFilterNode` renders it the same way.
65
+ */
66
+ export function measureFilterExpression(node) {
67
+ if (!isFilterGroup(node))
68
+ return filterExpression(node);
69
+ if ('not' in node && node.not !== undefined) {
70
+ return { kind: 'logical', operator: 'not', operand: measureFilterExpression(node.not) };
71
+ }
72
+ const operator = 'and' in node && node.and !== undefined ? 'and' : 'or';
73
+ const items = (operator === 'and' ? node.and : node.or) ?? [];
74
+ if (items.length === 1)
75
+ return measureFilterExpression(items[0]);
76
+ return { kind: 'logical', operator, operands: items.map(measureFilterExpression) };
77
+ }
58
78
  function aggregationExpression(spec) {
59
79
  const result = {
60
80
  kind: 'aggregate',
@@ -65,7 +85,7 @@ function aggregationExpression(spec) {
65
85
  : {}),
66
86
  ...(spec.level !== undefined ? { level: spec.level } : {}),
67
87
  ...(spec.filters?.length
68
- ? { filters: spec.filters.map(filterExpression) }
88
+ ? { filters: spec.filters.map(measureFilterExpression) }
69
89
  : {}),
70
90
  };
71
91
  return result;
@@ -1,5 +1,5 @@
1
1
  import type { ProtocolExpression } from '@hypequery/protocol';
2
- import type { MetricFilter } from '../types.js';
2
+ import type { MeasureFilterNode, MetricFilter } from '../types.js';
3
3
  /**
4
4
  * A measure's fixed filters cross the contract boundary as RFC 0003
5
5
  * expressions. `protocol-adapter.ts` only ever emits `reference <op> literal`
@@ -7,4 +7,11 @@ import type { MetricFilter } from '../types.js';
7
7
  * than partially interpreting an expression it cannot faithfully rebuild.
8
8
  */
9
9
  export declare function rehydrateMeasureFilter(expression: ProtocolExpression, unsupported: () => Error): MetricFilter;
10
+ /**
11
+ * A measure's fixed filter as the node it was authored as: a comparison, or a
12
+ * `logical` `and` / `or` / `not` of them as the matching group, in authored
13
+ * order, so the rebuilt measure renders the same SQL as the authored one.
14
+ * Anything else is refused, as `rehydrateMeasureFilter` refuses it.
15
+ */
16
+ export declare function rehydrateMeasureFilterNode(expression: ProtocolExpression, unsupported: () => Error, depth?: number): MeasureFilterNode;
10
17
  //# sourceMappingURL=protocol-rehydrate-filters.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"protocol-rehydrate-filters.d.ts","sourceRoot":"","sources":["../../src/utils/protocol-rehydrate-filters.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,UAAU,EAAE,kBAAkB,EAC9B,WAAW,EAAE,MAAM,KAAK,GACvB,YAAY,CAcd"}
1
+ {"version":3,"file":"protocol-rehydrate-filters.d.ts","sourceRoot":"","sources":["../../src/utils/protocol-rehydrate-filters.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGnE;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,UAAU,EAAE,kBAAkB,EAC9B,WAAW,EAAE,MAAM,KAAK,GACvB,YAAY,CAcd;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CACxC,UAAU,EAAE,kBAAkB,EAC9B,WAAW,EAAE,MAAM,KAAK,EACxB,KAAK,SAAI,GACR,iBAAiB,CAQnB"}
@@ -1,3 +1,4 @@
1
+ import { MAX_FILTER_GROUP_DEPTH } from './filter-tree.js';
1
2
  /**
2
3
  * A measure's fixed filters cross the contract boundary as RFC 0003
3
4
  * expressions. `protocol-adapter.ts` only ever emits `reference <op> literal`
@@ -22,6 +23,23 @@ export function rehydrateMeasureFilter(expression, unsupported) {
22
23
  value: fromCanonicalValue(right.value, unsupported),
23
24
  };
24
25
  }
26
+ /**
27
+ * A measure's fixed filter as the node it was authored as: a comparison, or a
28
+ * `logical` `and` / `or` / `not` of them as the matching group, in authored
29
+ * order, so the rebuilt measure renders the same SQL as the authored one.
30
+ * Anything else is refused, as `rehydrateMeasureFilter` refuses it.
31
+ */
32
+ export function rehydrateMeasureFilterNode(expression, unsupported, depth = 1) {
33
+ if (expression.kind !== 'logical')
34
+ return rehydrateMeasureFilter(expression, unsupported);
35
+ if (depth > MAX_FILTER_GROUP_DEPTH)
36
+ throw unsupported();
37
+ if (expression.operator === 'not') {
38
+ return { not: rehydrateMeasureFilterNode(expression.operand, unsupported, depth + 1) };
39
+ }
40
+ const items = expression.operands.map(operand => rehydrateMeasureFilterNode(operand, unsupported, depth + 1));
41
+ return expression.operator === 'and' ? { and: items } : { or: items };
42
+ }
25
43
  /**
26
44
  * Unwraps the RFC 0001 tagged value model back to the plain JavaScript value a
27
45
  * measure filter was authored with.
@@ -1,5 +1,6 @@
1
+ import { type ProtocolAnyVersionDataset } from '@hypequery/protocol';
1
2
  /** Contract 3 `alternateTimeFields` as the rehydrated dataset's `timeKeys` (RFC 0029). */
2
- export declare function alternateTimeKeys(contract: object): {
3
+ export declare function alternateTimeKeys(contract: ProtocolAnyVersionDataset): {
3
4
  timeKeys?: string[];
4
5
  };
5
6
  //# sourceMappingURL=protocol-rehydrate-time-keys.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"protocol-rehydrate-time-keys.d.ts","sourceRoot":"","sources":["../../src/utils/protocol-rehydrate-time-keys.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAG3E"}
1
+ {"version":3,"file":"protocol-rehydrate-time-keys.d.ts","sourceRoot":"","sources":["../../src/utils/protocol-rehydrate-time-keys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,KAAK,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAEtF,0FAA0F;AAC1F,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,yBAAyB,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAI9F"}
@@ -1,5 +1,7 @@
1
+ import { datasetTimeAxes } from '@hypequery/protocol';
1
2
  /** Contract 3 `alternateTimeFields` as the rehydrated dataset's `timeKeys` (RFC 0029). */
2
3
  export function alternateTimeKeys(contract) {
3
- const alternates = contract.alternateTimeFields;
4
- return alternates?.length ? { timeKeys: alternates.map(String) } : {};
4
+ // The default axis comes first; the rest are the alternates in authored order.
5
+ const alternates = datasetTimeAxes(contract).slice(1);
6
+ return alternates.length > 0 ? { timeKeys: alternates.map(String) } : {};
5
7
  }
@@ -31,7 +31,7 @@ export function queryFieldReferences(dataset, query) {
31
31
  const definition = dataset.measures[name];
32
32
  measureDependencies(definition).forEach(visit);
33
33
  if (isBaseMeasure(definition)) {
34
- names.push(...(definition.filters ?? []).map(filter => filterField(dataset, filter)));
34
+ names.push(...filterLeaves(definition.filters).map(filter => filterField(dataset, filter)));
35
35
  }
36
36
  };
37
37
  (query.measures ?? baseMeasureNames(dataset.measures)).forEach(visit);
@@ -0,0 +1,55 @@
1
+ import { z, type ZodTypeAny } from 'zod';
2
+ import type { DatasetQuery } from '../types.js';
3
+ export interface CalculationSchemaFields {
4
+ /** Groupable dimensions: what `rank.within`, `share.of` and `limitBy.by` may name. */
5
+ readonly dimensions: readonly string[];
6
+ /** Whether the dataset has a time axis, so `period` is a grouping key under a grain. */
7
+ readonly hasTime: boolean;
8
+ /** Base measures a filter calculation may condition. */
9
+ readonly filterMeasures: readonly string[];
10
+ /** Base and derived measures `other` may rank by. */
11
+ readonly bucketMeasures: readonly string[];
12
+ /** Local string dimensions `other` may bucket. */
13
+ readonly bucketDimensions: readonly string[];
14
+ /** Comparison shapes a filter calculation's `where` accepts. */
15
+ readonly whereVariants: readonly ZodTypeAny[];
16
+ /** Most calculation entries one query may carry. */
17
+ readonly maxCalculations?: number;
18
+ }
19
+ interface MeasureSource {
20
+ readonly measures: Readonly<Record<string, {
21
+ readonly aggregation?: string;
22
+ readonly kind?: string;
23
+ }>>;
24
+ readonly derivedMeasures?: Readonly<Record<string, unknown>>;
25
+ }
26
+ /**
27
+ * The measures a calculation may name by field: a filter calculation's base
28
+ * measure (local, neither window nor shift, and filterable), and what `other`
29
+ * ranks by (a base or derived measure).
30
+ */
31
+ export declare function calculationMeasures(source: MeasureSource): Pick<CalculationSchemaFields, 'filterMeasures' | 'bucketMeasures'>;
32
+ /** A simple identifier (RFC 0002): what a calculation is named. */
33
+ export declare function identifierSchema(): ZodTypeAny;
34
+ /**
35
+ * A measure or an earlier output. Its grammar and what it resolves to are the
36
+ * planner's to check, so the schema spends no bytes repeating the pattern.
37
+ */
38
+ export declare function referenceSchema(): ZodTypeAny;
39
+ /**
40
+ * `calculations`, `limitBy` and `other` for a dataset query. Each is left out
41
+ * when the dataset has nothing it could name, so no advertised option is one
42
+ * every call would fail.
43
+ */
44
+ export declare function calculationShape(fields: CalculationSchemaFields): Record<string, ZodTypeAny>;
45
+ /**
46
+ * `orderBy` and `having` may name a calculation output as well as a published
47
+ * field. Outputs are named by the query itself, so whether a name is one is
48
+ * checked here, against the calculations the call carries.
49
+ */
50
+ export declare function refineCalculationReferences(input: Pick<DatasetQuery, 'calculations' | 'orderBy' | 'having'>, published: {
51
+ readonly orderable: ReadonlySet<string>;
52
+ readonly measures: ReadonlySet<string>;
53
+ }, context: z.RefinementCtx): void;
54
+ export {};
55
+ //# sourceMappingURL=query-schema-calculations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-schema-calculations.d.ts","sourceRoot":"","sources":["../../src/utils/query-schema-calculations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,KAAK,UAAU,EAAE,MAAM,KAAK,CAAC;AAEzC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAoBhD,MAAM,WAAW,uBAAuB;IACtC,sFAAsF;IACtF,QAAQ,CAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,wFAAwF;IACxF,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,wDAAwD;IACxD,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,qDAAqD;IACrD,QAAQ,CAAC,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C,kDAAkD;IAClD,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7C,gEAAgE;IAChE,QAAQ,CAAC,aAAa,EAAE,SAAS,UAAU,EAAE,CAAC;IAC9C,oDAAoD;IACpD,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;CACnC;AAKD,UAAU,aAAa;IACrB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC,CAAC;IACvG,QAAQ,CAAC,eAAe,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC9D;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,aAAa,GACpB,IAAI,CAAC,uBAAuB,EAAE,gBAAgB,GAAG,gBAAgB,CAAC,CAMpE;AAED,mEAAmE;AACnE,wBAAgB,gBAAgB,IAAI,UAAU,CAE7C;AAED;;;GAGG;AACH,wBAAgB,eAAe,IAAI,UAAU,CAE5C;AA+DD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,uBAAuB,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAyB5F;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,IAAI,CAAC,YAAY,EAAE,cAAc,GAAG,SAAS,GAAG,QAAQ,CAAC,EAChE,SAAS,EAAE;IAAE,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;CAAE,EAC9F,OAAO,EAAE,CAAC,CAAC,aAAa,GACvB,IAAI,CAoBN"}
@@ -0,0 +1,150 @@
1
+ import { z } from 'zod';
2
+ import { SUPPORTED_TIME_GRAINS } from '../constants.js';
3
+ import { calculationOutputs } from './query-calculation-outputs.js';
4
+ import { fieldEnum } from './query-schema-filters.js';
5
+ /**
6
+ * Schemas for RFC 0026 query-scoped calculations, `limitBy` and `other` on a
7
+ * dataset query input. Field names stay enums of the dataset's fields; an
8
+ * input reference may also name an earlier entry's output, which the caller
9
+ * names, so it is an identifier and the planner checks what it resolves to.
10
+ */
11
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
12
+ const FORMULA_OPERATORS = [
13
+ 'add', 'subtract', 'multiply', 'divide', 'nullIfZero', 'coalesce', 'round', 'floor', 'ceil', 'percentChange',
14
+ ];
15
+ /** RFC 0026 ceilings: shift and trailing amounts, `other.n`, and the remainder label. */
16
+ const MAX_INTERVAL = 1000;
17
+ const MAX_OTHER = 1000;
18
+ const MAX_LABEL = 64;
19
+ /** Base aggregations a filter calculation cannot condition, as for model-level filtered measures. */
20
+ const UNFILTERABLE_AGGREGATIONS = new Set(['argMax', 'argMin', 'merge']);
21
+ /**
22
+ * The measures a calculation may name by field: a filter calculation's base
23
+ * measure (local, neither window nor shift, and filterable), and what `other`
24
+ * ranks by (a base or derived measure).
25
+ */
26
+ export function calculationMeasures(source) {
27
+ const base = Object.entries(source.measures).filter(([, entry]) => entry.kind === undefined && entry.aggregation !== undefined);
28
+ return {
29
+ filterMeasures: base.filter(([, entry]) => !UNFILTERABLE_AGGREGATIONS.has(entry.aggregation)).map(([name]) => name),
30
+ bucketMeasures: [...base.map(([name]) => name), ...Object.keys(source.derivedMeasures ?? {})],
31
+ };
32
+ }
33
+ /** A simple identifier (RFC 0002): what a calculation is named. */
34
+ export function identifierSchema() {
35
+ return z.string().regex(IDENTIFIER);
36
+ }
37
+ /**
38
+ * A measure or an earlier output. Its grammar and what it resolves to are the
39
+ * planner's to check, so the schema spends no bytes repeating the pattern.
40
+ */
41
+ export function referenceSchema() {
42
+ return z.string();
43
+ }
44
+ function union(schemas) {
45
+ return schemas.length === 1 ? schemas[0] : z.union(schemas);
46
+ }
47
+ /** Exactly one of `keys` is present on `value`. */
48
+ function exactlyOne(value, keys) {
49
+ return keys.filter(key => value[key] !== undefined).length === 1;
50
+ }
51
+ /**
52
+ * One entry: a `name` and exactly one kind member. A single object with every
53
+ * kind optional, rather than one object per kind, keeps `name` and the
54
+ * object's framing in the schema once; the "exactly one" rule is checked here.
55
+ */
56
+ function calculationEntry(fields) {
57
+ const reference = referenceSchema();
58
+ const unit = z.enum(SUPPORTED_TIME_GRAINS);
59
+ const amount = z.number().int().min(1).max(MAX_INTERVAL);
60
+ const partition = z.array(fieldEnum([...fields.dimensions, ...(fields.hasTime ? ['period'] : [])])).optional();
61
+ const formula = z.object({
62
+ op: z.enum(FORMULA_OPERATORS),
63
+ get args() { return z.array(z.union([reference, z.number().finite(), formula])).min(1).max(2); },
64
+ }).strict();
65
+ const windowModes = ['trailing', 'toDate', 'cumulative'];
66
+ const kinds = {
67
+ ...(fields.filterMeasures.length > 0 && fields.whereVariants.length > 0 ? {
68
+ filter: z.object({
69
+ measure: fieldEnum(fields.filterMeasures),
70
+ where: z.array(union(fields.whereVariants)).min(1),
71
+ }).strict(),
72
+ } : {}),
73
+ ...(fields.hasTime ? {
74
+ shift: z.object({ measure: reference, amount, unit }).strict(),
75
+ window: z.object({
76
+ measure: reference,
77
+ trailing: z.object({ amount, unit }).strict().optional(),
78
+ toDate: z.enum(SUPPORTED_TIME_GRAINS.filter(grain => grain !== 'minute')).optional(),
79
+ cumulative: z.literal(true).optional(),
80
+ }).strict().refine(window => exactlyOne(window, windowModes), 'Use exactly one of trailing, toDate or cumulative.').describe('Exactly one of trailing, toDate or cumulative.'),
81
+ compare: z.object({
82
+ to: z.enum(['previousPeriod', 'previousYear']),
83
+ measures: z.array(reference).min(1),
84
+ }).strict(),
85
+ } : {}),
86
+ formula,
87
+ rank: z.object({ measure: reference, within: partition, direction: z.enum(['asc', 'desc']).optional() }).strict(),
88
+ share: z.object({ measure: reference, of: partition }).strict(),
89
+ };
90
+ const names = Object.keys(kinds);
91
+ return z.object({
92
+ name: identifierSchema(),
93
+ ...Object.fromEntries(Object.entries(kinds).map(([kind, schema]) => [kind, schema.optional()])),
94
+ }).strict().refine(value => exactlyOne(value, names), `Give each calculation exactly one of ${names.join(', ')}.`);
95
+ }
96
+ /**
97
+ * `calculations`, `limitBy` and `other` for a dataset query. Each is left out
98
+ * when the dataset has nothing it could name, so no advertised option is one
99
+ * every call would fail.
100
+ */
101
+ export function calculationShape(fields) {
102
+ const groupKeys = [...fields.dimensions, ...(fields.hasTime ? ['period'] : [])];
103
+ const calculations = z.array(calculationEntry(fields));
104
+ return {
105
+ calculations: (fields.maxCalculations === undefined ? calculations : calculations.max(fields.maxCalculations))
106
+ .optional()
107
+ .describe('Each is a name and exactly one kind. Inputs name a selected measure or an earlier output; '
108
+ + 'shift, window and compare need grain and a time range filter. Outputs can be ordered by and used in having.'),
109
+ ...(groupKeys.length > 0 ? {
110
+ limitBy: z.object({
111
+ n: z.number().int().positive(),
112
+ by: z.array(fieldEnum(groupKeys)).min(1),
113
+ }).strict().optional().describe('Keep the first n rows of each by group, in orderBy order (orderBy required).'),
114
+ } : {}),
115
+ ...(fields.bucketDimensions.length > 0 && fields.bucketMeasures.length > 0 ? {
116
+ other: z.object({
117
+ dimension: fieldEnum(fields.bucketDimensions),
118
+ n: z.number().int().min(1).max(MAX_OTHER),
119
+ measure: fieldEnum(fields.bucketMeasures),
120
+ label: z.string().min(1).max(MAX_LABEL).optional(),
121
+ }).strict().optional().describe('Keep the top n values of a selected dimension by measure; group the rest under label (default "Other").'),
122
+ } : {}),
123
+ };
124
+ }
125
+ /**
126
+ * `orderBy` and `having` may name a calculation output as well as a published
127
+ * field. Outputs are named by the query itself, so whether a name is one is
128
+ * checked here, against the calculations the call carries.
129
+ */
130
+ export function refineCalculationReferences(input, published, context) {
131
+ const outputs = new Set(calculationOutputs(input).map(output => output.name));
132
+ input.orderBy?.forEach((order, index) => {
133
+ if (!published.orderable.has(order.field) && !outputs.has(order.field)) {
134
+ context.addIssue({
135
+ code: 'custom',
136
+ path: ['orderBy', index, 'field'],
137
+ message: 'Not a field this dataset can order by, or an output of this query\'s calculations.',
138
+ });
139
+ }
140
+ });
141
+ input.having?.forEach((condition, index) => {
142
+ if (!published.measures.has(condition.measure) && !outputs.has(condition.measure)) {
143
+ context.addIssue({
144
+ code: 'custom',
145
+ path: ['having', index, 'measure'],
146
+ message: 'Not a measure of this dataset, or an output of this query\'s calculations.',
147
+ });
148
+ }
149
+ });
150
+ }
@@ -0,0 +1,47 @@
1
+ import { type ZodTypeAny } from 'zod';
2
+ import type { FilterPolicy } from './effective-filters.js';
3
+ /** Every relative range of the RFC 0029 grammar without a count. */
4
+ export declare const RELATIVE_DATE_RANGES: readonly string[];
5
+ export interface FilterLeafOptions {
6
+ /**
7
+ * One comparison shape per distinct operator set rather than per field,
8
+ * with the fields as an enum. Accepts exactly the same filters in fewer
9
+ * bytes; off where existing schemas must stay byte-identical.
10
+ */
11
+ readonly compact?: boolean;
12
+ /** Fields that also accept `inDateRange` with a relative range value. */
13
+ readonly relativeDateFields?: readonly string[];
14
+ }
15
+ export declare function fieldEnum(values: readonly string[]): ZodTypeAny;
16
+ /** The RFC 0029 relative range grammar: the fixed forms as an enum, `last N units` as a pattern. */
17
+ export declare function relativeDateRangeSchema(): ZodTypeAny;
18
+ /** Comparison variants: a value form and, where allowed, a value-free null check (RFC 0023). */
19
+ export declare function filterLeafVariants(localFilters: Readonly<Record<string, FilterPolicy>>, fields: readonly string[], relationshipOperators: ReadonlyMap<string, string[]>, options?: FilterLeafOptions): ZodTypeAny[];
20
+ /** The schema of one top-level `filters` item. */
21
+ export declare function filterItemSchema(variants: readonly ZodTypeAny[], options?: {
22
+ readonly groups?: boolean;
23
+ }): ZodTypeAny;
24
+ interface TimeAxisSource {
25
+ readonly name?: string;
26
+ readonly timeKey?: string;
27
+ readonly timeKeys?: readonly string[];
28
+ readonly dimensions: Readonly<Record<string, {
29
+ readonly column?: string;
30
+ readonly type?: string;
31
+ }>>;
32
+ }
33
+ /** Whether a local filter reads a timestamp dimension, through its own name or an alias. */
34
+ export declare function isTimestampFilter(source: TimeAxisSource, localFilters: Readonly<Record<string, FilterPolicy>>, field: string): boolean;
35
+ /**
36
+ * Whether a local filter compares one of the dataset's time axes. Compared by
37
+ * backing column, as the planner reads the axis: a filter or a `timeKey` may
38
+ * name a column that a differently named dimension reads.
39
+ */
40
+ export declare function isTimeAxisFilter(source: TimeAxisSource, localFilters: Readonly<Record<string, FilterPolicy>>, field: string): boolean;
41
+ /**
42
+ * The filters that compare a time axis and allow both `gte` and `lt`, the
43
+ * effective operators of `inDateRange`.
44
+ */
45
+ export declare function relativeDateFilterFields(source: TimeAxisSource, localFilters: Readonly<Record<string, FilterPolicy>>, fields: readonly string[]): string[];
46
+ export {};
47
+ //# sourceMappingURL=query-schema-filters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-schema-filters.d.ts","sourceRoot":"","sources":["../../src/utils/query-schema-filters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAK,KAAK,UAAU,EAAE,MAAM,KAAK,CAAC;AAIzC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAU3D,oEAAoE;AACpE,eAAO,MAAM,oBAAoB,mBAQ/B,CAAC;AAKH,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,yEAAyE;IACzE,QAAQ,CAAC,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACjD;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,UAAU,CAK/D;AAED,oGAAoG;AACpG,wBAAgB,uBAAuB,IAAI,UAAU,CAKpD;AAYD,gGAAgG;AAChG,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,EACpD,MAAM,EAAE,SAAS,MAAM,EAAE,EACzB,qBAAqB,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,EACpD,OAAO,GAAE,iBAAsB,GAC9B,UAAU,EAAE,CAkCd;AAED,kDAAkD;AAClD,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,SAAS,UAAU,EAAE,EAC/B,OAAO,GAAE;IAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAO,GAC1C,UAAU,CA2BZ;AAED,UAAU,cAAc;IACtB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC,CAAC;CACrG;AAED,4FAA4F;AAC5F,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,EACpD,KAAK,EAAE,MAAM,GACZ,OAAO,CAGT;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,EACpD,KAAK,EAAE,MAAM,GACZ,OAAO,CAKT;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,EACpD,MAAM,EAAE,SAAS,MAAM,EAAE,GACxB,MAAM,EAAE,CAMV"}