briyah 2.0.8 → 2.0.9

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.
@@ -103,6 +103,24 @@ export declare class BaseAiService {
103
103
  * @returns Promise with model information
104
104
  */
105
105
  listModels(): Promise<ModelInfo[]>;
106
+ /**
107
+ * Drops the models {@link createAgent} would refuse, so the picker only offers
108
+ * models that can actually be used.
109
+ *
110
+ * A provider API lists everything it hosts — embeddings, speech, video, music,
111
+ * retired preview ids — but an agent can only be built for a model that has a
112
+ * pricing entry, because cost tracking and balance gating have nothing to charge
113
+ * without one. Sharing {@link isKnownModel} with the creation gate is what keeps
114
+ * the two from drifting apart; filtering on any other rule would reopen the gap.
115
+ *
116
+ * Services exempt from that gate (`requiresKnownModel() === false`) are returned
117
+ * unchanged, since their models are self-hosted or free and never appear in
118
+ * model_prices.json.
119
+ *
120
+ * @param models The models the provider API returned
121
+ * @returns The usable subset, or `models` unchanged for an exempt service
122
+ */
123
+ protected withoutUnpricedModels(models: ModelInfo[]): ModelInfo[];
106
124
  /**
107
125
  * Actual implementation to fetch models from the API
108
126
  * This should be overridden by subclasses
@@ -251,14 +251,47 @@ let BaseAiService = class BaseAiService {
251
251
  try {
252
252
  const models = await this.fetchModelsFromApi();
253
253
  // Cache the result for future calls
254
- this.modelsCache = models;
255
- return models;
254
+ this.modelsCache = this.withoutUnpricedModels(models);
255
+ return this.modelsCache;
256
256
  }
257
257
  catch (error) {
258
258
  logger_1.logger.error(`Error fetching models for ${this.getServiceName()}:`, error);
259
259
  throw error;
260
260
  }
261
261
  }
262
+ /**
263
+ * Drops the models {@link createAgent} would refuse, so the picker only offers
264
+ * models that can actually be used.
265
+ *
266
+ * A provider API lists everything it hosts — embeddings, speech, video, music,
267
+ * retired preview ids — but an agent can only be built for a model that has a
268
+ * pricing entry, because cost tracking and balance gating have nothing to charge
269
+ * without one. Sharing {@link isKnownModel} with the creation gate is what keeps
270
+ * the two from drifting apart; filtering on any other rule would reopen the gap.
271
+ *
272
+ * Services exempt from that gate (`requiresKnownModel() === false`) are returned
273
+ * unchanged, since their models are self-hosted or free and never appear in
274
+ * model_prices.json.
275
+ *
276
+ * @param models The models the provider API returned
277
+ * @returns The usable subset, or `models` unchanged for an exempt service
278
+ */
279
+ withoutUnpricedModels(models) {
280
+ if (!this.requiresKnownModel() || !Array.isArray(models))
281
+ return models;
282
+ const prefix = this.getModelPricePrefix();
283
+ const usable = models.filter((model) => (0, model_prices_1.isKnownModel)(model.model, prefix));
284
+ const hidden = models.length - usable.length;
285
+ if (hidden > 0) {
286
+ logger_1.logger.debug(`${this.getServiceName()}: hiding ${hidden} of ${models.length} models with no model_prices.json entry`);
287
+ }
288
+ // An empty picker looks the same as a dead provider in the UI, so name the
289
+ // cause while the pricing table is still the thing to go and look at.
290
+ if (models.length > 0 && usable.length === 0) {
291
+ logger_1.logger.warn(`${this.getServiceName()}: none of its ${models.length} models have a model_prices.json entry; the model picker will be empty`);
292
+ }
293
+ return usable;
294
+ }
262
295
  /**
263
296
  * Actual implementation to fetch models from the API
264
297
  * This should be overridden by subclasses
@@ -1,6 +1,7 @@
1
1
  /**
2
- * The pricing table: the bundled one, with the host's {@link LOCAL_PRICES_FILE}
3
- * merged over it.
2
+ * The pricing table, in three layers: the vendored one, our own
3
+ * {@link ANNOTATIONS_FILE} fields merged into the entries they name, and the
4
+ * host's {@link LOCAL_PRICES_FILE} merged over both.
4
5
  *
5
6
  * A shallow merge keyed by model name, so an overlay entry replaces a bundled one
6
7
  * outright rather than being merged field by field. Half an entry is worse than
@@ -56,6 +56,23 @@ const logger_1 = require("../common/logger");
56
56
  * accident to guard against — negotiated pricing has nowhere else to live.
57
57
  */
58
58
  const LOCAL_PRICES_FILE = 'model_prices.local.json';
59
+ /**
60
+ * Briyah's own capability facts about models in the bundled table.
61
+ *
62
+ * Some things we need to know are not in litellm's table and never will be --
63
+ * `supports_web_search_filtering` says whether Anthropic accepts the newer
64
+ * `web_search_20260209` server tool, which only our own request builder cares
65
+ * about. Annotating `model_prices.json` in place was the obvious home and the
66
+ * wrong one: `update-model-prices.js` writes the fetched bytes verbatim, so every
67
+ * refresh wipes the annotation and nothing says so.
68
+ *
69
+ * Kept here, the vendored table stays a byte-for-byte copy and these survive by
70
+ * construction. Merged **field by field** over the entry they name, unlike
71
+ * {@link LOCAL_PRICES_FILE}, which replaces an entry whole: an annotation adds a
72
+ * fact to a vendored entry rather than restating it, so merging any other way
73
+ * would mean copying prices here to keep them.
74
+ */
75
+ const ANNOTATIONS_FILE = 'model_prices.annotations.json';
59
76
  // Lazy-loaded so that BRIYAH_DATA_PATH is read at first use, not at import time.
60
77
  let _modelPrices = null;
61
78
  let _imageModels = null;
@@ -105,8 +122,38 @@ function getImageModels() {
105
122
  return _imageModels;
106
123
  }
107
124
  /**
108
- * The pricing table: the bundled one, with the host's {@link LOCAL_PRICES_FILE}
109
- * merged over it.
125
+ * Adds {@link ANNOTATIONS_FILE} fields to the bundled entries they name.
126
+ *
127
+ * An annotation only ever decorates an entry that already exists. A name the
128
+ * table does not have is skipped rather than created, because an entry holding a
129
+ * capability flag and no prices would read as a known model to `isKnownModel` and
130
+ * let an agent be built for it -- costing every call at zero, which is the exact
131
+ * thing the pricing gate exists to prevent. It warns, since the usual cause is a
132
+ * model retired upstream and the annotation outliving it.
133
+ *
134
+ * @param bundled The vendored table
135
+ * @param annotations The annotations file contents
136
+ * @returns A copy of `bundled` with the annotated fields applied
137
+ */
138
+ function applyAnnotations(bundled, annotations) {
139
+ const merged = { ...bundled };
140
+ for (const [modelName, fields] of Object.entries(annotations)) {
141
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
142
+ logger_1.logger.warn(`Ignoring ${ANNOTATIONS_FILE} entry "${modelName}": expected an object of fields`);
143
+ continue;
144
+ }
145
+ if (!merged[modelName]) {
146
+ logger_1.logger.warn(`${ANNOTATIONS_FILE} annotates "${modelName}", which is not in model_prices.json`);
147
+ continue;
148
+ }
149
+ merged[modelName] = { ...merged[modelName], ...fields };
150
+ }
151
+ return merged;
152
+ }
153
+ /**
154
+ * The pricing table, in three layers: the vendored one, our own
155
+ * {@link ANNOTATIONS_FILE} fields merged into the entries they name, and the
156
+ * host's {@link LOCAL_PRICES_FILE} merged over both.
110
157
  *
111
158
  * A shallow merge keyed by model name, so an overlay entry replaces a bundled one
112
159
  * outright rather than being merged field by field. Half an entry is worse than
@@ -140,7 +187,10 @@ function getModelPrices() {
140
187
  if (localCount > 0) {
141
188
  logger_1.logger.log(`Applied ${localCount} model price entr${localCount === 1 ? 'y' : 'ies'} from ${LOCAL_PRICES_FILE}`);
142
189
  }
143
- _modelPrices = { ...bundled, ...local };
190
+ const annotated = applyAnnotations(bundled, readOptionalJsonObject(path.join(configDir, ANNOTATIONS_FILE)));
191
+ // The host overlay goes on last so it still wins: it replaces an entry whole,
192
+ // annotations and all, which is what makes it an override rather than a layer.
193
+ _modelPrices = { ...annotated, ...local };
144
194
  return _modelPrices;
145
195
  }
146
196
  /**
@@ -25,6 +25,23 @@ function buildDataGuideMarkdown() {
25
25
  '',
26
26
  'A query with no `groupBy` and no `metrics` lists rows. With either, it',
27
27
  'aggregates: `groupBy` gives the dimensions, `metrics` the numbers.',
28
+ '`count` counts rows (with a field, the rows where it is present);',
29
+ '`countDistinct` counts a field\'s different values.',
30
+ '',
31
+ 'To keep only some groups, add `having`: conditions on your own metrics,',
32
+ 'applied after grouping, each naming a metric by its `as`. Groups with more',
33
+ 'than five rows:',
34
+ '',
35
+ '```json',
36
+ '{"dataset": "markets", "groupBy": ["mga"],',
37
+ ' "metrics": [{"fn": "count", "as": "markets"}],',
38
+ ' "having": [{"field": "markets", "op": "gt", "value": 5}]}',
39
+ '```',
40
+ '',
41
+ 'A **list** field holds several values on one row. Filter it with `has`',
42
+ '(holds this value), `hasAny` (holds one of these), `contains` (a member',
43
+ 'contains this text), `isEmpty` or `notEmpty`. A list cannot be grouped or',
44
+ 'aggregated.',
28
45
  '',
29
46
  '**Only what is listed here exists.** A field that is not on a dataset cannot',
30
47
  'be filtered, grouped or summed, and two datasets can only be related if a',
@@ -69,7 +86,7 @@ function describeDataset(set, heading) {
69
86
  /** One field line: what it is, and what may be done with it. */
70
87
  function describeField(field) {
71
88
  const parts = [`\`${field.name}\` (${field.type}`];
72
- if (field.type === 'enum' && field.enumValues?.length) {
89
+ if ((field.type === 'enum' || field.type === 'list') && field.enumValues?.length) {
73
90
  parts.push(`: ${field.enumValues.join(' | ')}`);
74
91
  }
75
92
  parts.push(')');
@@ -15,10 +15,24 @@
15
15
  * or sanitize anything a model wrote. That is what makes it safe to run against
16
16
  * a database with no read-only role behind it.
17
17
  */
18
- /** What kind of value a field holds, and therefore how it may be compared. */
19
- export type DataFieldType = 'string' | 'number' | 'boolean' | 'date' | 'enum';
20
- /** The aggregate functions a query may ask for. */
21
- export type DataAggregateFn = 'count' | 'sum' | 'avg' | 'min' | 'max';
18
+ /**
19
+ * What kind of value a field holds, and therefore how it may be compared.
20
+ *
21
+ * `list` is a set of strings on one row — the states a market is licensed in,
22
+ * the coverage lines it writes. It is filtered by membership (`has`, `hasAny`,
23
+ * `contains`, `isEmpty`, `notEmpty`) and can be neither grouped nor
24
+ * aggregated: grouping by a set has no single answer, and the set's members are
25
+ * better asked about as rows of their own dataset when they need counting.
26
+ */
27
+ export type DataFieldType = 'string' | 'number' | 'boolean' | 'date' | 'enum' | 'list';
28
+ /**
29
+ * The aggregate functions a query may ask for.
30
+ *
31
+ * `count` with no field counts rows; with a field it counts the rows where that
32
+ * field is present. `countDistinct` counts the field's different values — "how
33
+ * many carriers", where one carrier appears on several rows.
34
+ */
35
+ export type DataAggregateFn = 'count' | 'countDistinct' | 'sum' | 'avg' | 'min' | 'max';
22
36
  /**
23
37
  * How a filter compares a field to a value.
24
38
  *
@@ -26,7 +40,15 @@ export type DataAggregateFn = 'count' | 'sum' | 'avg' | 'min' | 'max';
26
40
  * and nothing here can express a subquery, a join the host did not declare, or
27
41
  * a raw expression.
28
42
  */
29
- export type DataFilterOp = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'contains' | 'between' | 'isNull' | 'notNull';
43
+ export type DataFilterOp = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'contains' | 'between' | 'isNull' | 'notNull'
44
+ /** A `list` field holds this value. */
45
+ | 'has'
46
+ /** A `list` field holds at least one of these values. */
47
+ | 'hasAny'
48
+ /** A `list` field holds nothing. */
49
+ | 'isEmpty'
50
+ /** A `list` field holds something. */
51
+ | 'notEmpty';
30
52
  /**
31
53
  * One queryable field.
32
54
  *
@@ -44,7 +66,10 @@ export interface DataField {
44
66
  label?: string;
45
67
  /** What the field means, and anything an agent would otherwise assume wrongly. */
46
68
  description?: string;
47
- /** For `enum`, the values it may hold. Rendered into the guide and enforced. */
69
+ /**
70
+ * For `enum`, the values it may hold; for `list`, the values its members may
71
+ * be. Rendered into the guide and enforced on every filter value.
72
+ */
48
73
  enumValues?: string[];
49
74
  /** May appear in `filters`. Default true. */
50
75
  filterable?: boolean;
@@ -82,9 +107,24 @@ export interface DataSet {
82
107
  export interface DataFilter {
83
108
  field: string;
84
109
  op: DataFilterOp;
85
- /** Omitted for `isNull`/`notNull`; an array for `in` and `between`. */
110
+ /**
111
+ * Omitted for `isNull`/`notNull`/`isEmpty`/`notEmpty`; an array for `in`,
112
+ * `hasAny` and `between`.
113
+ */
86
114
  value?: any;
87
115
  }
116
+ /**
117
+ * One comparison on an aggregate's result — SQL's HAVING. `field` names a
118
+ * metric by its `as` name: "MGAs with more than five markets" is markets
119
+ * grouped by MGA, counted, and kept where the count is over five.
120
+ */
121
+ export interface DataHaving {
122
+ /** A metric's `as` name. */
123
+ field: string;
124
+ op: 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'between';
125
+ /** A number, or `[low, high]` for `between`. */
126
+ value: any;
127
+ }
88
128
  /** One aggregate in a query. */
89
129
  export interface DataMetric {
90
130
  fn: DataAggregateFn;
@@ -111,6 +151,11 @@ export interface DataQuery {
111
151
  filters?: DataFilter[];
112
152
  groupBy?: string[];
113
153
  metrics?: DataMetric[];
154
+ /**
155
+ * Conditions on the metrics, applied after grouping. Only on an aggregate,
156
+ * and only naming a metric of this query.
157
+ */
158
+ having?: DataHaving[];
114
159
  /** Fields to return when this is a listing rather than an aggregate. */
115
160
  select?: string[];
116
161
  orderBy?: DataOrder[];
@@ -26,11 +26,20 @@ const OPS_BY_TYPE = {
26
26
  string: ['eq', 'ne', 'in', 'contains', 'isNull', 'notNull'],
27
27
  enum: ['eq', 'ne', 'in', 'isNull', 'notNull'],
28
28
  boolean: ['eq', 'ne', 'isNull', 'notNull'],
29
+ list: ['has', 'hasAny', 'contains', 'isEmpty', 'notEmpty'],
29
30
  };
30
31
  /** Operators that take no value at all. */
31
- const VALUELESS_OPS = ['isNull', 'notNull'];
32
+ const VALUELESS_OPS = ['isNull', 'notNull', 'isEmpty', 'notEmpty'];
33
+ /** Operators that take a list of values. */
34
+ const LIST_VALUE_OPS = ['in', 'hasAny'];
35
+ /** Every aggregate, in the order a refusal lists them. */
36
+ const AGGREGATES = ['count', 'countDistinct', 'sum', 'avg', 'min', 'max'];
32
37
  /** Aggregates that need a numeric or date field to mean anything. */
33
38
  const NUMERIC_AGGREGATES = ['sum', 'avg'];
39
+ /** How a `having` may compare a metric. */
40
+ const HAVING_OPS = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'between'];
41
+ /** Aggregates whose result is always a number, so a `having` on one needs a number. */
42
+ const NUMBER_RESULT_AGGREGATES = ['count', 'countDistinct', 'sum', 'avg'];
34
43
  function fail(error, available) {
35
44
  return available ? { ok: false, error, available } : { ok: false, error };
36
45
  }
@@ -76,8 +85,12 @@ function validateQuery(raw, sets) {
76
85
  if (!field) {
77
86
  return fail(`Cannot group by "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
78
87
  }
79
- if (field.groupable === false) {
80
- return fail(`Cannot group by "${name}". Groupable fields:`, set.fields.filter((f) => f.groupable !== false).map((f) => f.name));
88
+ // A list holds several values on one row, so grouping by it has no
89
+ // single answer; its members are filtered, not grouped.
90
+ if (field.groupable === false || field.type === 'list') {
91
+ return fail(field.type === 'list'
92
+ ? `Cannot group by "${name}" — it is a list, so one row holds several values. Filter it with has or hasAny instead. Groupable fields:`
93
+ : `Cannot group by "${name}". Groupable fields:`, set.fields.filter((f) => f.groupable !== false && f.type !== 'list').map((f) => f.name));
81
94
  }
82
95
  groupBy.push(field.name);
83
96
  }
@@ -115,6 +128,14 @@ function validateQuery(raw, sets) {
115
128
  }
116
129
  orderBy.push({ by, dir: dir });
117
130
  }
131
+ const having = [];
132
+ for (const rawHaving of asArray(raw.having)) {
133
+ const checked = validateHaving(rawHaving, metrics, isAggregate);
134
+ if ('error' in checked) {
135
+ return checked.error;
136
+ }
137
+ having.push(checked.having);
138
+ }
118
139
  return {
119
140
  ok: true,
120
141
  dataset: set,
@@ -123,6 +144,7 @@ function validateQuery(raw, sets) {
123
144
  filters,
124
145
  groupBy,
125
146
  metrics,
147
+ having,
126
148
  select,
127
149
  orderBy,
128
150
  limit: resolveLimit(raw.limit, set),
@@ -172,12 +194,12 @@ function validateFilter(raw, set) {
172
194
  if (raw.value === undefined || raw.value === null) {
173
195
  return { error: fail(`Filter on "${field.name}" with "${op}" needs a value.`) };
174
196
  }
175
- if (op === 'in') {
197
+ if (LIST_VALUE_OPS.includes(op)) {
176
198
  const values = asArray(raw.value);
177
199
  if (values.length === 0) {
178
- return { error: fail(`Filter on "${field.name}" with "in" needs a non-empty list of values.`) };
200
+ return { error: fail(`Filter on "${field.name}" with "${op}" needs a non-empty list of values.`) };
179
201
  }
180
- const bad = enumViolation(field, values);
202
+ const bad = enumViolation(field, values, op);
181
203
  if (bad) {
182
204
  return { error: bad };
183
205
  }
@@ -192,15 +214,19 @@ function validateFilter(raw, set) {
192
214
  }
193
215
  return { filter: { field: field.name, op, value: values } };
194
216
  }
195
- const bad = enumViolation(field, [raw.value]);
217
+ const bad = enumViolation(field, [raw.value], op);
196
218
  if (bad) {
197
219
  return { error: bad };
198
220
  }
199
221
  return { filter: { field: field.name, op, value: raw.value } };
200
222
  }
201
- /** Enum fields accept only what they declared, so a typo is caught here. */
202
- function enumViolation(field, values) {
203
- if (field.type !== 'enum' || !field.enumValues?.length) {
223
+ /**
224
+ * Enum fields — and list fields that declare their members — accept only what
225
+ * they declared, so a typo is caught here rather than matching nothing. A
226
+ * `contains` value is a fragment, not a member, so it is not checked.
227
+ */
228
+ function enumViolation(field, values, op) {
229
+ if ((field.type !== 'enum' && field.type !== 'list') || !field.enumValues?.length || op === 'contains') {
204
230
  return null;
205
231
  }
206
232
  for (const value of values) {
@@ -215,9 +241,9 @@ function validateMetric(raw, set) {
215
241
  return { error: fail('Each metric must be an object of {fn, field}.') };
216
242
  }
217
243
  const fn = String(raw.fn ?? '');
218
- if (!['count', 'sum', 'avg', 'min', 'max'].includes(fn)) {
244
+ if (!AGGREGATES.includes(fn)) {
219
245
  return {
220
- error: fail(`Unknown aggregate "${raw.fn}". Available:`, ['count', 'sum', 'avg', 'min', 'max']),
246
+ error: fail(`Unknown aggregate "${raw.fn}". Available:`, AGGREGATES),
221
247
  };
222
248
  }
223
249
  // `count` alone counts rows, which needs no field and is always allowed.
@@ -230,6 +256,11 @@ function validateMetric(raw, set) {
230
256
  error: fail(`Cannot ${fn} "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
231
257
  };
232
258
  }
259
+ if (field.type === 'list') {
260
+ return {
261
+ error: fail(`Cannot ${fn} "${field.name}" — it is a list. Filter it with has or hasAny, and count the rows that match.`),
262
+ };
263
+ }
233
264
  if (!field.aggregates?.includes(fn)) {
234
265
  const capable = set.fields.filter((f) => f.aggregates?.includes(fn)).map((f) => f.name);
235
266
  return {
@@ -243,3 +274,45 @@ function validateMetric(raw, set) {
243
274
  }
244
275
  return { metric: { fn, field: field.name, as: metricName(fn, field.name, raw.as) } };
245
276
  }
277
+ /**
278
+ * A condition on an aggregate's result. It names one of this query's own
279
+ * metrics, not a field, because it applies after grouping — to the numbers the
280
+ * grouping produced. A plain listing has no such numbers, and its condition
281
+ * belongs in `filters`.
282
+ */
283
+ function validateHaving(raw, metrics, isAggregate) {
284
+ if (!isAggregate) {
285
+ return {
286
+ error: fail('"having" filters the result of an aggregate. Add the metric it compares (and usually a groupBy), or put the condition in "filters".'),
287
+ };
288
+ }
289
+ if (!raw || typeof raw !== 'object') {
290
+ return { error: fail('Each having must be an object of {field, op, value}, naming a metric by its "as".') };
291
+ }
292
+ const name = String(raw.field ?? '');
293
+ const metric = metrics.find((candidate) => candidate.as === name);
294
+ if (!metric) {
295
+ return {
296
+ error: metrics.length
297
+ ? fail(`Cannot apply having to "${name}" — it must name one of this query's metrics:`, metrics.map((m) => m.as))
298
+ : fail(`Cannot apply having to "${name}" — this query has no metrics. Add one, e.g. {"fn": "count", "as": "count"}.`),
299
+ };
300
+ }
301
+ const op = String(raw.op ?? '');
302
+ if (!HAVING_OPS.includes(op)) {
303
+ return { error: fail(`Operator "${raw.op}" cannot compare a metric. Allowed:`, HAVING_OPS) };
304
+ }
305
+ const values = op === 'between' ? asArray(raw.value) : [raw.value];
306
+ if (op === 'between' && values.length !== 2) {
307
+ return { error: fail(`Having on "${name}" with "between" needs exactly two values: [low, high].`) };
308
+ }
309
+ if (values.some((value) => value === undefined || value === null || value === '')) {
310
+ return { error: fail(`Having on "${name}" with "${op}" needs a value.`) };
311
+ }
312
+ const numeric = NUMBER_RESULT_AGGREGATES.includes(metric.fn);
313
+ if (numeric && values.some((value) => !Number.isFinite(Number(value)))) {
314
+ return { error: fail(`Having on "${name}" compares a ${metric.fn}, so its value must be a number.`) };
315
+ }
316
+ const typed = numeric ? values.map(Number) : values;
317
+ return { having: { field: name, op, value: op === 'between' ? typed : typed[0] } };
318
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Runs a validated query over rows a host already holds.
3
+ *
4
+ * Most hosts answer {@link DataSource.execute} by building a statement for their
5
+ * database. Some datasets are better served from memory: data assembled from
6
+ * several tables, from a code registry, or from another service; per-row facts
7
+ * that are awkward in SQL (a count of related records, a list of names); or a
8
+ * set small enough that a statement is not worth writing. A host builds the rows
9
+ * — one plain object per record, keyed by the dataset's field names — and hands
10
+ * them here with the validated query. Every host then gets the same semantics
11
+ * for filters, grouping, metrics, `having`, ordering and limits, instead of each
12
+ * re-implementing them slightly differently.
13
+ *
14
+ * Semantics, chosen to match what a SQL executor would answer:
15
+ * - A missing value (`null`/`undefined`) fails every comparison, `ne` included;
16
+ * only `isNull` matches it. A host should store "nothing" as `null`, not `''`.
17
+ * - Text compares case-insensitively and ignores surrounding spaces, as a person
18
+ * asking "carriers named sentry" means.
19
+ * - A `list` field holds an array of strings; `null` reads as an empty list.
20
+ * - `count` with a field counts rows where it is present; `sum`/`avg`/`min`/`max`
21
+ * skip missing values and are `null` when nothing is left — SQL's answer.
22
+ * - Missing values sort last in either direction, so "top 10" is never ten blanks.
23
+ *
24
+ * The query must have come from `validateQuery`: nothing here re-checks names.
25
+ */
26
+ import { DataQuery, DataResult, DataRow, DataSet } from './data.types';
27
+ /**
28
+ * @param query A query `validateQuery` accepted for this dataset
29
+ * @param set The dataset the query names
30
+ * @param rows Every row of the dataset the caller may see — already scoped to
31
+ * the tenant or user; this function applies the query and nothing else
32
+ * @returns The answer, with `totalRows` counting rows (a listing) or groups (an
33
+ * aggregate) before the limit
34
+ */
35
+ export declare function queryRows(query: DataQuery, set: DataSet, rows: DataRow[]): DataResult;