@m6d/cortex 0.3.0 → 0.5.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.
package/dist/drizzle.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import {
2
2
  CortexError,
3
3
  FUNCTION_SIGNATURES,
4
+ datasetColumnSchema,
4
5
  filterRefs,
5
6
  groupKeyName,
6
7
  isColumnValue
7
- } from "./index-dck60t84.js";
8
+ } from "./index-jw8cnjqv.js";
8
9
 
9
10
  // src/datasets/drizzle.ts
10
11
  import {
@@ -35,13 +36,10 @@ import {
35
36
  sum,
36
37
  Column,
37
38
  is,
38
- SQL
39
+ SQL,
40
+ Subquery
39
41
  } from "drizzle-orm";
40
42
  import { SQLiteTimestamp } from "drizzle-orm/sqlite-core";
41
- function enumValuesOf(column) {
42
- const values = column.enumValues;
43
- return values && values.length >= 1 && values.length <= 100 && values.every((value) => value.length >= 1 && value.length <= 200) ? values : undefined;
44
- }
45
43
  function columnTypeOf(column) {
46
44
  const dataType = column.dataType;
47
45
  if (dataType.startsWith("boolean"))
@@ -56,6 +54,27 @@ function columnTypeOf(column) {
56
54
  return "string";
57
55
  return;
58
56
  }
57
+ function isInstant(column) {
58
+ return column.dataType === "object date" && /^(timestamp|datetime2?|smalldatetime|integer)\b/.test(column.getSQLType());
59
+ }
60
+ function clockOf(timeZone) {
61
+ if (!timeZone)
62
+ return 0;
63
+ try {
64
+ const name = new Intl.DateTimeFormat("en-US", { timeZone, timeZoneName: "longOffset" }).formatToParts().find((part) => part.type === "timeZoneName")?.value;
65
+ const [, sign, hours, minutes] = /([+-])(\d\d):(\d\d)/.exec(name ?? "") ?? [];
66
+ return sign ? (sign === "-" ? -1 : 1) * (Number(hours) * 60 + Number(minutes)) : 0;
67
+ } catch {
68
+ return 0;
69
+ }
70
+ }
71
+ function onClock(instant, clock) {
72
+ const reading = new Date(instant.getTime() + clock * 60000);
73
+ if (Number.isNaN(reading.getTime()))
74
+ return instant;
75
+ const offset = `${clock < 0 ? "-" : "+"}${new Date(Math.abs(clock) * 60000).toISOString().slice(11, 16)}`;
76
+ return reading.toISOString().replace(/(\.000)?Z$/, offset);
77
+ }
59
78
  var DATE_TRUNC = {
60
79
  postgres: (date, unit) => sql`cast(date_trunc(${sql.raw(`'${unit}'`)}, ${date}) as date)`,
61
80
  mssql: (date, unit) => sql`CONVERT(varchar(10), DATETRUNC(${sql.raw(unit === "week" ? "iso_week" : unit)}, ${date}), 23)`,
@@ -74,23 +93,31 @@ var DATE_TRUNC = {
74
93
  }
75
94
  }
76
95
  };
77
- function dateSource(dialect, column) {
78
- if (!is(column, Column))
79
- return column;
80
- const sqlType = column.getSQLType();
81
- const textual = columnTypeOf(column) !== "date";
82
- switch (dialect) {
83
- case "postgres":
84
- if (textual)
85
- return sql`cast(${column} as timestamp)`;
86
- return sqlType.includes("with time zone") ? sql`(${column} at time zone 'UTC')` : column;
87
- case "mssql":
88
- return textual ? sql`cast(${column} as datetime2)` : column;
89
- case "sqlite":
90
- if (sqlType !== "integer")
91
- return column;
92
- return is(column, SQLiteTimestamp) && column.mode === "timestamp_ms" ? sql`datetime(${column} / 1000.0, 'unixepoch')` : sql`datetime(${column}, 'unixepoch')`;
96
+ var DATE_SOURCE = {
97
+ postgres: (value, stored) => {
98
+ if (columnTypeOf(stored) !== "date")
99
+ return sql`cast(${value} as timestamp)`;
100
+ return stored.getSQLType().includes("with time zone") ? sql`(${value} at time zone 'UTC')` : value;
101
+ },
102
+ mssql: (value, stored) => columnTypeOf(stored) === "date" ? value : sql`cast(${value} as datetime2)`,
103
+ sqlite: (value, stored) => {
104
+ if (stored.getSQLType() !== "integer")
105
+ return value;
106
+ return is(stored, SQLiteTimestamp) && stored.mode === "timestamp_ms" ? sql`datetime(${value} / 1000.0, 'unixepoch')` : sql`datetime(${value}, 'unixepoch')`;
93
107
  }
108
+ };
109
+ var ON_CLOCK = {
110
+ postgres: (date, clock) => sql`(${date} + interval '${sql.raw(String(clock))} minutes')`,
111
+ mssql: (date, clock) => {
112
+ const value = sql`cast(${date} as datetime2)`;
113
+ const past = sql.raw(clock > 0 ? `> dateadd(minute, ${-clock}, cast('9999-12-31T23:59:59.9999999' as datetime2))` : `< dateadd(minute, ${-clock}, cast('0001-01-01' as datetime2))`);
114
+ return sql`case when ${value} ${past} then ${value} else dateadd(minute, ${sql.raw(String(clock))}, ${value}) end`;
115
+ },
116
+ sqlite: (date, clock) => sql`coalesce(datetime(${date}, '${sql.raw(String(clock))} minutes'), ${date})`
117
+ };
118
+ function dateSource(dialect, { column, stored, clock }) {
119
+ const date = stored ? DATE_SOURCE[dialect](column, stored) : column;
120
+ return clock ? ON_CLOCK[dialect](date, clock) : date;
94
121
  }
95
122
  var DATE_PART = {
96
123
  postgres: (date, unit) => sql`cast(extract(${sql.raw(unit === "dayOfWeek" ? "isodow" : unit)} from ${date}) as integer)`,
@@ -133,7 +160,7 @@ function drizzleDataset(options) {
133
160
  if (declared && type !== "string") {
134
161
  throw new Error(`Dataset "${options.name}": only a string column lists its values, and ${name} is a ${type}`);
135
162
  }
136
- const values = declared ?? enumValuesOf(column);
163
+ const values = declared ?? datasetColumnSchema.shape.values.safeParse(column.enumValues).data;
137
164
  return [
138
165
  {
139
166
  name,
@@ -173,9 +200,19 @@ function drizzleDataset(options) {
173
200
  };
174
201
  return definition;
175
202
  },
176
- async run(query, user, signal) {
177
- const rows = await compile(dataset, options, query, user).execute();
203
+ async run(query, user, signal, context) {
204
+ const clock = clockOf(context.timeZone);
205
+ const { statement, instants } = compile(dataset, options, query, user, clock);
206
+ refuseOversized(statement.getSQL());
207
+ const rows = await statement.execute();
178
208
  signal.throwIfAborted();
209
+ for (const row of rows) {
210
+ for (const key of instants) {
211
+ const value = row[key];
212
+ if (value instanceof Date)
213
+ row[key] = onClock(value, clock);
214
+ }
215
+ }
179
216
  return rows;
180
217
  }
181
218
  };
@@ -189,7 +226,28 @@ function joinedOf(target, table, columnsByName) {
189
226
  relations: target.relations()
190
227
  };
191
228
  }
192
- function compile(root, options, query, user) {
229
+ var STATEMENT_MAX_PARTS = 50000;
230
+ function refuseOversized(statement) {
231
+ let left = STATEMENT_MAX_PARTS;
232
+ const walk = (chunk) => {
233
+ if (--left < 0) {
234
+ throw new CortexError("invalid_request", `The query writes out to more than ${STATEMENT_MAX_PARTS} parts of SQL; ask for fewer computed values or simpler ones`);
235
+ }
236
+ for (const part of partsOf(chunk))
237
+ walk(part);
238
+ };
239
+ walk(statement);
240
+ }
241
+ function partsOf(chunk) {
242
+ if (Array.isArray(chunk))
243
+ return chunk;
244
+ if (is(chunk, SQL))
245
+ return chunk.queryChunks;
246
+ if (is(chunk, Subquery))
247
+ return chunk._.isWith ? [] : [chunk._.sql];
248
+ return [];
249
+ }
250
+ function compile(root, options, query, user, clock) {
193
251
  const { dialect, db } = options;
194
252
  const { joined, joins } = joinRelations(root, query.join, user, db);
195
253
  const resolve = (ref) => {
@@ -198,7 +256,14 @@ function compile(root, options, query, user) {
198
256
  if (!table)
199
257
  throw new CortexError("unsupported", `"${ref}" is not reachable`);
200
258
  const name = ref.slice(dot + 1);
201
- return { column: columnOf(table, name), type: table.types.get(name) ?? "string" };
259
+ const column = columnOf(table, name);
260
+ const type = table.types.get(name) ?? "string";
261
+ return {
262
+ column,
263
+ type,
264
+ ...type === "date" && { stored: column },
265
+ ...isInstant(column) && { clock }
266
+ };
202
267
  };
203
268
  const shape = shapeOf(root, dialect, query, resolve);
204
269
  const conditions = [
@@ -217,7 +282,10 @@ function compile(root, options, query, user) {
217
282
  const { chain, target } = query.rank || query.qualify.length ? finished(dialect, db, select, shape, query) : { chain: select(shape.fields), target: (name) => sortTarget(shape, name) };
218
283
  const orderings = query.sort.map(({ col, dir }) => ordering(dialect, target(col), dir));
219
284
  const ordered = orderings.length ? chain.orderBy(...orderings) : chain;
220
- return capped(ordered, dialect, query, orderings.length > 0);
285
+ return {
286
+ statement: capped(ordered, dialect, query, orderings.length > 0),
287
+ instants: Object.keys(shape.fields).filter((key) => shape.row(key).clock)
288
+ };
221
289
  }
222
290
  function ordering(dialect, target, dir) {
223
291
  const term = dir === "asc" ? asc(target) : desc(target);
@@ -246,7 +314,7 @@ function finished(dialect, db, select, shape, query) {
246
314
  if (rank && !layered)
247
315
  fields[RANK] = rankSql(dialect, rank, shape.row);
248
316
  let inner = select(fields).as("finished");
249
- const outer = (ref) => ({ column: sql`${inner[ref]}`, type: shape.row(ref).type });
317
+ const outer = (ref) => ({ ...shape.row(ref), column: sql`${inner[ref]}` });
250
318
  const qualified = and(...query.qualify.map((filter) => filterSql(dialect, filter, outer)));
251
319
  if (rank && layered) {
252
320
  const numbered = Object.fromEntries(Object.keys(fields).map((key) => [key, inner[key]]));
@@ -325,9 +393,9 @@ function shapeOf(root, dialect, query, resolve) {
325
393
  const { fields, groupKeys } = grouped ? groupedFields(dialect, query, resolve, named) : plainFields(root, dialect, query, resolve, named);
326
394
  for (const entry of query.window) {
327
395
  const over = entry.partitionBy.map((col) => row(col).column);
328
- const { expression, type } = aggregateOf(dialect, entry, row, over);
396
+ const { expression, ...value } = aggregateOf(dialect, entry, row, over);
329
397
  fields[entry.as] = expression.as(entry.as);
330
- named.set(entry.as, { column: expression, type });
398
+ named.set(entry.as, { ...value, column: expression });
331
399
  }
332
400
  for (const entry of query.compute) {
333
401
  const value = operandSql(dialect, entry.expr, row);
@@ -346,12 +414,12 @@ function groupedFields(dialect, query, resolve, named) {
346
414
  const key = is(value.column, Column) ? value.column : value.column.inlineParams();
347
415
  fields[name] = is(key, Column) ? key : decoded(key, value.type);
348
416
  groupKeys.push(key);
349
- named.set(name, { column: key, type: value.type });
417
+ named.set(name, { ...value, column: key });
350
418
  }
351
419
  for (const aggregate of query.aggregate) {
352
- const { expression, type } = aggregateOf(dialect, aggregate, resolve);
420
+ const { expression, ...value } = aggregateOf(dialect, aggregate, resolve);
353
421
  fields[aggregate.as] = expression.as(aggregate.as);
354
- named.set(aggregate.as, { column: expression, type });
422
+ named.set(aggregate.as, { ...value, column: expression });
355
423
  }
356
424
  return { fields, groupKeys };
357
425
  }
@@ -420,13 +488,14 @@ function operandSql(dialect, operand, resolve) {
420
488
  return caseSql(dialect, operand, resolve);
421
489
  if ("args" in operand) {
422
490
  const args = operand.args.map((arg) => operandSql(dialect, arg, resolve));
491
+ const column = functionSql(dialect, operand.fn, args.map((arg) => arg.column));
423
492
  return {
424
- column: functionSql(dialect, operand.fn, args.map((arg) => arg.column)),
493
+ ...builtFrom(column, args),
425
494
  type: FUNCTION_SIGNATURES[operand.fn].answers ?? args[0].type
426
495
  };
427
496
  }
428
- const date = dateSource(dialect, operandSql(dialect, operand.of, resolve).column);
429
- return operand.fn === "dateTrunc" ? { column: DATE_TRUNC[dialect](date, operand.unit), type: "string" } : { column: DATE_PART[dialect](date, operand.unit), type: "number" };
497
+ const date = dateSource(dialect, operandSql(dialect, operand.of, resolve));
498
+ return operand.fn === "dateTrunc" ? { column: DATE_TRUNC[dialect](date, operand.unit), type: "date" } : { column: DATE_PART[dialect](date, operand.unit), type: "number" };
430
499
  }
431
500
  function literalSql(dialect, value) {
432
501
  if (typeof value === "string") {
@@ -443,11 +512,38 @@ function caseSql(dialect, operand, resolve) {
443
512
  }));
444
513
  const fallback = operand.else === undefined ? undefined : operandSql(dialect, operand.else, resolve);
445
514
  const whens = sql.join(branches.map(({ when, then }) => sql`when ${when} then ${then.column}`), sql` `);
515
+ const values = branches.map(({ then }) => then);
446
516
  return {
447
- column: sql`case ${whens}${fallback ? sql` else ${fallback.column}` : sql``} end`,
517
+ ...builtFrom(sql`case ${whens}${fallback ? sql` else ${fallback.column}` : sql``} end`, fallback ? [...values, fallback] : values),
448
518
  type: fallback?.type ?? branches[0].then.type
449
519
  };
450
520
  }
521
+ function builtFrom(column, parts) {
522
+ const { stored, clock } = meeting(parts);
523
+ if (!stored)
524
+ return { column };
525
+ return { column: column.mapWith(stored), stored, ...clock !== undefined && { clock } };
526
+ }
527
+ function meeting(parts) {
528
+ const dates = parts.filter((part) => part.type === "date");
529
+ const clock = dates.find((part) => part.clock !== undefined)?.clock;
530
+ if (clock !== undefined && dates.some((part) => part.clock === undefined)) {
531
+ throw new CortexError("unsupported", "an instant cannot meet a calendar or truncated date; compare or combine like with like");
532
+ }
533
+ const kept = dates.flatMap((part) => part.stored ? [part.stored] : []);
534
+ const [stored] = kept;
535
+ if (stored && kept.some((other) => storageOf(other) !== storageOf(stored))) {
536
+ throw new CortexError("unsupported", "dates kept differently (in seconds and in milliseconds, say) cannot meet; compare or combine like with like");
537
+ }
538
+ return { stored, clock };
539
+ }
540
+ function storageOf(column) {
541
+ if (is(column, SQLiteTimestamp))
542
+ return column.mode;
543
+ if (columnTypeOf(column) !== "date")
544
+ return "text";
545
+ return column.getSQLType().includes("with time zone") ? "zoned" : "native";
546
+ }
451
547
  function functionSql(dialect, fn, args) {
452
548
  const [first, digits] = args;
453
549
  switch (fn) {
@@ -481,7 +577,8 @@ function aggregateOf(dialect, aggregate, resolve, over) {
481
577
  const partition = over.length ? sql`partition by ${sql.join(over, sql`, `)}` : sql``;
482
578
  return sql`${fn} over (${partition})`;
483
579
  };
484
- const extreme = (expression) => is(column, Column) ? expression.mapWith(column) : decoded(expression, operand.type);
580
+ const decoder = is(column, Column) ? column : operand?.stored;
581
+ const extreme = (expression) => decoder ? expression.mapWith(decoder) : decoded(expression, operand.type);
485
582
  switch (aggregate.fn) {
486
583
  case "count":
487
584
  return {
@@ -504,15 +601,24 @@ function aggregateOf(dialect, aggregate, resolve, over) {
504
601
  type: "number"
505
602
  };
506
603
  case "min":
507
- return { expression: extreme(windowed(min(filtered))), type: operand.type };
604
+ return { ...operand, expression: extreme(windowed(min(filtered))) };
508
605
  case "max":
509
- return { expression: extreme(windowed(max(filtered))), type: operand.type };
606
+ return { ...operand, expression: extreme(windowed(max(filtered))) };
607
+ }
608
+ }
609
+ var OWN_OFFSET = /T[^Zz+-]*(?:[Zz]|[+-]\d{2}:?\d{2})$/;
610
+ function instantOf(text, clock) {
611
+ const iso = text.replace(/^(\d{4}-\d\d-\d\d)[t ](?=\d)/, "$1T");
612
+ const instant = OWN_OFFSET.test(iso) ? new Date(iso) : new Date(new Date(iso.includes("T") ? `${iso}Z` : iso).getTime() - clock * 60000);
613
+ if (!/^[+-]?\d{4}/.test(iso) || Number.isNaN(instant.getTime())) {
614
+ throw new CortexError("invalid_request", `"${text}" is not a date this host can read`);
510
615
  }
616
+ return instant;
511
617
  }
512
618
  function coerce(type, value) {
513
619
  switch (type) {
514
620
  case "date":
515
- return typeof value === "string" ? new Date(value) : value;
621
+ return value;
516
622
  case "number":
517
623
  return typeof value === "string" ? Number(value) : value;
518
624
  case "boolean":
@@ -526,13 +632,23 @@ function escapeLike(value) {
526
632
  }
527
633
  function condition(dialect, target, filter, resolve) {
528
634
  const column = target.column;
529
- const dateColumn = dialect !== "mssql" && is(target.column, Column) && columnTypeOf(target.column) === "date";
530
- const type = target.type === "date" && !dateColumn ? "string" : target.type;
635
+ const stored = dialect !== "mssql" && target.stored && columnTypeOf(target.stored) === "date" ? target.stored : undefined;
636
+ const type = target.type === "date" && !stored ? "string" : target.type;
531
637
  const literal = (value) => {
532
- const coerced = coerce(type, value);
638
+ if (stored && typeof value === "string") {
639
+ const date = instantOf(value, target.clock ?? 0);
640
+ return is(target.column, Column) ? date : stored.mapToDriverValue(date);
641
+ }
642
+ const coerced = target.clock && typeof value === "string" ? instantOf(value, target.clock).toISOString().slice(0, -1) : coerce(type, value);
533
643
  return typeof coerced === "string" || typeof coerced === "boolean" ? literalSql(dialect, coerced).column : coerced;
534
644
  };
535
- const scalar = () => isColumnValue(filter.value) ? operandSql(dialect, filter.value.col, resolve).column : literal(filter.value);
645
+ const scalar = () => {
646
+ if (!isColumnValue(filter.value))
647
+ return literal(filter.value);
648
+ const right = operandSql(dialect, filter.value.col, resolve);
649
+ meeting([target, right]);
650
+ return right.column;
651
+ };
536
652
  const list = () => filter.value.map(literal);
537
653
  const text = () => typeof filter.value === "object" ? "" : String(filter.value);
538
654
  switch (filter.op) {
@@ -1,3 +1,7 @@
1
+ // src/cortex-error.ts
2
+ import { createHash } from "node:crypto";
3
+ import { bodyLimit } from "hono/body-limit";
4
+
1
5
  // ../../internal/contracts/src/errors/index.ts
2
6
  import { z } from "zod";
3
7
  var BACKEND_ERROR_KINDS = [
@@ -21,6 +25,11 @@ var backendErrorSchema = z.object({
21
25
  detail: z.string().max(BACKEND_ERROR_DETAIL_MAX)
22
26
  })
23
27
  });
28
+ function errorEnvelope(kind, detail) {
29
+ return {
30
+ error: { kind, detail: detail.slice(0, BACKEND_ERROR_DETAIL_MAX) }
31
+ };
32
+ }
24
33
 
25
34
  // src/cortex-error.ts
26
35
  class CortexError extends Error {
@@ -31,11 +40,7 @@ class CortexError extends Error {
31
40
  this.name = "CortexError";
32
41
  }
33
42
  }
34
- function errorEnvelope(kind, detail) {
35
- return {
36
- error: { kind, detail: detail.slice(0, BACKEND_ERROR_DETAIL_MAX) }
37
- };
38
- }
43
+ var malformedBody = errorEnvelope("invalid_request", "Malformed request body");
39
44
  function envelopeOf(error) {
40
45
  if (error instanceof CortexError)
41
46
  return errorEnvelope(error.kind, error.message);
@@ -44,6 +49,15 @@ function envelopeOf(error) {
44
49
  }
45
50
  return errorEnvelope("internal", "The call failed");
46
51
  }
52
+ function protocolBodyLimit(maxSize) {
53
+ return bodyLimit({
54
+ maxSize,
55
+ onError: (c) => c.json(errorEnvelope("invalid_request", "Request body too large"), 413)
56
+ });
57
+ }
58
+ function contentVersion(value) {
59
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
60
+ }
47
61
 
48
62
  // ../../internal/contracts/src/datasets/datasets.ts
49
63
  import { z as z2 } from "zod";
@@ -55,6 +69,33 @@ function isRecord(value) {
55
69
  function unescapePointerToken(token) {
56
70
  return token.replaceAll("~1", "/").replaceAll("~0", "~");
57
71
  }
72
+ function pointerTokens(pointer) {
73
+ let path = pointer;
74
+ if (pointer.startsWith("#")) {
75
+ try {
76
+ path = decodeURIComponent(pointer.slice(1));
77
+ } catch {
78
+ return;
79
+ }
80
+ }
81
+ if (path === "")
82
+ return [];
83
+ if (!path.startsWith("/"))
84
+ return;
85
+ return path.slice(1).split("/").map(unescapePointerToken);
86
+ }
87
+ var ARRAY_INDEX = /^(?:0|[1-9]\d*)$/;
88
+ var JSON_NUMBER_PATTERN = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$/;
89
+ function pointerChild(container, token) {
90
+ if (Array.isArray(container)) {
91
+ const items = container;
92
+ return ARRAY_INDEX.test(token) ? items[Number(token)] : undefined;
93
+ }
94
+ return isRecord(container) && Object.hasOwn(container, token) ? container[token] : undefined;
95
+ }
96
+ function readJsonPointer(document, pointer) {
97
+ return pointerTokens(pointer)?.reduce(pointerChild, document);
98
+ }
58
99
 
59
100
  // ../../internal/contracts/src/datasets/datasets.ts
60
101
  var DATASET_IDENTIFIER_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
@@ -63,11 +104,19 @@ var DATASET_COLUMN_REF_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*
63
104
  var datasetIdentifierSchema = z2.string().regex(DATASET_IDENTIFIER_PATTERN).max(DATASET_IDENTIFIER_MAX);
64
105
  var datasetColumnRefSchema = z2.string().regex(DATASET_COLUMN_REF_PATTERN).max(256);
65
106
  var DATASET_COLUMN_TYPES = ["string", "number", "boolean", "date"];
107
+ var DATASET_DEFINITION_LIMITS = {
108
+ description: 500,
109
+ columns: 200,
110
+ columnDescription: 200,
111
+ values: 100,
112
+ valueLength: 200,
113
+ maxRows: 5000
114
+ };
66
115
  var datasetColumnSchema = z2.object({
67
116
  name: datasetIdentifierSchema,
68
117
  type: z2.enum(DATASET_COLUMN_TYPES),
69
- description: z2.string().max(200).default(""),
70
- values: z2.array(z2.string().min(1).max(200)).min(1).max(100).optional()
118
+ description: z2.string().max(DATASET_DEFINITION_LIMITS.columnDescription).default(""),
119
+ values: z2.array(z2.string().min(1).max(DATASET_DEFINITION_LIMITS.valueLength)).min(1).max(DATASET_DEFINITION_LIMITS.values).optional()
71
120
  }).refine((column) => column.values === undefined || column.type === "string", {
72
121
  message: "only a string column lists its values",
73
122
  path: ["values"]
@@ -83,10 +132,10 @@ var datasetRelationSchema = z2.object({
83
132
  var DATASET_MAX_ROWS_DEFAULT = 500;
84
133
  var datasetDefinitionSchema = z2.object({
85
134
  name: datasetIdentifierSchema,
86
- description: z2.string().max(500),
87
- columns: z2.array(datasetColumnSchema).min(1).max(200),
135
+ description: z2.string().max(DATASET_DEFINITION_LIMITS.description),
136
+ columns: z2.array(datasetColumnSchema).min(1).max(DATASET_DEFINITION_LIMITS.columns),
88
137
  relations: z2.record(datasetIdentifierSchema, datasetRelationSchema).default({}),
89
- maxRows: z2.number().int().min(1).max(5000).default(DATASET_MAX_ROWS_DEFAULT)
138
+ maxRows: z2.number().int().min(1).max(DATASET_DEFINITION_LIMITS.maxRows).default(DATASET_MAX_ROWS_DEFAULT)
90
139
  });
91
140
  var datasetManifestSchema = z2.object({
92
141
  version: z2.string().min(1).max(128),
@@ -166,11 +215,12 @@ var datasetConditionSchema = z2.object({
166
215
  z2.object({ col: datasetOperandSchema })
167
216
  ]).optional()
168
217
  });
218
+ var notACondition = { col: z2.never().optional() };
169
219
  var datasetFilterSchema = z2.lazy(() => z2.union([
170
220
  datasetConditionSchema,
171
- z2.object({ any: z2.array(datasetFilterSchema).min(1).max(20) }),
172
- z2.object({ all: z2.array(datasetFilterSchema).min(1).max(20) }),
173
- z2.object({ not: datasetFilterSchema })
221
+ z2.object({ any: z2.array(datasetFilterSchema).min(1).max(20), ...notACondition }),
222
+ z2.object({ all: z2.array(datasetFilterSchema).min(1).max(20), ...notACondition }),
223
+ z2.object({ not: datasetFilterSchema, ...notACondition })
174
224
  ]));
175
225
  var datasetGroupBySchema = z2.union([datasetColumnRefSchema, datasetNamedOperandSchema]);
176
226
  var datasetSortSchema = z2.object({
@@ -202,10 +252,12 @@ var datasetQueryObjectSchema = z2.object({
202
252
  limit: z2.number().int().min(1).max(100)
203
253
  }).optional(),
204
254
  sort: z2.array(datasetSortSchema).max(5).default([]).describe("By a column or select alias, a group key, an aggregate alias or a computed alias."),
205
- limit: z2.number().int().min(1).optional(),
206
- offset: z2.number().int().min(0).optional()
255
+ limit: z2.int32().min(1).optional(),
256
+ offset: z2.int32().min(0).optional()
207
257
  });
208
258
  var DATASET_QUERY_MAX_DEPTH = 32;
259
+ var DATASET_REQUEST_MAX_BYTES = 256 * 1024;
260
+ var DATASET_COMPUTE_REFERENCES_MAX = 100;
209
261
  function nestsWithin(value, budget) {
210
262
  if (typeof value !== "object" || value === null)
211
263
  return true;
@@ -216,7 +268,8 @@ var datasetRequestSchema = z2.object({
216
268
  query: datasetQuerySchema,
217
269
  context: z2.object({
218
270
  threadId: z2.string().max(128),
219
- requestId: z2.string().max(128).optional()
271
+ requestId: z2.string().max(128).optional(),
272
+ timeZone: z2.string().max(64).optional()
220
273
  })
221
274
  });
222
275
  var datasetResultSchema = z2.object({
@@ -477,7 +530,9 @@ function validateDatasetQuery(catalog, query) {
477
530
  checkFilter(check, filter);
478
531
  const row = checkAnsweredRow(check, catalog, query);
479
532
  checkFinishedRow(check, query, row);
480
- checkExpansion(check, query, catalog.get(query.from)?.columns.length ?? 0);
533
+ if (computeReferences(query) > DATASET_COMPUTE_REFERENCES_MAX) {
534
+ check.issue(`computed aliases are named more than ${DATASET_COMPUTE_REFERENCES_MAX} times once each is written out where it is named; name earlier computed aliases fewer times`);
535
+ }
481
536
  return issues;
482
537
  }
483
538
  function checkAnsweredRow(check, catalog, query) {
@@ -507,106 +562,24 @@ function checkAnsweredRow(check, catalog, query) {
507
562
  columns: passedColumns(catalog, query, query.select ?? [])
508
563
  };
509
564
  }
510
- var DATASET_EXPANSION_BUDGET = 2000;
511
- function checkExpansion(check, query, columnCount) {
512
- const source = new Map;
513
- const named = [...query.select ?? [], ...query.groupBy].flatMap((entry) => typeof entry === "string" ? [] : [[entry.as, operandCost(entry.expr, source)]]);
514
- const where = query.filter.map((filter) => filterCost(filter, source));
515
- const costs = [...named.map(([, total]) => total), ...where];
516
- const expanded = new Map(named);
517
- const aggregates = query.aggregate.map((entry) => {
518
- const parts = [
519
- ...entry.col === undefined ? [] : [operandCost(entry.col, source)],
520
- ...entry.filter.map((filter) => filterCost(filter, source))
521
- ];
522
- costs.push(...parts);
523
- expanded.set(entry.as, nodeCost(parts));
524
- return nodeCost(parts);
525
- });
526
- const grouped = query.groupBy.length > 0 || query.aggregate.length > 0;
527
- const projected = grouped ? query.groupBy : query.select ?? [];
528
- const carried = Math.min(DATASET_EXPANSION_BUDGET + 1, [
529
- ...where,
530
- ...projected.map((entry) => typeof entry === "string" ? 1 : expanded.get(entry.as) ?? 1),
531
- ...grouped || projected.length ? [] : Array(columnCount).fill(1),
532
- ...aggregates
533
- ].reduce((total, cost) => total + cost, 0));
534
- const windows = query.window.map((entry) => {
535
- const total = nodeCost([
536
- ...entry.col === undefined ? [] : [operandCost(entry.col, expanded)],
537
- ...entry.filter.map((filter) => filterCost(filter, expanded)),
538
- ...entry.partitionBy.map((name) => operandCost(name, expanded)),
539
- carried
540
- ]);
541
- costs.push(total);
542
- return [entry.as, total];
543
- });
544
- for (const [as, total] of windows)
545
- expanded.set(as, total);
565
+ function computeReferences(query) {
566
+ const written = new Map;
567
+ const count = (refs) => Math.min(refs.reduce((sum, ref) => {
568
+ const inner = written.get(ref);
569
+ return inner === undefined ? sum : sum + 1 + inner;
570
+ }, 0), DATASET_COMPUTE_REFERENCES_MAX + 1);
571
+ let total = 0;
546
572
  for (const entry of query.compute) {
547
- const total = operandCost(entry.expr, expanded);
548
- expanded.set(entry.as, total);
549
- costs.push(total);
550
- }
551
- for (const filter of query.having)
552
- costs.push(filterCost(filter, expanded));
553
- const qualifying = query.groupBy.length ? source : expanded;
554
- for (const filter of query.qualify)
555
- costs.push(filterCost(filter, qualifying));
556
- if (costs.some((total) => total > DATASET_EXPANSION_BUDGET)) {
557
- check.issue(`Computed aliases expand to more than ${DATASET_EXPANSION_BUDGET} references; name intermediate results and reuse them less`);
558
- }
559
- }
560
- var EXPANSION_WEIGHTS = {
561
- divisor: 2,
562
- roundDigits: 2,
563
- lengthText: 2,
564
- conditionLeft: 3,
565
- conditionRight: 2,
566
- dateTrunc: { day: 9, month: 6, quarter: 6, year: 3, week: 17 },
567
- datePart: { day: 1, month: 1, quarter: 1, year: 1, dayOfWeek: 16, week: 17 }
568
- };
569
- function nodeCost(children) {
570
- return Math.min(DATASET_EXPANSION_BUDGET + 1, children.reduce((total, cost) => total + cost, 1));
571
- }
572
- function argumentWeight(fn, index) {
573
- if (fn === "length")
574
- return EXPANSION_WEIGHTS.lengthText;
575
- return fn === "round" && index === 1 ? EXPANSION_WEIGHTS.roundDigits : 1;
576
- }
577
- function operandCost(operand, expanded) {
578
- if (typeof operand === "string")
579
- return expanded.get(operand) ?? 1;
580
- if (typeof operand === "number" || "value" in operand)
581
- return 1;
582
- if ("op" in operand) {
583
- const divisor = operand.op === "/" ? EXPANSION_WEIGHTS.divisor : 1;
584
- return nodeCost([
585
- operandCost(operand.left, expanded),
586
- operandCost(operand.right, expanded) * divisor
587
- ]);
588
- }
589
- if ("case" in operand) {
590
- return nodeCost([
591
- ...operand.case.map((branch) => nodeCost([filterCost(branch.when, expanded), operandCost(branch.then, expanded)])),
592
- ...operand.else === undefined ? [] : [operandCost(operand.else, expanded)]
593
- ]);
594
- }
595
- if ("args" in operand) {
596
- return nodeCost(operand.args.map((arg, index) => operandCost(arg, expanded) * argumentWeight(operand.fn, index)));
597
- }
598
- const weight = operand.fn === "dateTrunc" ? EXPANSION_WEIGHTS.dateTrunc[operand.unit] : EXPANSION_WEIGHTS.datePart[operand.unit];
599
- return nodeCost([operandCost(operand.of, expanded) * weight]);
600
- }
601
- function filterCost(filter, expanded) {
602
- if ("not" in filter)
603
- return nodeCost([filterCost(filter.not, expanded)]);
604
- if ("any" in filter || "all" in filter) {
605
- const entries = "any" in filter ? filter.any : filter.all;
606
- return nodeCost(entries.map((entry) => filterCost(entry, expanded)));
573
+ const own = count(operandRefs(entry.expr));
574
+ written.set(entry.as, own);
575
+ total += own;
607
576
  }
608
- const right = isColumnValue(filter.value) ? operandCost(filter.value.col, expanded) * EXPANSION_WEIGHTS.conditionRight : Array.isArray(filter.value) ? filter.value.length : filter.value === undefined ? 0 : 1;
609
- return nodeCost([operandCost(filter.col, expanded) * EXPANSION_WEIGHTS.conditionLeft, right]);
577
+ const rowNames = [
578
+ ...[...query.having, ...query.qualify].flatMap(filterRefs),
579
+ ...[...query.sort, ...query.rank?.sort ?? []].map((entry) => entry.col),
580
+ ...query.rank?.partitionBy ?? []
581
+ ];
582
+ return total + count(rowNames);
610
583
  }
611
584
  function checkFinishedRow(check, query, row) {
612
585
  const rowCheck = rowScope(check, row);
@@ -878,7 +851,7 @@ function filterValueTypeIssue(type, filter) {
878
851
  const fits = (value) => {
879
852
  switch (type) {
880
853
  case "number":
881
- return typeof value === "number" || typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value));
854
+ return typeof value === "number" || typeof value === "string" && JSON_NUMBER_PATTERN.test(value) && Number.isFinite(Number(value));
882
855
  case "date":
883
856
  return typeof value === "string" && !Number.isNaN(Date.parse(value));
884
857
  case "boolean":
@@ -1208,4 +1181,4 @@ class Sources {
1208
1181
  }
1209
1182
  // ../../internal/contracts/src/datasets/dataset-sql-guide.ts
1210
1183
  var DATASET_SQL_GRAMMAR = "One SELECT over one dataset. LEFT JOIN related datasets exactly as the dataset's description lists them (LEFT JOIN keeps rows without a match; JOIN or INNER JOIN drops them); reference dataset.column. " + "SELECT: columns, DATE_TRUNC('unit', column), EXTRACT(part FROM column), CASE WHEN ... END, LOWER/UPPER/TRIM/LENGTH/ABS/ROUND/COALESCE, COUNT/SUM/AVG/MIN/MAX over a column or arithmetic each with an optional FILTER (WHERE ...), and named arithmetic between aggregates (SUM(a) / COUNT(*) AS avg). " + "WHERE and HAVING: AND, OR, NOT, parentheses, comparisons with literals or other columns, IN, BETWEEN, LIKE, IS NULL; CURRENT_DATE and INTERVAL arithmetic on it. " + "GROUP BY columns or select aliases. An aggregate with OVER () or OVER (PARTITION BY ...) is a window: that aggregate over the rows sharing the partition, on every row (SUM(COUNT(*)) OVER () is the grand total); name it AS, use it in arithmetic, and QUALIFY filters the finished rows. " + "QUALIFY RANK() OVER (PARTITION BY ... ORDER BY ...) <= n for the top n per group (rows tied on every ORDER BY key share a rank and all stay); ORDER BY; LIMIT; OFFSET. " + "Rows nest qualified columns under the qualifier as written (pets.name comes back as row.pets.name); aliases and aggregates are top-level.";
1211
- export { BACKEND_ERROR_STATUS, backendErrorSchema, isRecord, unescapePointerToken, CortexError, errorEnvelope, envelopeOf, datasetIdentifierSchema, datasetDefinitionSchema, datasetRequestSchema, datasetCatalogOf, groupKeyName, filterRefs, isColumnValue, checkDatasetQuery, boundDatasetResult, FUNCTION_SIGNATURES };
1184
+ export { BACKEND_ERROR_STATUS, backendErrorSchema, errorEnvelope, isRecord, readJsonPointer, CortexError, malformedBody, envelopeOf, protocolBodyLimit, contentVersion, datasetIdentifierSchema, datasetColumnSchema, datasetDefinitionSchema, DATASET_REQUEST_MAX_BYTES, datasetRequestSchema, datasetCatalogOf, groupKeyName, filterRefs, isColumnValue, checkDatasetQuery, boundDatasetResult, FUNCTION_SIGNATURES };