@aeye/query 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -82,6 +82,9 @@ var AID_REGISTRY = {
82
82
  Source: { label: "a query source", noun: "source" },
83
83
  // ── Scalars / literals ────────────────────────────────────────────────────
84
84
  ScalarValue: { label: "a literal value: string, number, boolean, or null" },
85
+ LiteralValue: {
86
+ label: "a literal value: string, number, boolean, null, or a whole JSON document (object / array) for a json / array field"
87
+ },
85
88
  TypeName: { label: "a registered Type name" },
86
89
  FieldName: { label: "a field name" },
87
90
  FunctionName: { label: "a registered function name" },
@@ -110,7 +113,7 @@ var AID_REGISTRY = {
110
113
  SourceName: { label: "a bound source name" },
111
114
  SelectField: { label: "a select field, an object of { expr, as? }" },
112
115
  FieldValue: { label: "a field assignment, an object of { field, value }" },
113
- WriteValue: { label: "a write value: a typed value or an expression (use JSON null / omit to skip a field)" },
116
+ WriteValue: { label: "a write value: a typed value, a JSON document (object / array) for a json / array field, or an expression (use JSON null / omit to skip a field)" },
114
117
  InsertRow: { label: "an INSERT row, a { field: value } object" },
115
118
  SetValue: { label: "a SET record, a { field: value } object" },
116
119
  OnConflict: { label: "an ON CONFLICT clause, an object of { fields, doNothing?, update? }" },
@@ -829,16 +832,16 @@ var NumberFieldType = class _NumberFieldType extends FieldType {
829
832
  /** This instance's discriminant kind. */
830
833
  kind = _NumberFieldType.NAME;
831
834
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
832
- static from(json) {
833
- if (json.kind !== "number") {
835
+ static from(json2) {
836
+ if (json2.kind !== "number") {
834
837
  throw new QueryTypeError({
835
838
  path: [],
836
839
  code: "field-type.mismatch",
837
840
  severity: "error",
838
- message: `NumberFieldType.from: expected kind 'number', got '${json.kind}'`
841
+ message: `NumberFieldType.from: expected kind 'number', got '${json2.kind}'`
839
842
  });
840
843
  }
841
- const { min: min2, max: max2, whole, minPlaces, maxPlaces, values } = json;
844
+ const { min: min2, max: max2, whole, minPlaces, maxPlaces, values } = json2;
842
845
  return new _NumberFieldType(compactNumberOptions({ min: min2, max: max2, whole, minPlaces, maxPlaces, values }));
843
846
  }
844
847
  /** The Zod schema for this field type's JSON def. */
@@ -912,16 +915,16 @@ var TextFieldType = class _TextFieldType extends FieldType {
912
915
  return this.options.sensitive === true;
913
916
  }
914
917
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
915
- static from(json) {
916
- if (json.kind !== "text") {
918
+ static from(json2) {
919
+ if (json2.kind !== "text") {
917
920
  throw new QueryTypeError({
918
921
  path: [],
919
922
  code: "field-type.mismatch",
920
923
  severity: "error",
921
- message: `TextFieldType.from: expected kind 'text', got '${json.kind}'`
924
+ message: `TextFieldType.from: expected kind 'text', got '${json2.kind}'`
922
925
  });
923
926
  }
924
- const { minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values } = json;
927
+ const { minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values } = json2;
925
928
  return new _TextFieldType(compact({ minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values }));
926
929
  }
927
930
  /** The Zod schema for this field type's JSON def. */
@@ -996,16 +999,16 @@ var MoneyFieldType = class _MoneyFieldType extends FieldType {
996
999
  /** This instance's discriminant kind. */
997
1000
  kind = _MoneyFieldType.NAME;
998
1001
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
999
- static from(json) {
1000
- if (json.kind !== "money") {
1002
+ static from(json2) {
1003
+ if (json2.kind !== "money") {
1001
1004
  throw new QueryTypeError({
1002
1005
  path: [],
1003
1006
  code: "field-type.mismatch",
1004
1007
  severity: "error",
1005
- message: `MoneyFieldType.from: expected kind 'money', got '${json.kind}'`
1008
+ message: `MoneyFieldType.from: expected kind 'money', got '${json2.kind}'`
1006
1009
  });
1007
1010
  }
1008
- return new _MoneyFieldType(compact2({ number: json.number, currency: json.currency }));
1011
+ return new _MoneyFieldType(compact2({ number: json2.number, currency: json2.currency }));
1009
1012
  }
1010
1013
  /** The Zod schema for this field type's JSON def. */
1011
1014
  static toSchema() {
@@ -1052,13 +1055,13 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
1052
1055
  /** This instance's discriminant kind. */
1053
1056
  kind = _BoolFieldType.NAME;
1054
1057
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1055
- static from(json) {
1056
- if (json.kind !== "bool") {
1058
+ static from(json2) {
1059
+ if (json2.kind !== "bool") {
1057
1060
  throw new QueryTypeError({
1058
1061
  path: [],
1059
1062
  code: "field-type.mismatch",
1060
1063
  severity: "error",
1061
- message: `BoolFieldType.from: expected kind 'bool', got '${json.kind}'`
1064
+ message: `BoolFieldType.from: expected kind 'bool', got '${json2.kind}'`
1062
1065
  });
1063
1066
  }
1064
1067
  return new _BoolFieldType();
@@ -1319,16 +1322,16 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1319
1322
  /** This instance's discriminant kind. */
1320
1323
  kind = _RelationFieldType.NAME;
1321
1324
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1322
- static from(json) {
1323
- if (json.kind !== "relation") {
1325
+ static from(json2) {
1326
+ if (json2.kind !== "relation") {
1324
1327
  throw new QueryTypeError({
1325
1328
  path: [],
1326
1329
  code: "field-type.mismatch",
1327
1330
  severity: "error",
1328
- message: `RelationFieldType.from: expected kind 'relation', got '${json.kind}'`
1331
+ message: `RelationFieldType.from: expected kind 'relation', got '${json2.kind}'`
1329
1332
  });
1330
1333
  }
1331
- return new _RelationFieldType(json.to, json.count, json.inverseRelation);
1334
+ return new _RelationFieldType(json2.to, json2.count, json2.inverseRelation);
1332
1335
  }
1333
1336
  /** The Zod schema for this field type's JSON def. */
1334
1337
  static toSchema() {
@@ -1498,16 +1501,16 @@ var TimestampFieldType = class _TimestampFieldType extends FieldType {
1498
1501
  /** This instance's discriminant kind. */
1499
1502
  kind = _TimestampFieldType.NAME;
1500
1503
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1501
- static from(json) {
1502
- if (json.kind !== "timestamp") {
1504
+ static from(json2) {
1505
+ if (json2.kind !== "timestamp") {
1503
1506
  throw new QueryTypeError({
1504
1507
  path: [],
1505
1508
  code: "field-type.mismatch",
1506
1509
  severity: "error",
1507
- message: `TimestampFieldType.from: expected kind 'timestamp', got '${json.kind}'`
1510
+ message: `TimestampFieldType.from: expected kind 'timestamp', got '${json2.kind}'`
1508
1511
  });
1509
1512
  }
1510
- return new _TimestampFieldType(json.timezone);
1513
+ return new _TimestampFieldType(json2.timezone);
1511
1514
  }
1512
1515
  /** The Zod schema for this field type's JSON def. */
1513
1516
  static toSchema() {
@@ -1555,16 +1558,16 @@ var DateFieldType = class _DateFieldType extends FieldType {
1555
1558
  /** This instance's discriminant kind. */
1556
1559
  kind = _DateFieldType.NAME;
1557
1560
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1558
- static from(json) {
1559
- if (json.kind !== "date") {
1561
+ static from(json2) {
1562
+ if (json2.kind !== "date") {
1560
1563
  throw new QueryTypeError({
1561
1564
  path: [],
1562
1565
  code: "field-type.mismatch",
1563
1566
  severity: "error",
1564
- message: `DateFieldType.from: expected kind 'date', got '${json.kind}'`
1567
+ message: `DateFieldType.from: expected kind 'date', got '${json2.kind}'`
1565
1568
  });
1566
1569
  }
1567
- return new _DateFieldType(json.timezone);
1570
+ return new _DateFieldType(json2.timezone);
1568
1571
  }
1569
1572
  /** The Zod schema for this field type's JSON def. */
1570
1573
  static toSchema() {
@@ -1625,16 +1628,16 @@ var JsonFieldType = class _JsonFieldType extends FieldType {
1625
1628
  /** This instance's discriminant kind. */
1626
1629
  kind = _JsonFieldType.NAME;
1627
1630
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1628
- static from(json) {
1629
- if (json.kind !== "json") {
1631
+ static from(json2) {
1632
+ if (json2.kind !== "json") {
1630
1633
  throw new QueryTypeError({
1631
1634
  path: [],
1632
1635
  code: "field-type.mismatch",
1633
1636
  severity: "error",
1634
- message: `JsonFieldType.from: expected kind 'json', got '${json.kind}'`
1637
+ message: `JsonFieldType.from: expected kind 'json', got '${json2.kind}'`
1635
1638
  });
1636
1639
  }
1637
- return new _JsonFieldType(json.schema);
1640
+ return new _JsonFieldType(json2.schema);
1638
1641
  }
1639
1642
  /** The Zod schema for this field type's JSON def. */
1640
1643
  static toSchema() {
@@ -1693,17 +1696,17 @@ var ArrayFieldType = class _ArrayFieldType extends FieldType {
1693
1696
  /** This instance's discriminant kind. */
1694
1697
  kind = _ArrayFieldType.NAME;
1695
1698
  /** Reconstruct from a JSON def, parsing the element type via the registry. */
1696
- static from(json, registry) {
1697
- if (json.kind !== "array") {
1699
+ static from(json2, registry) {
1700
+ if (json2.kind !== "array") {
1698
1701
  throw new QueryTypeError({
1699
1702
  path: [],
1700
1703
  code: "field-type.mismatch",
1701
1704
  severity: "error",
1702
- message: `ArrayFieldType.from: expected kind 'array', got '${json.kind}'`
1705
+ message: `ArrayFieldType.from: expected kind 'array', got '${json2.kind}'`
1703
1706
  });
1704
1707
  }
1705
- const item = json.item !== void 0 && registry ? registry.parseFieldType(json.item) : void 0;
1706
- return new _ArrayFieldType(item, json.minItems, json.maxItems);
1708
+ const item = json2.item !== void 0 && registry ? registry.parseFieldType(json2.item) : void 0;
1709
+ return new _ArrayFieldType(item, json2.minItems, json2.maxItems);
1707
1710
  }
1708
1711
  /** The Zod schema for this field type's JSON def. */
1709
1712
  static toSchema() {
@@ -1830,21 +1833,21 @@ var Field = class _Field {
1830
1833
  this.synthetic = spec.synthetic ?? false;
1831
1834
  }
1832
1835
  /** Build a Field from its JSON, parsing the field type via `registry`. */
1833
- static from(json, registry) {
1834
- const fieldType = registry.parseFieldType(json.type);
1836
+ static from(json2, registry) {
1837
+ const fieldType = registry.parseFieldType(json2.type);
1835
1838
  return new _Field({
1836
- name: json.name,
1837
- label: json.label,
1838
- description: json.description,
1839
+ name: json2.name,
1840
+ label: json2.label,
1841
+ description: json2.description,
1839
1842
  fieldType,
1840
1843
  // An explicit per-field `bytes` wins; otherwise a registry-level default for
1841
1844
  // this field type's kind may apply (else the field type's own avgBytes()).
1842
- bytes: json.bytes ?? registry.defaultFieldBytes(fieldType.kind),
1843
- changes: json.changes,
1844
- nullable: json.nullable ?? false,
1845
- insertable: json.insertable,
1846
- updatable: json.updatable,
1847
- exprs: json.exprs
1845
+ bytes: json2.bytes ?? registry.defaultFieldBytes(fieldType.kind),
1846
+ changes: json2.changes,
1847
+ nullable: json2.nullable ?? false,
1848
+ insertable: json2.insertable,
1849
+ updatable: json2.updatable,
1850
+ exprs: json2.exprs
1848
1851
  });
1849
1852
  }
1850
1853
  /**
@@ -1966,8 +1969,8 @@ function stableStringify(value2) {
1966
1969
  return JSON.stringify(value2);
1967
1970
  }
1968
1971
  function exprDigest(expr) {
1969
- const json = JSON.parse(JSON.stringify(expr));
1970
- return stableStringify(json);
1972
+ const json2 = JSON.parse(JSON.stringify(expr));
1973
+ return stableStringify(json2);
1971
1974
  }
1972
1975
  function renameJson(node, from, to) {
1973
1976
  if (Array.isArray(node)) return node.map((n) => renameJson(n, from, to));
@@ -2066,8 +2069,8 @@ var Index = class _Index {
2066
2069
  return reduction;
2067
2070
  }
2068
2071
  /** Build an Index from its `IndexDef` JSON. */
2069
- static from(json) {
2070
- return new _Index(json.exprs.map((p) => new IndexPart(p.expr, p.count)), json.bytes);
2072
+ static from(json2) {
2073
+ return new _Index(json2.exprs.map((p) => new IndexPart(p.expr, p.count)), json2.bytes);
2071
2074
  }
2072
2075
  /** Serialize to its `IndexDef` JSON shape (emitting `bytes` only when authored explicitly). */
2073
2076
  toJSON() {
@@ -2279,24 +2282,24 @@ var Type = class _Type {
2279
2282
  return this.search || this.fields.some((f) => this.isFieldSearchable(f));
2280
2283
  }
2281
2284
  /** Build a Type from its JSON, parsing fields/indexes via `registry`. */
2282
- static from(json, registry) {
2283
- const fields = json.fields.map((fd) => Field.from(fd, registry));
2284
- const indexes = (json.indexes ?? []).map((id) => Index.from(id));
2285
+ static from(json2, registry) {
2286
+ const fields = json2.fields.map((fd) => Field.from(fd, registry));
2287
+ const indexes = (json2.indexes ?? []).map((id) => Index.from(id));
2285
2288
  return new _Type({
2286
- name: json.name,
2287
- label: json.label,
2288
- description: json.description,
2289
+ name: json2.name,
2290
+ label: json2.label,
2291
+ description: json2.description,
2289
2292
  fields,
2290
2293
  indexes,
2291
- identity: json.identity,
2292
- count: json.count,
2293
- bytes: json.bytes,
2294
- changes: json.changes,
2295
- semantic: json.semantic,
2296
- search: json.search,
2297
- insertable: json.insertable,
2298
- updatable: json.updatable,
2299
- deletable: json.deletable
2294
+ identity: json2.identity,
2295
+ count: json2.count,
2296
+ bytes: json2.bytes,
2297
+ changes: json2.changes,
2298
+ semantic: json2.semantic,
2299
+ search: json2.search,
2300
+ insertable: json2.insertable,
2301
+ updatable: json2.updatable,
2302
+ deletable: json2.deletable
2300
2303
  });
2301
2304
  }
2302
2305
  /** Zod schema for the `TypeDef` JSON shape. */
@@ -2874,58 +2877,66 @@ var INVALID = /* @__PURE__ */ Symbol("invalid");
2874
2877
  function isRecord3(value2) {
2875
2878
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
2876
2879
  }
2877
- function gotTail(json) {
2878
- const got = describeInput(json);
2880
+ function gotTail(json2) {
2881
+ const got = describeInput(json2);
2879
2882
  return got !== void 0 ? `, got ${got}` : "";
2880
2883
  }
2881
- function expected(aid, json) {
2882
- return `expected ${aidInfo(aid).label}${gotTail(json)}`;
2884
+ function expected(aid, json2) {
2885
+ return `expected ${aidInfo(aid).label}${gotTail(json2)}`;
2883
2886
  }
2884
2887
  function lit(value2) {
2885
2888
  return {
2886
- check(json, ctx) {
2887
- if (json === value2) return value2;
2888
- ctx.problems.error("shape.literal", `expected ${JSON.stringify(value2)}${gotTail(json)}`);
2889
+ check(json2, ctx) {
2890
+ if (json2 === value2) return value2;
2891
+ ctx.problems.error("shape.literal", `expected ${JSON.stringify(value2)}${gotTail(json2)}`);
2889
2892
  return INVALID;
2890
2893
  }
2891
2894
  };
2892
2895
  }
2893
2896
  function str(aid) {
2894
2897
  return {
2895
- check(json, ctx) {
2896
- if (typeof json === "string") return json;
2897
- ctx.problems.error("shape.type", expected(aid, json));
2898
+ check(json2, ctx) {
2899
+ if (typeof json2 === "string") return json2;
2900
+ ctx.problems.error("shape.type", expected(aid, json2));
2898
2901
  return INVALID;
2899
2902
  }
2900
2903
  };
2901
2904
  }
2902
2905
  function bool(aid) {
2903
2906
  return {
2904
- check(json, ctx) {
2905
- if (typeof json === "boolean") return json;
2906
- ctx.problems.error("shape.type", expected(aid, json));
2907
+ check(json2, ctx) {
2908
+ if (typeof json2 === "boolean") return json2;
2909
+ ctx.problems.error("shape.type", expected(aid, json2));
2907
2910
  return INVALID;
2908
2911
  }
2909
2912
  };
2910
2913
  }
2911
- function scalar(aid) {
2914
+ function json(aid) {
2912
2915
  return {
2913
- check(json, ctx) {
2914
- if (json === null || typeof json === "string" || typeof json === "number" || typeof json === "boolean") {
2915
- return json;
2916
- }
2917
- ctx.problems.error("shape.type", expected(aid, json));
2916
+ check(value2, ctx) {
2917
+ if (isJsonValue(value2, JSON_MAX_DEPTH)) return value2;
2918
+ ctx.problems.error("shape.type", expected(aid, value2));
2918
2919
  return INVALID;
2919
2920
  }
2920
2921
  };
2921
2922
  }
2923
+ var JSON_MAX_DEPTH = 64;
2924
+ function isJsonValue(value2, depth) {
2925
+ if (value2 === null || typeof value2 === "string" || typeof value2 === "boolean") return true;
2926
+ if (typeof value2 === "number") return Number.isFinite(value2);
2927
+ if (depth <= 0 || typeof value2 !== "object") return false;
2928
+ if (Array.isArray(value2)) return value2.every((v) => isJsonValue(v, depth - 1));
2929
+ const proto = Object.getPrototypeOf(value2);
2930
+ if (proto !== Object.prototype && proto !== null) return false;
2931
+ return Object.values(value2).every((v) => isJsonValue(v, depth - 1));
2932
+ }
2922
2933
  function enumOf(values, aid) {
2923
2934
  return {
2924
- check(json, ctx) {
2925
- if (typeof json === "string") {
2926
- for (const v of values) if (v === json) return v;
2935
+ check(json2, ctx) {
2936
+ if (typeof json2 === "string") {
2937
+ for (const v of values) if (v === json2) return v;
2927
2938
  }
2928
- const suggestion = typeof json === "string" ? didYouMean(json, values) : "";
2939
+ const suggestion = typeof json2 === "string" ? didYouMean(json2, values) : "";
2929
2940
  ctx.problems.error("shape.enum", `expected ${aidInfo(aid).label}: ${values.join(", ")}${suggestion}`);
2930
2941
  return INVALID;
2931
2942
  }
@@ -2933,24 +2944,24 @@ function enumOf(values, aid) {
2933
2944
  }
2934
2945
  function list(shape, opts = {}) {
2935
2946
  return {
2936
- check(json, ctx) {
2937
- if (!Array.isArray(json)) {
2938
- ctx.problems.error("shape.array", `expected a list${gotTail(json)}`);
2947
+ check(json2, ctx) {
2948
+ if (!Array.isArray(json2)) {
2949
+ ctx.problems.error("shape.array", `expected a list${gotTail(json2)}`);
2939
2950
  return INVALID;
2940
2951
  }
2941
2952
  const out = [];
2942
2953
  let ok = true;
2943
- json.forEach((element, i) => {
2954
+ json2.forEach((element, i) => {
2944
2955
  const value2 = ctx.problems.at(i, () => shape.check(element, ctx));
2945
2956
  if (value2 === INVALID) ok = false;
2946
2957
  else out.push(value2);
2947
2958
  });
2948
- if (opts.min !== void 0 && json.length < opts.min) {
2949
- ctx.problems.error("shape.min", `expected at least ${opts.min} item${opts.min === 1 ? "" : "s"}, got ${json.length}`);
2959
+ if (opts.min !== void 0 && json2.length < opts.min) {
2960
+ ctx.problems.error("shape.min", `expected at least ${opts.min} item${opts.min === 1 ? "" : "s"}, got ${json2.length}`);
2950
2961
  ok = false;
2951
2962
  }
2952
- if (opts.max !== void 0 && json.length > opts.max) {
2953
- ctx.problems.error("shape.max", `expected at most ${opts.max} item${opts.max === 1 ? "" : "s"}, got ${json.length}`);
2963
+ if (opts.max !== void 0 && json2.length > opts.max) {
2964
+ ctx.problems.error("shape.max", `expected at most ${opts.max} item${opts.max === 1 ? "" : "s"}, got ${json2.length}`);
2954
2965
  ok = false;
2955
2966
  }
2956
2967
  return ok ? out : INVALID;
@@ -2959,15 +2970,15 @@ function list(shape, opts = {}) {
2959
2970
  }
2960
2971
  function record(shape, aid) {
2961
2972
  return {
2962
- check(json, ctx) {
2963
- if (!isRecord3(json)) {
2964
- ctx.problems.error("shape.not-object", expected(aid, json));
2973
+ check(json2, ctx) {
2974
+ if (!isRecord3(json2)) {
2975
+ ctx.problems.error("shape.not-object", expected(aid, json2));
2965
2976
  return INVALID;
2966
2977
  }
2967
2978
  const out = /* @__PURE__ */ new Map();
2968
2979
  let ok = true;
2969
- for (const key of Object.keys(json)) {
2970
- const value2 = ctx.problems.at(key, () => shape.check(json[key], ctx));
2980
+ for (const key of Object.keys(json2)) {
2981
+ const value2 = ctx.problems.at(key, () => shape.check(json2[key], ctx));
2971
2982
  if (value2 === INVALID) ok = false;
2972
2983
  else out.set(key, value2);
2973
2984
  }
@@ -2977,32 +2988,32 @@ function record(shape, aid) {
2977
2988
  }
2978
2989
  function exprRef() {
2979
2990
  return {
2980
- check(json, ctx) {
2981
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
2991
+ check(json2, ctx) {
2992
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
2982
2993
  return built === void 0 ? INVALID : built;
2983
2994
  }
2984
2995
  };
2985
2996
  }
2986
2997
  function queryRef() {
2987
2998
  return {
2988
- check(json, ctx) {
2989
- const built = ctx.registry.parseCheckedQuery(json, ctx.problems);
2999
+ check(json2, ctx) {
3000
+ const built = ctx.registry.parseCheckedQuery(json2, ctx.problems);
2990
3001
  return built === void 0 ? INVALID : built;
2991
3002
  }
2992
3003
  };
2993
3004
  }
2994
3005
  function queryDefRef() {
2995
3006
  return {
2996
- check(json, ctx) {
2997
- const built = ctx.registry.parseCheckedQuery(json, ctx.problems);
3007
+ check(json2, ctx) {
3008
+ const built = ctx.registry.parseCheckedQuery(json2, ctx.problems);
2998
3009
  return built === void 0 ? INVALID : built.toJSON();
2999
3010
  }
3000
3011
  };
3001
3012
  }
3002
3013
  function sourceRef() {
3003
3014
  return {
3004
- check(json, ctx) {
3005
- const built = ctx.registry.parseCheckedSource(json, ctx.problems);
3015
+ check(json2, ctx) {
3016
+ const built = ctx.registry.parseCheckedSource(json2, ctx.problems);
3006
3017
  return built === void 0 ? INVALID : built;
3007
3018
  }
3008
3019
  };
@@ -3015,22 +3026,22 @@ function obj(fields, build, opts = {}) {
3015
3026
  const keys = Object.keys(fields);
3016
3027
  const required = keys.filter((key) => !optionalKeys.has(key));
3017
3028
  return {
3018
- check(json, ctx) {
3019
- if (!isRecord3(json)) {
3020
- ctx.problems.error("shape.not-object", expected(opts.aid ?? "Expr", json));
3029
+ check(json2, ctx) {
3030
+ if (!isRecord3(json2)) {
3031
+ ctx.problems.error("shape.not-object", expected(opts.aid ?? "Expr", json2));
3021
3032
  return INVALID;
3022
3033
  }
3023
3034
  const acc = {};
3024
3035
  const checkKey = (key) => {
3025
3036
  const shape = fields[key];
3026
3037
  ctx.problems.at(key, () => {
3027
- if (!(key in json)) {
3038
+ if (!(key in json2)) {
3028
3039
  if (!optionalKeys.has(key)) {
3029
3040
  ctx.problems.error("shape.required", `missing required field \`${key}\``);
3030
3041
  }
3031
3042
  return;
3032
3043
  }
3033
- const value2 = shape.check(json[key], ctx);
3044
+ const value2 = shape.check(json2[key], ctx);
3034
3045
  if (value2 !== INVALID) acc[key] = value2;
3035
3046
  });
3036
3047
  };
@@ -3049,8 +3060,9 @@ import { z as z15 } from "zod";
3049
3060
 
3050
3061
  // src/exprs/_shared.ts
3051
3062
  import { z as z14 } from "zod";
3052
- function computed(fieldType, sources, nullable, aggregate2) {
3053
- return { kind: "computed", fieldType, sources, nullable, aggregate: aggregate2 };
3063
+ function computed(fieldType, sources, nullable, aggregate2, aggregateFn) {
3064
+ const rt = { kind: "computed", fieldType, sources, nullable, aggregate: aggregate2 };
3065
+ return aggregateFn === void 0 ? rt : { ...rt, aggregateFn };
3054
3066
  }
3055
3067
  function boolResult(sources, nullable, aggregate2 = false) {
3056
3068
  return computed(new BoolFieldType(), sources, nullable, aggregate2);
@@ -3241,7 +3253,7 @@ var SqlContext = class _SqlContext {
3241
3253
 
3242
3254
  // src/exprs/literal.ts
3243
3255
  var LiteralExpr = class _LiteralExpr extends Expr {
3244
- /** Wrap a constant scalar value (`string | number | boolean | null`). */
3256
+ /** Wrap a constant value: a scalar, or a whole JSON document. */
3245
3257
  constructor(value2) {
3246
3258
  super();
3247
3259
  this.value = value2;
@@ -3249,14 +3261,14 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3249
3261
  value;
3250
3262
  static KIND = "literal";
3251
3263
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3252
- static INSTRUCTIONS = "A constant scalar value.";
3264
+ static INSTRUCTIONS = "A constant value: a scalar (string / number / boolean / null), or a whole JSON DOCUMENT (object / array) for a `json` / `array` field \u2014 which is how a write cell carries one. A document is bound as ONE parameter, never interpolated.";
3253
3265
  kind = _LiteralExpr.KIND;
3254
3266
  /** Reconstruct a LiteralExpr from its JSON def (validates the `kind` discriminant). */
3255
- static from(json, _registry) {
3256
- if (json.kind !== "literal") {
3257
- throw new Error(`LiteralExpr.from: expected 'literal', got '${json.kind}'`);
3267
+ static from(json2, _registry) {
3268
+ if (json2.kind !== "literal") {
3269
+ throw new Error(`LiteralExpr.from: expected 'literal', got '${json2.kind}'`);
3258
3270
  }
3259
- return new _LiteralExpr(json.value);
3271
+ return new _LiteralExpr(json2.value);
3260
3272
  }
3261
3273
  /**
3262
3274
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -3266,7 +3278,7 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3266
3278
  static SHAPE = obj(
3267
3279
  {
3268
3280
  kind: lit("literal"),
3269
- value: scalar("ScalarValue")
3281
+ value: json("LiteralValue")
3270
3282
  },
3271
3283
  (v) => new _LiteralExpr(v.value),
3272
3284
  { aid: "Expr_literal" }
@@ -3276,10 +3288,10 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3276
3288
  return withAid(
3277
3289
  z15.object({
3278
3290
  kind: z15.literal("literal"),
3279
- value: withAid(z15.union([z15.string(), z15.number(), z15.boolean(), z15.null()]), "ScalarValue")
3291
+ value: withAid(jsonValueSchema(), "LiteralValue")
3280
3292
  }),
3281
3293
  "Expr_literal"
3282
- ).describe("A constant scalar value.");
3294
+ ).describe("A constant value: a scalar, or a whole JSON document for a json / array field.");
3283
3295
  }
3284
3296
  /** Whether this is the SQL `NULL` literal. */
3285
3297
  isNullLiteral() {
@@ -3290,11 +3302,14 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3290
3302
  if (this.value === null) {
3291
3303
  return computed(new TextFieldType(), [], true, false);
3292
3304
  }
3305
+ if (Array.isArray(this.value)) return computed(new ArrayFieldType(), [], false, false);
3293
3306
  switch (typeof this.value) {
3294
3307
  case "number":
3295
3308
  return computed(new NumberFieldType(), [], false, false);
3296
3309
  case "boolean":
3297
3310
  return computed(new BoolFieldType(), [], false, false);
3311
+ case "object":
3312
+ return computed(new JsonFieldType(), [], false, false);
3298
3313
  default:
3299
3314
  return computed(new TextFieldType(), [], false, false);
3300
3315
  }
@@ -3312,9 +3327,20 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3312
3327
  async evaluate() {
3313
3328
  return Value.of(this.value);
3314
3329
  }
3315
- /** Emit as a SqlText fragment — `NULL` keyword or a bound param. */
3316
- toSQL(_dialect, _ctx) {
3317
- return this.value === null ? SqlText.raw("NULL") : SqlText.param(this.value);
3330
+ /**
3331
+ * Emit as a SqlText fragment — `NULL` keyword, a bound scalar param, or a
3332
+ * bound DOCUMENT.
3333
+ *
3334
+ * A document has no target field type HERE (a bare literal in a WHERE knows
3335
+ * only its own shape), so it binds through the dialect's default json type.
3336
+ * The WRITE path emits its cells through `writeCellSql`, which supplies the
3337
+ * target COLUMN's field type — the difference between a Postgres `jsonb` cast
3338
+ * and the `ARRAY[…]::text[]` a native array column actually needs.
3339
+ */
3340
+ toSQL(dialect, _ctx) {
3341
+ if (this.value === null) return SqlText.raw("NULL");
3342
+ if (typeof this.value === "object") return dialect.jsonValue(this.value);
3343
+ return SqlText.param(this.value);
3318
3344
  }
3319
3345
  /** Serialize back to its JSON ExprDef. */
3320
3346
  toJSON() {
@@ -3344,11 +3370,11 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
3344
3370
  static INSTRUCTIONS = "References a projected SELECT output field by name (valid ONLY in groupBy/orderBy/having); expands to that item's expr.";
3345
3371
  kind = _OutputRefExpr.KIND;
3346
3372
  /** Reconstruct an OutputRefExpr from its JSON def (validates the `kind` discriminant). */
3347
- static from(json, _registry) {
3348
- if (json.kind !== "output") {
3349
- throw new Error(`OutputRefExpr.from: expected 'output', got '${json.kind}'`);
3373
+ static from(json2, _registry) {
3374
+ if (json2.kind !== "output") {
3375
+ throw new Error(`OutputRefExpr.from: expected 'output', got '${json2.kind}'`);
3350
3376
  }
3351
- return new _OutputRefExpr(json.name);
3377
+ return new _OutputRefExpr(json2.name);
3352
3378
  }
3353
3379
  /**
3354
3380
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -3928,14 +3954,14 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
3928
3954
  field;
3929
3955
  static KIND = "field-ref";
3930
3956
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3931
- static INSTRUCTIONS = "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a RELATION field resolves to the whole related row, NOT a scalar: to READ a related scalar, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. To CORRELATE a subquery, join the relation and compare the joined key \u2014 do NOT compare a relation field-ref to an id/scalar. A relation field-ref may only be compared to ANOTHER relation of the same target.";
3957
+ static INSTRUCTIONS = "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a BELONGS-TO RELATION field IS a value: it projects the relation's IDENTITY \u2014 the target's key read off THIS row's own key column(s), as an object keyed by the target's identity field names (`{id:'u1'}`, `{tenantId:3,userId:1}`), NULL when unset \u2014 planning NO join and applying no target scope. Legal in `fields` / `RETURNING`, `order`, `groupBy`, `is null`, and an identity `=` / `<>` / `in`. To read any OTHER field of the target, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. A HAS-MANY ref is REFUSED (`ref.relation-has-many`) \u2014 it has no key on this row and its value is a SET: join it, or test membership against a target key. A relation is still NOT a value as an arithmetic operand / `case` arm / function argument / aggregate; and to CORRELATE a subquery, join the relation and compare the joined key \u2014 never a relation field-ref against an id/scalar.";
3932
3958
  kind = _FieldRefExpr.KIND;
3933
3959
  /** Reconstruct a FieldRefExpr from its JSON def (validates the `kind` discriminant). */
3934
- static from(json, _registry) {
3935
- if (json.kind !== "field-ref") {
3936
- throw new Error(`FieldRefExpr.from: expected 'field-ref', got '${json.kind}'`);
3960
+ static from(json2, _registry) {
3961
+ if (json2.kind !== "field-ref") {
3962
+ throw new Error(`FieldRefExpr.from: expected 'field-ref', got '${json2.kind}'`);
3937
3963
  }
3938
- return new _FieldRefExpr(json.source, json.field);
3964
+ return new _FieldRefExpr(json2.source, json2.field);
3939
3965
  }
3940
3966
  /**
3941
3967
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -4415,11 +4441,11 @@ var ParamExpr = class _ParamExpr extends Expr {
4415
4441
  static INSTRUCTIONS = "A named bind parameter; type inferred from use, bound at run/emit time.";
4416
4442
  kind = _ParamExpr.KIND;
4417
4443
  /** Reconstruct a ParamExpr from its JSON def (validates the `kind` discriminant). */
4418
- static from(json, _registry) {
4419
- if (json.kind !== "param") {
4420
- throw new Error(`ParamExpr.from: expected 'param', got '${json.kind}'`);
4444
+ static from(json2, _registry) {
4445
+ if (json2.kind !== "param") {
4446
+ throw new Error(`ParamExpr.from: expected 'param', got '${json2.kind}'`);
4421
4447
  }
4422
- return new _ParamExpr(json.name);
4448
+ return new _ParamExpr(json2.name);
4423
4449
  }
4424
4450
  /**
4425
4451
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -4466,10 +4492,26 @@ var ParamExpr = class _ParamExpr extends Expr {
4466
4492
  async evaluate(ctx) {
4467
4493
  return ctx.param(this.name);
4468
4494
  }
4469
- /** Emit as a bound SqlText param slot (null until a value is supplied). */
4470
- toSQL(_dialect, ctx) {
4495
+ /**
4496
+ * Emit as a bound SqlText param slot (NULL until a value is supplied).
4497
+ *
4498
+ * A NON-SCALAR bound value — a JSON document, or a relation `{ pk }` object
4499
+ * that reached here undecomposed — binds through `Dialect.jsonValue`, NOT as
4500
+ * NULL. Binding NULL was the worst outcome available (A9): the statement
4501
+ * SUCCEEDED and the supplied value was silently dropped, so an INSERT of a
4502
+ * `json` column through a param appeared to work and lost the data. A
4503
+ * relation comparison still decomposes its `{ pk }` object into per-column
4504
+ * binds before reaching here, so that path is unchanged; anything that DOES
4505
+ * get here is a value the caller supplied, and is bound as one.
4506
+ *
4507
+ * A write CELL routes through `writeCellSql` first, which also knows the
4508
+ * target column's field type; this is the fallback for every other position,
4509
+ * which knows only the value's own shape.
4510
+ */
4511
+ toSQL(dialect, ctx) {
4471
4512
  const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, this.name) ? ctx.params[this.name] : null;
4472
- const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
4513
+ if (raw2 !== null && raw2 !== void 0 && typeof raw2 === "object") return dialect.jsonValue(raw2);
4514
+ const value2 = raw2 ?? null;
4473
4515
  return SqlText.param(value2);
4474
4516
  }
4475
4517
  /** Serialize back to its JSON ExprDef. */
@@ -4804,15 +4846,15 @@ var SorterExpr = class _SorterExpr extends Expr {
4804
4846
  static INSTRUCTIONS = "A dynamic-sort catalog for a SELECT `order`: declare named `sorts` (+ optional `defaultSort`); the caller picks the sort at execution time.";
4805
4847
  kind = _SorterExpr.KIND;
4806
4848
  /** Reconstruct a SorterExpr from its JSON def (validates the `kind` discriminant). */
4807
- static from(json, registry) {
4808
- if (json.kind !== "sorter") {
4809
- throw new Error(`SorterExpr.from: expected 'sorter', got '${json.kind}'`);
4849
+ static from(json2, registry) {
4850
+ if (json2.kind !== "sorter") {
4851
+ throw new Error(`SorterExpr.from: expected 'sorter', got '${json2.kind}'`);
4810
4852
  }
4811
4853
  const sorts = /* @__PURE__ */ new Map();
4812
- for (const name of Object.keys(json.sorts)) {
4813
- sorts.set(name, registry.parseExpr(json.sorts[name]));
4854
+ for (const name of Object.keys(json2.sorts)) {
4855
+ sorts.set(name, registry.parseExpr(json2.sorts[name]));
4814
4856
  }
4815
- const defaultSort = json.defaultSort ? json.defaultSort.map((d) => ({ ...d })) : void 0;
4857
+ const defaultSort = json2.defaultSort ? json2.defaultSort.map((d) => ({ ...d })) : void 0;
4816
4858
  return new _SorterExpr(sorts, defaultSort);
4817
4859
  }
4818
4860
  /**
@@ -5010,14 +5052,14 @@ var BinaryExpr = class _BinaryExpr extends Expr {
5010
5052
  static INSTRUCTIONS = "Arithmetic `left <op> right` (`+ - * / %`).";
5011
5053
  kind = _BinaryExpr.KIND;
5012
5054
  /** Reconstruct a BinaryExpr from its JSON def (validates the `kind` discriminant). */
5013
- static from(json, registry) {
5014
- if (json.kind !== "binary") {
5015
- throw new Error(`BinaryExpr.from: expected 'binary', got '${json.kind}'`);
5055
+ static from(json2, registry) {
5056
+ if (json2.kind !== "binary") {
5057
+ throw new Error(`BinaryExpr.from: expected 'binary', got '${json2.kind}'`);
5016
5058
  }
5017
5059
  return new _BinaryExpr(
5018
- json.op,
5019
- registry.parseExpr(json.left),
5020
- registry.parseExpr(json.right)
5060
+ json2.op,
5061
+ registry.parseExpr(json2.left),
5062
+ registry.parseExpr(json2.right)
5021
5063
  );
5022
5064
  }
5023
5065
  /**
@@ -5178,11 +5220,11 @@ var UnaryExpr = class _UnaryExpr extends Expr {
5178
5220
  static INSTRUCTIONS = "`<op> operand` (`-` / `+`).";
5179
5221
  kind = _UnaryExpr.KIND;
5180
5222
  /** Reconstruct a UnaryExpr from its JSON def (validates the `kind` discriminant). */
5181
- static from(json, registry) {
5182
- if (json.kind !== "unary") {
5183
- throw new Error(`UnaryExpr.from: expected 'unary', got '${json.kind}'`);
5223
+ static from(json2, registry) {
5224
+ if (json2.kind !== "unary") {
5225
+ throw new Error(`UnaryExpr.from: expected 'unary', got '${json2.kind}'`);
5184
5226
  }
5185
- return new _UnaryExpr(json.op, registry.parseExpr(json.operand));
5227
+ return new _UnaryExpr(json2.op, registry.parseExpr(json2.operand));
5186
5228
  }
5187
5229
  /**
5188
5230
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -5346,14 +5388,14 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5346
5388
  static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION field-ref compares by IDENTITY with `=`/`<>` ONLY (ordering / LIKE on a relation is rejected). Its RHS may be (a) another relation of the SAME target \u2014 compared by FK key (`order.customer = invoice.customer`); or (b) a `{ pk }` VALUE param keyed by the target's primary-key fields (`assignedUser = :u` with `:u = {id:5}`); a single-key relation also accepts a bare scalar param. A BELONGS-TO compares the FK columns; a HAS-MANY compares by MEMBERSHIP \u2014 `= value` is TRUE when the value's key is in the related set (correlated EXISTS), `<>` is NOT EXISTS; a has-many may not be compared to another relation. Do NOT compare a relation to a scalar id COLUMN/field-ref (the correlation bug) \u2014 JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key.";
5347
5389
  kind = _ComparisonExpr.KIND;
5348
5390
  /** Reconstruct a ComparisonExpr from its JSON def (validates `kind`, recurses into operands via `registry.parseExpr`). */
5349
- static from(json, registry) {
5350
- if (json.kind !== "comparison") {
5351
- throw new Error(`ComparisonExpr.from: expected 'comparison', got '${json.kind}'`);
5391
+ static from(json2, registry) {
5392
+ if (json2.kind !== "comparison") {
5393
+ throw new Error(`ComparisonExpr.from: expected 'comparison', got '${json2.kind}'`);
5352
5394
  }
5353
5395
  return new _ComparisonExpr(
5354
- json.op,
5355
- registry.parseExpr(json.left),
5356
- registry.parseExpr(json.right)
5396
+ json2.op,
5397
+ registry.parseExpr(json2.left),
5398
+ registry.parseExpr(json2.right)
5357
5399
  );
5358
5400
  }
5359
5401
  /**
@@ -5592,13 +5634,13 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
5592
5634
  static INSTRUCTIONS = "Boolean connective `and` / `or` / `not` over operands.";
5593
5635
  kind = _LogicalExpr.KIND;
5594
5636
  /** Reconstruct a LogicalExpr from its JSON def (validates `kind`, recurses into operands via `registry.parseExpr`). */
5595
- static from(json, registry) {
5596
- if (json.kind !== "logical") {
5597
- throw new Error(`LogicalExpr.from: expected 'logical', got '${json.kind}'`);
5637
+ static from(json2, registry) {
5638
+ if (json2.kind !== "logical") {
5639
+ throw new Error(`LogicalExpr.from: expected 'logical', got '${json2.kind}'`);
5598
5640
  }
5599
5641
  return new _LogicalExpr(
5600
- json.op,
5601
- json.operands.map((o) => registry.parseExpr(o))
5642
+ json2.op,
5643
+ json2.operands.map((o) => registry.parseExpr(o))
5602
5644
  );
5603
5645
  }
5604
5646
  /**
@@ -5609,8 +5651,8 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
5609
5651
  * builds an expr equal to `from`'s output on a valid def. See `shape/`.
5610
5652
  */
5611
5653
  static SHAPE = {
5612
- check(json, ctx) {
5613
- const built = _LogicalExpr.SHAPE_OBJECT.check(json, ctx);
5654
+ check(json2, ctx) {
5655
+ const built = _LogicalExpr.SHAPE_OBJECT.check(json2, ctx);
5614
5656
  if (built === INVALID) return INVALID;
5615
5657
  if (built.op === "not" && built.operands.length !== 1) {
5616
5658
  ctx.problems.at(
@@ -5780,7 +5822,7 @@ var InExpr = class _InExpr extends BoolExpr {
5780
5822
  not;
5781
5823
  static KIND = "in";
5782
5824
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
5783
- static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. To project a value across a relation in the SUBQUERY form, add a `relation` join and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
5825
+ static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. A COMPOSITE-key relation may NOT use the subquery form (`in.relation-composite`) \u2014 one projected field cannot match a multi-column key, so list its `{ pk }` values instead. Inside the SUBQUERY, cross a relation with a `relation` join and field-ref the joined alias: projecting the relation field-ref itself yields its IDENTITY OBJECT, not a scalar id, and is refused here (`compare.relation-vs-value`). To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
5784
5826
  /**
5785
5827
  * Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
5786
5828
  * value LIST, and a single-field SUBQUERY that crosses a relation via a
@@ -5830,15 +5872,15 @@ var InExpr = class _InExpr extends BoolExpr {
5830
5872
  ];
5831
5873
  kind = _InExpr.KIND;
5832
5874
  /** Reconstruct an InExpr from its JSON def (validates `kind`; recurses into the value and any list elements via `registry.parseExpr`). */
5833
- static from(json, registry) {
5834
- if (json.kind !== "in") {
5835
- throw new Error(`InExpr.from: expected 'in', got '${json.kind}'`);
5875
+ static from(json2, registry) {
5876
+ if (json2.kind !== "in") {
5877
+ throw new Error(`InExpr.from: expected 'in', got '${json2.kind}'`);
5836
5878
  }
5837
- const value2 = registry.parseExpr(json.value);
5838
- if (Array.isArray(json.in)) {
5839
- return new _InExpr(value2, json.in.map((e2) => registry.parseExpr(e2)), void 0, json.not ?? false);
5879
+ const value2 = registry.parseExpr(json2.value);
5880
+ if (Array.isArray(json2.in)) {
5881
+ return new _InExpr(value2, json2.in.map((e2) => registry.parseExpr(e2)), void 0, json2.not ?? false);
5840
5882
  }
5841
- return new _InExpr(value2, void 0, json.in, json.not ?? false);
5883
+ return new _InExpr(value2, void 0, json2.in, json2.not ?? false);
5842
5884
  }
5843
5885
  /**
5844
5886
  * Owned structural {@link Shape} — the zod-free parallel parser. Dispatches on
@@ -5848,11 +5890,11 @@ var InExpr = class _InExpr extends BoolExpr {
5848
5890
  * to `from`'s output on a valid def. Never throws; accumulates. See `shape/`.
5849
5891
  */
5850
5892
  static SHAPE = {
5851
- check(json, ctx) {
5852
- if (isRecord3(json) && isRecord3(json["in"])) {
5853
- return _InExpr.SHAPE_SUBQUERY.check(json, ctx);
5893
+ check(json2, ctx) {
5894
+ if (isRecord3(json2) && isRecord3(json2["in"])) {
5895
+ return _InExpr.SHAPE_SUBQUERY.check(json2, ctx);
5854
5896
  }
5855
- return _InExpr.SHAPE_LIST.check(json, ctx);
5897
+ return _InExpr.SHAPE_LIST.check(json2, ctx);
5856
5898
  }
5857
5899
  };
5858
5900
  /** The LIST-form object shape dispatched to by {@link SHAPE}. */
@@ -6080,15 +6122,15 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
6080
6122
  static INSTRUCTIONS = "`value BETWEEN lower AND upper` (negatable).";
6081
6123
  kind = _BetweenExpr.KIND;
6082
6124
  /** Reconstruct a BetweenExpr from its JSON def (validates `kind`, recurses into value/lower/upper via `registry.parseExpr`). */
6083
- static from(json, registry) {
6084
- if (json.kind !== "between") {
6085
- throw new Error(`BetweenExpr.from: expected 'between', got '${json.kind}'`);
6125
+ static from(json2, registry) {
6126
+ if (json2.kind !== "between") {
6127
+ throw new Error(`BetweenExpr.from: expected 'between', got '${json2.kind}'`);
6086
6128
  }
6087
6129
  return new _BetweenExpr(
6088
- registry.parseExpr(json.value),
6089
- registry.parseExpr(json.lower),
6090
- registry.parseExpr(json.upper),
6091
- json.not ?? false
6130
+ registry.parseExpr(json2.value),
6131
+ registry.parseExpr(json2.lower),
6132
+ registry.parseExpr(json2.upper),
6133
+ json2.not ?? false
6092
6134
  );
6093
6135
  }
6094
6136
  /**
@@ -6229,14 +6271,14 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
6229
6271
  not;
6230
6272
  static KIND = "is-null";
6231
6273
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
6232
- static INSTRUCTIONS = "`value IS [NOT] NULL`.";
6274
+ static INSTRUCTIONS = "`value IS [NOT] NULL`. On a BELONGS-TO relation field-ref it tests whether the relation is UNSET \u2014 the KEY COLUMNS, so it stays index-usable; a HAS-MANY there is refused (`ref.relation-has-many`) \u2014 use `[NOT] EXISTS` over the related rows instead.";
6233
6275
  kind = _IsNullExpr.KIND;
6234
6276
  /** Reconstruct an IsNullExpr from its JSON def (validates `kind`, recurses into the value via `registry.parseExpr`). */
6235
- static from(json, registry) {
6236
- if (json.kind !== "is-null") {
6237
- throw new Error(`IsNullExpr.from: expected 'is-null', got '${json.kind}'`);
6277
+ static from(json2, registry) {
6278
+ if (json2.kind !== "is-null") {
6279
+ throw new Error(`IsNullExpr.from: expected 'is-null', got '${json2.kind}'`);
6238
6280
  }
6239
- return new _IsNullExpr(registry.parseExpr(json.value), json.not ?? false);
6281
+ return new _IsNullExpr(registry.parseExpr(json2.value), json2.not ?? false);
6240
6282
  }
6241
6283
  /**
6242
6284
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -6405,11 +6447,11 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
6405
6447
  ];
6406
6448
  kind = _ExistsExpr.KIND;
6407
6449
  /** Reconstruct an ExistsExpr from its JSON def (validates `kind`; the subquery is carried as-is). */
6408
- static from(json, _registry) {
6409
- if (json.kind !== "exists") {
6410
- throw new Error(`ExistsExpr.from: expected 'exists', got '${json.kind}'`);
6450
+ static from(json2, _registry) {
6451
+ if (json2.kind !== "exists") {
6452
+ throw new Error(`ExistsExpr.from: expected 'exists', got '${json2.kind}'`);
6411
6453
  }
6412
- return new _ExistsExpr(json.query, json.not ?? false);
6454
+ return new _ExistsExpr(json2.query, json2.not ?? false);
6413
6455
  }
6414
6456
  /**
6415
6457
  * Owned structural {@link Shape} — the zod-free parallel parser. Structurally
@@ -6490,9 +6532,9 @@ var ARRAY_OPS = [
6490
6532
  "notEmpty"
6491
6533
  ];
6492
6534
  var ARRAY_VALUE_SHAPE = {
6493
- check(json, ctx) {
6494
- if (Array.isArray(json)) return list(exprRef()).check(json, ctx);
6495
- const built = exprRef().check(json, ctx);
6535
+ check(json2, ctx) {
6536
+ if (Array.isArray(json2)) return list(exprRef()).check(json2, ctx);
6537
+ const built = exprRef().check(json2, ctx);
6496
6538
  return built === INVALID ? INVALID : [built];
6497
6539
  }
6498
6540
  };
@@ -6512,13 +6554,13 @@ var ArrayOpExpr = class _ArrayOpExpr extends BoolExpr {
6512
6554
  static INSTRUCTIONS = "Predicate over an array field: `contains` / `containsAny` / `containsAll` / `isEmpty` / `notEmpty`.";
6513
6555
  kind = _ArrayOpExpr.KIND;
6514
6556
  /** Reconstruct an ArrayOpExpr from its JSON def, recursing into target/values via the registry. */
6515
- static from(json, registry) {
6516
- if (json.kind !== "array-op") {
6517
- throw new Error(`ArrayOpExpr.from: expected 'array-op', got '${json.kind}'`);
6557
+ static from(json2, registry) {
6558
+ if (json2.kind !== "array-op") {
6559
+ throw new Error(`ArrayOpExpr.from: expected 'array-op', got '${json2.kind}'`);
6518
6560
  }
6519
- const target = registry.parseExpr(json.target);
6520
- const values = json.value === void 0 ? [] : Array.isArray(json.value) ? json.value.map((v) => registry.parseExpr(v)) : [registry.parseExpr(json.value)];
6521
- return new _ArrayOpExpr(json.op, target, values);
6561
+ const target = registry.parseExpr(json2.target);
6562
+ const values = json2.value === void 0 ? [] : Array.isArray(json2.value) ? json2.value.map((v) => registry.parseExpr(v)) : [registry.parseExpr(json2.value)];
6563
+ return new _ArrayOpExpr(json2.op, target, values);
6522
6564
  }
6523
6565
  /**
6524
6566
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -6733,15 +6775,15 @@ var CaseExpr = class _CaseExpr extends Expr {
6733
6775
  static INSTRUCTIONS = "`CASE WHEN \u2026 THEN \u2026 [ELSE \u2026] END`.";
6734
6776
  kind = _CaseExpr.KIND;
6735
6777
  /** Reconstruct a CaseExpr from its JSON def, recursing into each branch/else via the registry. */
6736
- static from(json, registry) {
6737
- if (json.kind !== "case") {
6738
- throw new Error(`CaseExpr.from: expected 'case', got '${json.kind}'`);
6778
+ static from(json2, registry) {
6779
+ if (json2.kind !== "case") {
6780
+ throw new Error(`CaseExpr.from: expected 'case', got '${json2.kind}'`);
6739
6781
  }
6740
- const branches = json.branches.map((b) => ({
6782
+ const branches = json2.branches.map((b) => ({
6741
6783
  when: registry.parseExpr(b.when),
6742
6784
  then: registry.parseExpr(b.then)
6743
6785
  }));
6744
- const els = json.else ? registry.parseExpr(json.else) : void 0;
6786
+ const els = json2.else ? registry.parseExpr(json2.else) : void 0;
6745
6787
  return new _CaseExpr(branches, els);
6746
6788
  }
6747
6789
  /**
@@ -6884,9 +6926,9 @@ import { z as z30 } from "zod";
6884
6926
 
6885
6927
  // src/exprs/_function-args.ts
6886
6928
  import { z as z29 } from "zod";
6887
- function parseNamedArgs(json, registry) {
6929
+ function parseNamedArgs(json2, registry) {
6888
6930
  const out = /* @__PURE__ */ new Map();
6889
- for (const [name, def] of Object.entries(json)) out.set(name, registry.parseExpr(def));
6931
+ for (const [name, def] of Object.entries(json2)) out.set(name, registry.parseExpr(def));
6890
6932
  return out;
6891
6933
  }
6892
6934
  function namedArgSchema(child) {
@@ -7023,7 +7065,7 @@ var AggregateExpr = class _AggregateExpr extends Expr {
7023
7065
  distinct;
7024
7066
  static KIND = "aggregate";
7025
7067
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
7026
- static INSTRUCTIONS = "An aggregate function over a group (`count(*)` = empty args); optional `distinct`.";
7068
+ static INSTRUCTIONS = "An aggregate function over a group (`count(*)` = empty args); optional `distinct`. A RELATION field-ref is NOT aggregable (`ref.relation-aggregate`) \u2014 its value is an IDENTITY: group by it, or aggregate a scalar off a `relation`-joined alias.";
7027
7069
  kind = _AggregateExpr.KIND;
7028
7070
  /** The conventional single `value` argument (absent for `count(*)`). */
7029
7071
  valueArg() {
@@ -7048,11 +7090,11 @@ var AggregateExpr = class _AggregateExpr extends Expr {
7048
7090
  return substituted ? engine.registry.parseExpr(substituted) : void 0;
7049
7091
  }
7050
7092
  /** Reconstruct an AggregateExpr from its JSON def, parsing named args via the registry. */
7051
- static from(json, registry) {
7052
- if (json.kind !== "aggregate") {
7053
- throw new Error(`AggregateExpr.from: expected 'aggregate', got '${json.kind}'`);
7093
+ static from(json2, registry) {
7094
+ if (json2.kind !== "aggregate") {
7095
+ throw new Error(`AggregateExpr.from: expected 'aggregate', got '${json2.kind}'`);
7054
7096
  }
7055
- return new _AggregateExpr(json.function, parseNamedArgs(json.args, registry), json.distinct ?? false);
7097
+ return new _AggregateExpr(json2.function, parseNamedArgs(json2.args, registry), json2.distinct ?? false);
7056
7098
  }
7057
7099
  /**
7058
7100
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -7091,16 +7133,26 @@ var AggregateExpr = class _AggregateExpr extends Expr {
7091
7133
  forEachChild(visit) {
7092
7134
  for (const a of this.args.values()) visit(a);
7093
7135
  }
7094
- /** Resolve to the function's declared output type, marked aggregate and nullable (except `count`). */
7136
+ /**
7137
+ * Resolve to the function's declared output type, marked aggregate and nullable
7138
+ * (except `count`), and carrying the APPLIED function's name.
7139
+ *
7140
+ * `aggregateFn` is set on BOTH roads — including the unknown-function fallback,
7141
+ * where the name is still the fact of what was written even though the
7142
+ * resolution is a placeholder. This is the ONE node that can answer "which
7143
+ * aggregate is this?": every wrapping expr reports `aggregate: true` from its
7144
+ * children without a single applied function, and `Function.resolveOutput`
7145
+ * never sets it, so nothing propagates a stale name upward.
7146
+ */
7095
7147
  resolve(engine, scope) {
7096
7148
  const fn2 = engine.lookupFunction(this.fn);
7097
7149
  if (!fn2) {
7098
- return computed(new NumberFieldType(), [], true, true);
7150
+ return computed(new NumberFieldType(), [], true, true, this.fn);
7099
7151
  }
7100
7152
  const base = fn2.resolveOutput(resolveNamedArgs(this.args, engine, scope));
7101
7153
  if (base.kind !== "computed") return base;
7102
7154
  const nullable = this.fn !== "count";
7103
- return { ...base, nullable, aggregate: true };
7155
+ return { ...base, nullable, aggregate: true, aggregateFn: this.fn };
7104
7156
  }
7105
7157
  /** Validate aggregate placement (not in WHERE, not nested) and the function's own named-arg checks. */
7106
7158
  validateWalk(engine, scope, p, ctx) {
@@ -7277,17 +7329,17 @@ var WindowExpr = class _WindowExpr extends Expr {
7277
7329
  ];
7278
7330
  kind = _WindowExpr.KIND;
7279
7331
  /** Reconstruct a WindowExpr from its JSON def, recursing into args/partition/order via the registry. */
7280
- static from(json, registry) {
7281
- if (json.kind !== "window") {
7282
- throw new Error(`WindowExpr.from: expected 'window', got '${json.kind}'`);
7332
+ static from(json2, registry) {
7333
+ if (json2.kind !== "window") {
7334
+ throw new Error(`WindowExpr.from: expected 'window', got '${json2.kind}'`);
7283
7335
  }
7284
- const partitionBy = (json.partitionBy ?? []).map((e2) => registry.parseExpr(e2));
7285
- const orderBy = (json.orderBy ?? []).map((o) => ({
7336
+ const partitionBy = (json2.partitionBy ?? []).map((e2) => registry.parseExpr(e2));
7337
+ const orderBy = (json2.orderBy ?? []).map((o) => ({
7286
7338
  expr: registry.parseExpr(o.expr),
7287
7339
  dir: o.dir,
7288
7340
  nulls: o.nulls
7289
7341
  }));
7290
- return new _WindowExpr(json.function, parseNamedArgs(json.args, registry), partitionBy, orderBy);
7342
+ return new _WindowExpr(json2.function, parseNamedArgs(json2.args, registry), partitionBy, orderBy);
7291
7343
  }
7292
7344
  /**
7293
7345
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -7533,11 +7585,11 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7533
7585
  ];
7534
7586
  kind = _FunctionCallExpr.KIND;
7535
7587
  /** Reconstruct a FunctionCallExpr from its JSON def, parsing named args via the registry. */
7536
- static from(json, registry) {
7537
- if (json.kind !== "function-call") {
7538
- throw new Error(`FunctionCallExpr.from: expected 'function-call', got '${json.kind}'`);
7588
+ static from(json2, registry) {
7589
+ if (json2.kind !== "function-call") {
7590
+ throw new Error(`FunctionCallExpr.from: expected 'function-call', got '${json2.kind}'`);
7539
7591
  }
7540
- return new _FunctionCallExpr(json.function, parseNamedArgs(json.args, registry));
7592
+ return new _FunctionCallExpr(json2.function, parseNamedArgs(json2.args, registry));
7541
7593
  }
7542
7594
  /**
7543
7595
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -7662,11 +7714,11 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7662
7714
  static INSTRUCTIONS = "A row-producing (table-valued) function call, usable as a source.";
7663
7715
  kind = _TabularFunctionCallExpr.KIND;
7664
7716
  /** Reconstruct a TabularFunctionCallExpr from its JSON def, parsing named args via the registry. */
7665
- static from(json, registry) {
7666
- if (json.kind !== "tabular-function-call") {
7667
- throw new Error(`TabularFunctionCallExpr.from: expected 'tabular-function-call', got '${json.kind}'`);
7717
+ static from(json2, registry) {
7718
+ if (json2.kind !== "tabular-function-call") {
7719
+ throw new Error(`TabularFunctionCallExpr.from: expected 'tabular-function-call', got '${json2.kind}'`);
7668
7720
  }
7669
- return new _TabularFunctionCallExpr(json.function, parseNamedArgs(json.args, registry));
7721
+ return new _TabularFunctionCallExpr(json2.function, parseNamedArgs(json2.args, registry));
7670
7722
  }
7671
7723
  /**
7672
7724
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -7864,18 +7916,18 @@ var SEMANTIC_TYPE_FIELD_SHAPE = obj(
7864
7916
  { aid: "SemanticQuery" }
7865
7917
  );
7866
7918
  var semanticQueryShape = {
7867
- check(json, ctx) {
7868
- if (typeof json === "string") return { kind: "text", text: json };
7869
- if (isRecord3(json)) {
7870
- if (json["kind"] === "param") {
7871
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
7919
+ check(json2, ctx) {
7920
+ if (typeof json2 === "string") return { kind: "text", text: json2 };
7921
+ if (isRecord3(json2)) {
7922
+ if (json2["kind"] === "param") {
7923
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
7872
7924
  if (built instanceof ParamExpr) return { kind: "param", param: built };
7873
7925
  return INVALID;
7874
7926
  }
7875
- if ("source" in json) return SEMANTIC_SOURCE_FIELD_SHAPE.check(json, ctx);
7876
- if ("type" in json) return SEMANTIC_TYPE_FIELD_SHAPE.check(json, ctx);
7927
+ if ("source" in json2) return SEMANTIC_SOURCE_FIELD_SHAPE.check(json2, ctx);
7928
+ if ("type" in json2) return SEMANTIC_TYPE_FIELD_SHAPE.check(json2, ctx);
7877
7929
  }
7878
- ctx.problems.error("shape.type", expected("SemanticQuery", json));
7930
+ ctx.problems.error("shape.type", expected("SemanticQuery", json2));
7879
7931
  return INVALID;
7880
7932
  }
7881
7933
  };
@@ -7910,11 +7962,11 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7910
7962
  static INSTRUCTIONS = "Embedding-similarity score of a source\u2019s row vs a query (string / param / pairing ref) \u2192 number.";
7911
7963
  kind = _SemanticExpr.KIND;
7912
7964
  /** Reconstruct a SemanticExpr from its JSON def (validates the `kind` discriminant). */
7913
- static from(json, registry) {
7914
- if (json.kind !== "semantic") {
7915
- throw new Error(`SemanticExpr.from: expected 'semantic', got '${json.kind}'`);
7965
+ static from(json2, registry) {
7966
+ if (json2.kind !== "semantic") {
7967
+ throw new Error(`SemanticExpr.from: expected 'semantic', got '${json2.kind}'`);
7916
7968
  }
7917
- return new _SemanticExpr(json.source, json.field, parseQuery(json.query, registry));
7969
+ return new _SemanticExpr(json2.source, json2.field, parseQuery(json2.query, registry));
7918
7970
  }
7919
7971
  /**
7920
7972
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8298,9 +8350,9 @@ function parseTextQuery(def, registry) {
8298
8350
  }
8299
8351
  function textQueryShape() {
8300
8352
  return {
8301
- check(json, ctx) {
8302
- if (typeof json === "string") return { kind: "text", text: json };
8303
- const built = ParamExpr.SHAPE.check(json, ctx);
8353
+ check(json2, ctx) {
8354
+ if (typeof json2 === "string") return { kind: "text", text: json2 };
8355
+ const built = ParamExpr.SHAPE.check(json2, ctx);
8304
8356
  return built === INVALID ? INVALID : { kind: "param", param: built };
8305
8357
  }
8306
8358
  };
@@ -8383,14 +8435,14 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
8383
8435
  query;
8384
8436
  static KIND = "text-search";
8385
8437
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
8386
- static INSTRUCTIONS = "Full-text predicate over a source (optionally one field) \u2192 boolean.";
8438
+ static INSTRUCTIONS = "Full-text predicate over a source (optionally one field) \u2192 boolean. NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source search is REFUSED (`text-search.unbacked`) rather than guessing a column.";
8387
8439
  kind = _TextSearchExpr.KIND;
8388
8440
  /** Reconstruct a TextSearchExpr from its JSON def (validates the `kind` discriminant). */
8389
- static from(json, registry) {
8390
- if (json.kind !== "text-search") {
8391
- throw new Error(`TextSearchExpr.from: expected 'text-search', got '${json.kind}'`);
8441
+ static from(json2, registry) {
8442
+ if (json2.kind !== "text-search") {
8443
+ throw new Error(`TextSearchExpr.from: expected 'text-search', got '${json2.kind}'`);
8392
8444
  }
8393
- return new _TextSearchExpr(json.source, json.field, parseTextQuery(json.query, registry));
8445
+ return new _TextSearchExpr(json2.source, json2.field, parseTextQuery(json2.query, registry));
8394
8446
  }
8395
8447
  /**
8396
8448
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8542,14 +8594,14 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
8542
8594
  query;
8543
8595
  static KIND = "text-score";
8544
8596
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
8545
- static INSTRUCTIONS = "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`).";
8597
+ static INSTRUCTIONS = "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`). NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source score is REFUSED (`text-score.unbacked`) rather than guessing a column.";
8546
8598
  kind = _TextScoreExpr.KIND;
8547
8599
  /** Reconstruct a TextScoreExpr from its JSON def (validates the `kind` discriminant). */
8548
- static from(json, registry) {
8549
- if (json.kind !== "text-score") {
8550
- throw new Error(`TextScoreExpr.from: expected 'text-score', got '${json.kind}'`);
8600
+ static from(json2, registry) {
8601
+ if (json2.kind !== "text-score") {
8602
+ throw new Error(`TextScoreExpr.from: expected 'text-score', got '${json2.kind}'`);
8551
8603
  }
8552
- return new _TextScoreExpr(json.source, json.field, parseTextQuery(json.query, registry));
8604
+ return new _TextScoreExpr(json2.source, json2.field, parseTextQuery(json2.query, registry));
8553
8605
  }
8554
8606
  /**
8555
8607
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8709,11 +8761,11 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
8709
8761
  static INSTRUCTIONS = "An execution-time filter placeholder bound to a source (optional `fields` allowlist); predicate supplied at run time.";
8710
8762
  kind = _FiltersExpr.KIND;
8711
8763
  /** Reconstruct a FiltersExpr from its JSON def (validates the `kind` discriminant). */
8712
- static from(json, _registry) {
8713
- if (json.kind !== "filters") {
8714
- throw new Error(`FiltersExpr.from: expected 'filters', got '${json.kind}'`);
8764
+ static from(json2, _registry) {
8765
+ if (json2.kind !== "filters") {
8766
+ throw new Error(`FiltersExpr.from: expected 'filters', got '${json2.kind}'`);
8715
8767
  }
8716
- return new _FiltersExpr(json.source, json.fields ? [...json.fields] : void 0);
8768
+ return new _FiltersExpr(json2.source, json2.fields ? [...json2.fields] : void 0);
8717
8769
  }
8718
8770
  /**
8719
8771
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8888,11 +8940,11 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
8888
8940
  ];
8889
8941
  kind = _SubqueryExpr.KIND;
8890
8942
  /** Reconstruct a SubqueryExpr from its JSON def (validates the `kind` discriminant). */
8891
- static from(json, _registry) {
8892
- if (json.kind !== "subquery") {
8893
- throw new Error(`SubqueryExpr.from: expected 'subquery', got '${json.kind}'`);
8943
+ static from(json2, _registry) {
8944
+ if (json2.kind !== "subquery") {
8945
+ throw new Error(`SubqueryExpr.from: expected 'subquery', got '${json2.kind}'`);
8894
8946
  }
8895
- return new _SubqueryExpr(json.query);
8947
+ return new _SubqueryExpr(json2.query);
8896
8948
  }
8897
8949
  /**
8898
8950
  * Owned structural {@link Shape} — the zod-free parallel parser. Structurally
@@ -8969,11 +9021,11 @@ var ExcludedExpr = class _ExcludedExpr extends Expr {
8969
9021
  static INSTRUCTIONS = '`EXCLUDED."field"` \u2014 the proposed row inside `INSERT \u2026 ON CONFLICT DO UPDATE`.';
8970
9022
  kind = _ExcludedExpr.KIND;
8971
9023
  /** Reconstruct an ExcludedExpr from its JSON def (validates the `kind` discriminant). */
8972
- static from(json, _registry) {
8973
- if (json.kind !== "excluded") {
8974
- throw new Error(`ExcludedExpr.from: expected 'excluded', got '${json.kind}'`);
9024
+ static from(json2, _registry) {
9025
+ if (json2.kind !== "excluded") {
9026
+ throw new Error(`ExcludedExpr.from: expected 'excluded', got '${json2.kind}'`);
8975
9027
  }
8976
- return new _ExcludedExpr(json.field);
9028
+ return new _ExcludedExpr(json2.field);
8977
9029
  }
8978
9030
  /**
8979
9031
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -9630,11 +9682,11 @@ var RELATION_ON_SHAPE = obj(
9630
9682
  { aid: "JoinOn" }
9631
9683
  );
9632
9684
  var JOIN_ON_SHAPE = {
9633
- check(json, ctx) {
9634
- if (isRecord3(json) && json["kind"] === "relation") {
9635
- return RELATION_ON_SHAPE.check(json, ctx);
9685
+ check(json2, ctx) {
9686
+ if (isRecord3(json2) && json2["kind"] === "relation") {
9687
+ return RELATION_ON_SHAPE.check(json2, ctx);
9636
9688
  }
9637
- const src = sourceRef().check(json, ctx);
9689
+ const src = sourceRef().check(json2, ctx);
9638
9690
  return src === INVALID ? INVALID : { kind: "source", source: src };
9639
9691
  }
9640
9692
  };
@@ -9911,20 +9963,24 @@ function reportDuplicateSources(p, sources) {
9911
9963
  }
9912
9964
 
9913
9965
  // src/queries/_write.ts
9914
- function isExprValue(v) {
9915
- return isRecord3(v) && typeof v["kind"] === "string";
9966
+ function isExprValue(v, registry) {
9967
+ if (!isRecord3(v) || typeof v["kind"] !== "string") return false;
9968
+ return registry === void 0 || registry.exprClass(v["kind"]) !== void 0;
9916
9969
  }
9917
9970
  function writeValueToExpr(v, registry) {
9918
9971
  if (v === null || v === void 0) return void 0;
9919
- if (isExprValue(v)) return registry.parseExpr(v);
9920
- if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") return new LiteralExpr(v);
9972
+ if (isExprValue(v, registry)) return registry.parseExpr(v);
9973
+ if (isJsonValue(v, JSON_MAX_DEPTH)) return new LiteralExpr(v);
9921
9974
  throw new QueryTypeError({
9922
9975
  path: [],
9923
9976
  code: "write.unsupported-value",
9924
9977
  severity: "error",
9925
- message: `Unsupported write value ${JSON.stringify(v)}; use a scalar or an expression.`
9978
+ message: `Unsupported write value ${describeUnsupported(v)}; use a JSON value or an expression.`
9926
9979
  });
9927
9980
  }
9981
+ function describeUnsupported(v) {
9982
+ return typeof v === "object" && v !== null ? Object.prototype.toString.call(v) : String(v);
9983
+ }
9928
9984
  function parseWriteRecord(record2, registry) {
9929
9985
  const out = /* @__PURE__ */ new Map();
9930
9986
  for (const key of Object.keys(record2)) {
@@ -9933,6 +9989,40 @@ function parseWriteRecord(record2, registry) {
9933
9989
  }
9934
9990
  return out;
9935
9991
  }
9992
+ function validateWriteValue(engine, scope, p, ctx, field, expr) {
9993
+ const resolved = expr.validateWalk(engine, scope, p, ctx);
9994
+ if (!field) return;
9995
+ if (expr instanceof ParamExpr) {
9996
+ scope.params.observe(expr.name, field.fieldType, p.here);
9997
+ return;
9998
+ }
9999
+ if (expr instanceof LiteralExpr && expr.isNullLiteral()) return;
10000
+ if (field.fieldType instanceof RelationFieldType) return;
10001
+ const valueType = asFieldType(resolved);
10002
+ if (valueType && !field.fieldType.comparableWith(valueType)) {
10003
+ p.error(
10004
+ "write.type",
10005
+ `Cannot write a ${valueType.resolve()} value to field '${field.name}' (${field.fieldType.resolve()}).`
10006
+ );
10007
+ }
10008
+ }
10009
+ function writeCellSql(expr, field, dialect, ctx) {
10010
+ const value2 = writeCellValue(expr, ctx);
10011
+ if (value2 !== void 0 && value2 !== null && (typeof value2 === "object" || isJsonColumn(field))) {
10012
+ return dialect.jsonValue(value2, field?.fieldType);
10013
+ }
10014
+ return expr.toSQL(dialect, ctx);
10015
+ }
10016
+ function isJsonColumn(field) {
10017
+ return field?.fieldType.resolve() === "json";
10018
+ }
10019
+ function writeCellValue(expr, ctx) {
10020
+ if (expr instanceof LiteralExpr) return expr.value;
10021
+ if (expr instanceof ParamExpr && Object.prototype.hasOwnProperty.call(ctx.params, expr.name)) {
10022
+ return ctx.params[expr.name];
10023
+ }
10024
+ return void 0;
10025
+ }
9936
10026
 
9937
10027
  // src/queries/_shape.ts
9938
10028
  function selectFieldShape() {
@@ -9944,16 +10034,14 @@ function selectFieldShape() {
9944
10034
  }
9945
10035
  function writeValueShape() {
9946
10036
  return {
9947
- check(json, ctx) {
9948
- if (json === null || json === void 0) return void 0;
9949
- if (isExprValue(json)) {
9950
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
10037
+ check(json2, ctx) {
10038
+ if (json2 === null || json2 === void 0) return void 0;
10039
+ if (isExprValue(json2, ctx.registry)) {
10040
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
9951
10041
  return built === void 0 ? INVALID : built;
9952
10042
  }
9953
- if (typeof json === "string" || typeof json === "number" || typeof json === "boolean") {
9954
- return new LiteralExpr(json);
9955
- }
9956
- ctx.problems.error("shape.type", expected("WriteValue", json));
10043
+ if (isJsonValue(json2, JSON_MAX_DEPTH)) return new LiteralExpr(json2);
10044
+ ctx.problems.error("shape.type", expected("WriteValue", json2));
9957
10045
  return INVALID;
9958
10046
  }
9959
10047
  };
@@ -9961,15 +10049,15 @@ function writeValueShape() {
9961
10049
  function writeRecordShape(aid) {
9962
10050
  const value2 = writeValueShape();
9963
10051
  return {
9964
- check(json, ctx) {
9965
- if (!isRecord3(json)) {
9966
- ctx.problems.error("shape.not-object", expected(aid, json));
10052
+ check(json2, ctx) {
10053
+ if (!isRecord3(json2)) {
10054
+ ctx.problems.error("shape.not-object", expected(aid, json2));
9967
10055
  return INVALID;
9968
10056
  }
9969
10057
  const out = /* @__PURE__ */ new Map();
9970
10058
  let ok = true;
9971
- for (const key of Object.keys(json)) {
9972
- const built = ctx.problems.at(key, () => value2.check(json[key], ctx));
10059
+ for (const key of Object.keys(json2)) {
10060
+ const built = ctx.problems.at(key, () => value2.check(json2[key], ctx));
9973
10061
  if (built === INVALID) ok = false;
9974
10062
  else if (built !== void 0) out.set(key, built);
9975
10063
  }
@@ -9979,14 +10067,14 @@ function writeRecordShape(aid) {
9979
10067
  }
9980
10068
  function boundShape() {
9981
10069
  return {
9982
- check(json, ctx) {
9983
- if (typeof json === "number") return json;
9984
- if (isRecord3(json) && json["kind"] === "param") {
9985
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
10070
+ check(json2, ctx) {
10071
+ if (typeof json2 === "number") return json2;
10072
+ if (isRecord3(json2) && json2["kind"] === "param") {
10073
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
9986
10074
  if (built instanceof ParamExpr) return built.toJSON();
9987
10075
  return INVALID;
9988
10076
  }
9989
- ctx.problems.error("shape.type", expected("Limit", json));
10077
+ ctx.problems.error("shape.type", expected("Limit", json2));
9990
10078
  return INVALID;
9991
10079
  }
9992
10080
  };
@@ -10669,8 +10757,8 @@ async function rowPassesDefaultConditions(active, row, ctx) {
10669
10757
 
10670
10758
  // src/queries/select.ts
10671
10759
  var orderItemShape = {
10672
- check(json, ctx) {
10673
- return isRecord3(json) && json["kind"] === "sorter" ? SorterExpr.SHAPE.check(json, ctx) : QueryOrder.SHAPE.check(json, ctx);
10760
+ check(json2, ctx) {
10761
+ return isRecord3(json2) && json2["kind"] === "sorter" ? SorterExpr.SHAPE.check(json2, ctx) : QueryOrder.SHAPE.check(json2, ctx);
10674
10762
  }
10675
10763
  };
10676
10764
  function parseOrderItem(def, registry) {
@@ -10806,19 +10894,19 @@ var SelectQuery = class _SelectQuery extends Query {
10806
10894
  /** This query's `kind` discriminant. */
10807
10895
  kind = _SelectQuery.KIND;
10808
10896
  /** Parse a `select` `QueryDef` into a `SelectQuery`. */
10809
- static from(json, registry) {
10810
- if (json.kind !== "select") throw new Error(`SelectQuery.from: expected 'select', got '${json.kind}'`);
10897
+ static from(json2, registry) {
10898
+ if (json2.kind !== "select") throw new Error(`SelectQuery.from: expected 'select', got '${json2.kind}'`);
10811
10899
  return new _SelectQuery(
10812
- json.distinct ?? false,
10813
- json.fields.map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as })),
10814
- QuerySource.from(json.from, registry),
10815
- (json.joins ?? []).map((j) => QueryJoin.from(j, registry)),
10816
- (json.where ?? []).map((w) => registry.parseExpr(w)),
10817
- (json.groupBy ?? []).map((g) => registry.parseExpr(g)),
10818
- (json.having ?? []).map((h) => registry.parseExpr(h)),
10819
- (json.order ?? []).map((o) => parseOrderItem(o, registry)),
10820
- json.limit,
10821
- json.offset
10900
+ json2.distinct ?? false,
10901
+ json2.fields.map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as })),
10902
+ QuerySource.from(json2.from, registry),
10903
+ (json2.joins ?? []).map((j) => QueryJoin.from(j, registry)),
10904
+ (json2.where ?? []).map((w) => registry.parseExpr(w)),
10905
+ (json2.groupBy ?? []).map((g) => registry.parseExpr(g)),
10906
+ (json2.having ?? []).map((h) => registry.parseExpr(h)),
10907
+ (json2.order ?? []).map((o) => parseOrderItem(o, registry)),
10908
+ json2.limit,
10909
+ json2.offset
10822
10910
  );
10823
10911
  }
10824
10912
  /**
@@ -11903,17 +11991,17 @@ var InsertQuery = class _InsertQuery extends Query {
11903
11991
  /** This query's `kind` discriminant. */
11904
11992
  kind = _InsertQuery.KIND;
11905
11993
  /** Parse an `insert` `QueryDef` into an `InsertQuery`. */
11906
- static from(json, registry) {
11907
- if (json.kind !== "insert") throw new Error(`InsertQuery.from: expected 'insert', got '${json.kind}'`);
11908
- const rows = json.rows?.map((r) => parseWriteRecord(r, registry));
11909
- const select = json.select ? registry.parseQuery(json.select) : void 0;
11910
- const returning = (json.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }));
11911
- const onConflict = json.onConflict ? {
11912
- fields: [...json.onConflict.fields],
11913
- doNothing: json.onConflict.doNothing ?? false,
11914
- update: toAssigns(parseWriteRecord(json.onConflict.update ?? {}, registry))
11994
+ static from(json2, registry) {
11995
+ if (json2.kind !== "insert") throw new Error(`InsertQuery.from: expected 'insert', got '${json2.kind}'`);
11996
+ const rows = json2.rows?.map((r) => parseWriteRecord(r, registry));
11997
+ const select = json2.select ? registry.parseQuery(json2.select) : void 0;
11998
+ const returning = (json2.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }));
11999
+ const onConflict = json2.onConflict ? {
12000
+ fields: [...json2.onConflict.fields],
12001
+ doNothing: json2.onConflict.doNothing ?? false,
12002
+ update: toAssigns(parseWriteRecord(json2.onConflict.update ?? {}, registry))
11915
12003
  } : void 0;
11916
- return new _InsertQuery(json.into, rows, select, returning, onConflict);
12004
+ return new _InsertQuery(json2.into, rows, select, returning, onConflict);
11917
12005
  }
11918
12006
  /**
11919
12007
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -12012,6 +12100,21 @@ var InsertQuery = class _InsertQuery extends Query {
12012
12100
  }
12013
12101
  });
12014
12102
  });
12103
+ const valueScope = this.targetScope(engine, scope);
12104
+ const valueCtx = {
12105
+ inAggregate: false,
12106
+ inWindow: false,
12107
+ allowAggregate: false,
12108
+ groupKeys: [],
12109
+ inGroupBy: false
12110
+ };
12111
+ p.at("rows", () => {
12112
+ this.rows.forEach((row, i) => {
12113
+ for (const [column2, expr] of row) {
12114
+ p.at([i, column2], () => validateWriteValue(engine, valueScope, p, valueCtx, type.field(column2), expr));
12115
+ }
12116
+ });
12117
+ });
12015
12118
  const missing = type.fields.filter((f) => !canonical.has(f.name) && requiredOnInsert(f, engine.fieldBacking(this.into, f.name))).map((f) => f.name);
12016
12119
  if (missing.length) {
12017
12120
  p.at(
@@ -12035,7 +12138,7 @@ var InsertQuery = class _InsertQuery extends Query {
12035
12138
  if (type && !type.field(u.field)) {
12036
12139
  p.at(u.field, () => p.error("insert.unknown-field", `Type '${this.into}' has no field '${u.field}'.${didYouMean(u.field, type.fields.map((f) => f.name))}`));
12037
12140
  }
12038
- p.at(u.field, () => u.expr.validateWalk(engine, conflictScope, p, assignCtx));
12141
+ p.at(u.field, () => validateWriteValue(engine, conflictScope, p, assignCtx, type.field(u.field), u.expr));
12039
12142
  });
12040
12143
  });
12041
12144
  }
@@ -12180,8 +12283,12 @@ var InsertQuery = class _InsertQuery extends Query {
12180
12283
  SqlText.raw(")")
12181
12284
  ];
12182
12285
  if (this.rows) {
12286
+ const target = ctx.engine.type(this.into);
12183
12287
  const tuples = this.rows.map(
12184
- (row) => SqlText.join(columns.map((c) => row.get(c).toSQL(dialect, ctx)), ", ").parens()
12288
+ (row) => SqlText.join(
12289
+ columns.map((c) => writeCellSql(row.get(c), target?.field(c), dialect, ctx)),
12290
+ ", "
12291
+ ).parens()
12185
12292
  );
12186
12293
  parts.push(SqlText.raw(" VALUES "), SqlText.join(tuples, ", "));
12187
12294
  } else if (this.select) {
@@ -12197,8 +12304,13 @@ var InsertQuery = class _InsertQuery extends Query {
12197
12304
  parts.push(SqlText.raw(" DO NOTHING"));
12198
12305
  } else {
12199
12306
  const conflictCtx = ctx.withScope(this.conflictScope(ctx.engine, ctx.scope));
12307
+ const conflictType = ctx.engine.type(this.into);
12200
12308
  const sets = this.onConflict.update.map(
12201
- (u) => SqlText.concat([dialect.ident(u.field), SqlText.raw(" = "), u.expr.toSQL(dialect, conflictCtx)])
12309
+ (u) => SqlText.concat([
12310
+ dialect.ident(u.field),
12311
+ SqlText.raw(" = "),
12312
+ writeCellSql(u.expr, conflictType?.field(u.field), dialect, conflictCtx)
12313
+ ])
12202
12314
  );
12203
12315
  parts.push(SqlText.raw(" DO UPDATE SET "), SqlText.join(sets, ", "));
12204
12316
  }
@@ -12273,14 +12385,14 @@ var UpdateQuery = class _UpdateQuery extends Query {
12273
12385
  /** This query's `kind` discriminant. */
12274
12386
  kind = _UpdateQuery.KIND;
12275
12387
  /** Parse an `update` `QueryDef` into an `UpdateQuery`. */
12276
- static from(json, registry) {
12277
- if (json.kind !== "update") throw new Error(`UpdateQuery.from: expected 'update', got '${json.kind}'`);
12388
+ static from(json2, registry) {
12389
+ if (json2.kind !== "update") throw new Error(`UpdateQuery.from: expected 'update', got '${json2.kind}'`);
12278
12390
  return new _UpdateQuery(
12279
- json.type,
12280
- [...parseWriteRecord(json.set, registry)].map(([field, expr]) => ({ field, expr })),
12281
- (json.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12282
- (json.where ?? []).map((w) => registry.parseExpr(w)),
12283
- (json.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12391
+ json2.type,
12392
+ [...parseWriteRecord(json2.set, registry)].map(([field, expr]) => ({ field, expr })),
12393
+ (json2.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12394
+ (json2.where ?? []).map((w) => registry.parseExpr(w)),
12395
+ (json2.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12284
12396
  );
12285
12397
  }
12286
12398
  /**
@@ -12384,7 +12496,7 @@ var UpdateQuery = class _UpdateQuery extends Query {
12384
12496
  } else if (!field.updatableFor(engine.fieldBacking(this.type, s.field))) {
12385
12497
  p.at([i, "field"], () => p.error("update.field-readonly", `Field '${s.field}' of '${this.type}' is not updatable.`));
12386
12498
  }
12387
- p.at([i, "value"], () => s.expr.validateWalk(engine, inner, p, ctx));
12499
+ p.at([i, "value"], () => validateWriteValue(engine, inner, p, ctx, field, s.expr));
12388
12500
  });
12389
12501
  });
12390
12502
  p.at("where", () => this.where.forEach((w, i) => p.at(i, () => {
@@ -12512,8 +12624,13 @@ var UpdateQuery = class _UpdateQuery extends Query {
12512
12624
  const planner = new JoinCtePlanner(dialect, engine, ctx.rls, ctx.params, true);
12513
12625
  const selCtx = ctx.withPlanner(inner, planner);
12514
12626
  this.registerJoins(dialect, engine, selCtx, planner, aliasTypes);
12627
+ const target = engine.type(this.type);
12515
12628
  const sets = this.set.map(
12516
- (s) => SqlText.concat([dialect.ident(s.field), SqlText.raw(" = "), s.expr.toSQL(dialect, selCtx)])
12629
+ (s) => SqlText.concat([
12630
+ dialect.ident(s.field),
12631
+ SqlText.raw(" = "),
12632
+ writeCellSql(s.expr, target?.field(s.field), dialect, selCtx)
12633
+ ])
12517
12634
  );
12518
12635
  const wherePreds = this.where.map((w) => w.toSQL(dialect, selCtx));
12519
12636
  const rls = rlsPredicate(ctx.rls, dialect, engine, planner, this.type, this.alias);
@@ -12582,13 +12699,13 @@ var DeleteQuery = class _DeleteQuery extends Query {
12582
12699
  /** This query's `kind` discriminant. */
12583
12700
  kind = _DeleteQuery.KIND;
12584
12701
  /** Parse a `delete` `QueryDef` into a `DeleteQuery`. */
12585
- static from(json, registry) {
12586
- if (json.kind !== "delete") throw new Error(`DeleteQuery.from: expected 'delete', got '${json.kind}'`);
12702
+ static from(json2, registry) {
12703
+ if (json2.kind !== "delete") throw new Error(`DeleteQuery.from: expected 'delete', got '${json2.kind}'`);
12587
12704
  return new _DeleteQuery(
12588
- json.from,
12589
- (json.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12590
- (json.where ?? []).map((w) => registry.parseExpr(w)),
12591
- (json.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12705
+ json2.from,
12706
+ (json2.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12707
+ (json2.where ?? []).map((w) => registry.parseExpr(w)),
12708
+ (json2.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12592
12709
  );
12593
12710
  }
12594
12711
  /**
@@ -12886,18 +13003,18 @@ var SetOperationQuery = class _SetOperationQuery extends Query {
12886
13003
  /** This instance's actual set operation (`union` / `intersect` / `except`). */
12887
13004
  kind;
12888
13005
  /** Parse a `union` / `intersect` / `except` `QueryDef` into a `SetOperationQuery`. */
12889
- static from(json, registry) {
12890
- if (json.kind !== "union" && json.kind !== "intersect" && json.kind !== "except") {
12891
- throw new Error(`SetOperationQuery.from: expected a set op, got '${json.kind}'`);
13006
+ static from(json2, registry) {
13007
+ if (json2.kind !== "union" && json2.kind !== "intersect" && json2.kind !== "except") {
13008
+ throw new Error(`SetOperationQuery.from: expected a set op, got '${json2.kind}'`);
12892
13009
  }
12893
13010
  return new _SetOperationQuery(
12894
- json.kind,
12895
- registry.parseQuery(json.left),
12896
- registry.parseQuery(json.right),
12897
- json.all ?? false,
12898
- (json.order ?? []).map((o) => QueryOrder.from(o, registry)),
12899
- json.limit,
12900
- json.offset
13011
+ json2.kind,
13012
+ registry.parseQuery(json2.left),
13013
+ registry.parseQuery(json2.right),
13014
+ json2.all ?? false,
13015
+ (json2.order ?? []).map((o) => QueryOrder.from(o, registry)),
13016
+ json2.limit,
13017
+ json2.offset
12901
13018
  );
12902
13019
  }
12903
13020
  /**
@@ -13251,11 +13368,11 @@ var RECURSIVE_ENTRY_SHAPE = obj(
13251
13368
  { aid: "CTEEntry" }
13252
13369
  );
13253
13370
  var cteEntryShape = {
13254
- check(json, ctx) {
13255
- if (isRecord3(json) && "base" in json && "recursive" in json) {
13256
- return RECURSIVE_ENTRY_SHAPE.check(json, ctx);
13371
+ check(json2, ctx) {
13372
+ if (isRecord3(json2) && "base" in json2 && "recursive" in json2) {
13373
+ return RECURSIVE_ENTRY_SHAPE.check(json2, ctx);
13257
13374
  }
13258
- return PLAIN_ENTRY_SHAPE.check(json, ctx);
13375
+ return PLAIN_ENTRY_SHAPE.check(json2, ctx);
13259
13376
  }
13260
13377
  };
13261
13378
  var CTEStatementQuery = class _CTEStatementQuery extends Query {
@@ -13361,10 +13478,10 @@ var CTEStatementQuery = class _CTEStatementQuery extends Query {
13361
13478
  /** This query's `kind` discriminant. */
13362
13479
  kind = _CTEStatementQuery.KIND;
13363
13480
  /** Parse a `cte` `QueryDef` into a `CTEStatementQuery`. */
13364
- static from(json, registry) {
13365
- if (json.kind !== "cte") throw new Error(`CTEStatementQuery.from: expected 'cte', got '${json.kind}'`);
13366
- const ctes = json.ctes.map((c) => parseEntry(c, registry));
13367
- return new _CTEStatementQuery(ctes, registry.parseQuery(json.final));
13481
+ static from(json2, registry) {
13482
+ if (json2.kind !== "cte") throw new Error(`CTEStatementQuery.from: expected 'cte', got '${json2.kind}'`);
13483
+ const ctes = json2.ctes.map((c) => parseEntry(c, registry));
13484
+ return new _CTEStatementQuery(ctes, registry.parseQuery(json2.final));
13368
13485
  }
13369
13486
  /**
13370
13487
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -13495,9 +13612,9 @@ var ExprQuery = class _ExprQuery extends Query {
13495
13612
  /** This query's `kind` discriminant. */
13496
13613
  kind = _ExprQuery.KIND;
13497
13614
  /** Parse an `expr` `QueryDef` into an `ExprQuery`. */
13498
- static from(json, registry) {
13499
- if (json.kind !== "expr") throw new Error(`ExprQuery.from: expected 'expr', got '${json.kind}'`);
13500
- return new _ExprQuery(registry.parseExpr(json.expr));
13615
+ static from(json2, registry) {
13616
+ if (json2.kind !== "expr") throw new Error(`ExprQuery.from: expected 'expr', got '${json2.kind}'`);
13617
+ return new _ExprQuery(registry.parseExpr(json2.expr));
13501
13618
  }
13502
13619
  /**
13503
13620
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -13690,6 +13807,35 @@ var Dialect = class {
13690
13807
  SqlText.raw(")")
13691
13808
  ]);
13692
13809
  }
13810
+ /**
13811
+ * Bind a whole JSON DOCUMENT (an object / array) as ONE parameter, cast to the
13812
+ * column type it is destined for. The single binding path for a non-scalar
13813
+ * VALUE — a `json` cell, an `array` cell, a document literal in a predicate.
13814
+ *
13815
+ * WHY A CAST, AND WHY THE FIELD TYPE. The document travels as its JSON TEXT in
13816
+ * a normal parameter slot (so `SqlValue` stays scalar and nothing is ever
13817
+ * string-interpolated), which means the server must be told what to parse it
13818
+ * AS. Left to inference, the same text is a `jsonb` in one column and a syntax
13819
+ * error in another. `fieldType` — supplied by the WRITE path, which knows the
13820
+ * column — makes that explicit; without it (a bare literal in a `where`, which
13821
+ * knows only its own shape) the dialect's own JSON type is the default.
13822
+ *
13823
+ * The base dialect casts to whatever `sqlTypeFor` names, which is the portable
13824
+ * answer for a JSON-typed column. A dialect with a NATIVE array type (Postgres
13825
+ * `text[]`) must override — an array literal there is not JSON text.
13826
+ */
13827
+ jsonValue(value2, fieldType) {
13828
+ const target = fieldType ? this.sqlTypeFor(fieldType) : this.jsonSqlType();
13829
+ return SqlText.concat([
13830
+ SqlText.raw("CAST("),
13831
+ SqlText.param(JSON.stringify(value2)),
13832
+ SqlText.raw(` AS ${target})`)
13833
+ ]);
13834
+ }
13835
+ /** This dialect's JSON column type — the default cast target for a document. */
13836
+ jsonSqlType() {
13837
+ return "json";
13838
+ }
13693
13839
  /**
13694
13840
  * Render a builtin's INLINE-LITERAL argument (a `rawArgs` position — see
13695
13841
  * {@link import('../schema').FunctionDef.rawArgs}) as a dialect-appropriate SQL
@@ -13969,6 +14115,47 @@ var PostgresDialect = class extends BaseDialect {
13969
14115
  SqlText.raw(")")
13970
14116
  ]);
13971
14117
  }
14118
+ /** Postgres stores JSON as `jsonb` (it has the equality / ordering operators `json` lacks). */
14119
+ jsonSqlType() {
14120
+ return "jsonb";
14121
+ }
14122
+ /**
14123
+ * Bind a JSON DOCUMENT — with the one Postgres wrinkle that makes the base
14124
+ * implementation wrong here: a NATIVE array column (`text[]`, `integer[]`, …)
14125
+ * does NOT accept JSON text. `CAST('["a","b"]' AS text[])` is a syntax error,
14126
+ * because a Postgres array literal is `{a,b}`.
14127
+ *
14128
+ * So a document destined for a native array is CONSTRUCTED instead —
14129
+ * `ARRAY[$1, $2]::text[]` — with each element bound in its own slot. That
14130
+ * reuses the element-binding pattern the array containment operators already
14131
+ * use, needs no array-literal encoder (whose quoting / escaping / NULL rules
14132
+ * would be their own defect surface), and handles the empty array
14133
+ * (`ARRAY[]::text[]`, which Postgres accepts precisely because the cast names
14134
+ * the type). Elements recurse, so a `jsonb[]` column takes documents.
14135
+ *
14136
+ * Everything else — a `json` / `jsonb` column, a heterogeneous array (which
14137
+ * `sqlTypeFor` already stores as `jsonb`), or a bare document with no declared
14138
+ * target — casts the JSON text to `jsonb`.
14139
+ */
14140
+ jsonValue(value2, fieldType) {
14141
+ const array = fieldType instanceof ArrayFieldType ? fieldType : void 0;
14142
+ const item = array?.item;
14143
+ if (array !== void 0 && item !== void 0 && Array.isArray(value2)) {
14144
+ const elements2 = value2.map(
14145
+ (v) => v !== null && typeof v === "object" ? this.jsonValue(v, item) : SqlText.param(v)
14146
+ );
14147
+ return SqlText.concat([
14148
+ SqlText.raw("ARRAY["),
14149
+ SqlText.join(elements2, ", "),
14150
+ SqlText.raw(`]::${this.sqlTypeFor(array)}`)
14151
+ ]);
14152
+ }
14153
+ return SqlText.concat([
14154
+ SqlText.raw("CAST("),
14155
+ SqlText.param(JSON.stringify(value2)),
14156
+ SqlText.raw(` AS ${this.jsonSqlType()})`)
14157
+ ]);
14158
+ }
13972
14159
  /** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
13973
14160
  queryVectorParam(param3) {
13974
14161
  return SqlText.concat([param3, SqlText.raw("::vector")]);
@@ -15271,12 +15458,12 @@ var Registry = class {
15271
15458
  return this.defaultFieldTypeBytes.get(kind);
15272
15459
  }
15273
15460
  /** Parse a `FieldTypeDef` into a `FieldType` instance by dispatching on kind. */
15274
- parseFieldType(json) {
15275
- const cls = this.fieldTypeClasses.get(json.kind);
15461
+ parseFieldType(json2) {
15462
+ const cls = this.fieldTypeClasses.get(json2.kind);
15276
15463
  if (!cls) {
15277
- throw new Error(`registry.parseFieldType: unknown field-type kind '${json.kind}'`);
15464
+ throw new Error(`registry.parseFieldType: unknown field-type kind '${json2.kind}'`);
15278
15465
  }
15279
- return cls.from(json, this);
15466
+ return cls.from(json2, this);
15280
15467
  }
15281
15468
  // ─── Named Type registration / dispatch ──────────────────────────────────
15282
15469
  /**
@@ -15351,8 +15538,8 @@ var Registry = class {
15351
15538
  return Array.from(this.namedTypes.values());
15352
15539
  }
15353
15540
  /** Parse a `TypeDef` into a `Type` instance (does NOT auto-register). */
15354
- parseType(json) {
15355
- return Type.from(json, this);
15541
+ parseType(json2) {
15542
+ return Type.from(json2, this);
15356
15543
  }
15357
15544
  // ─── Function registration (Phase 2/4) ────────────────────────────────────
15358
15545
  /**
@@ -15447,13 +15634,13 @@ var Registry = class {
15447
15634
  * PASS-THROUGH — returned as-is. This is a runtime-boundary widening only: the
15448
15635
  * JSON `ExprDef` types stay pure, but built and parsed exprs compose freely.
15449
15636
  */
15450
- parseExpr(json) {
15451
- if (json instanceof Expr) return json;
15452
- const cls = this.exprClasses.get(json.kind);
15637
+ parseExpr(json2) {
15638
+ if (json2 instanceof Expr) return json2;
15639
+ const cls = this.exprClasses.get(json2.kind);
15453
15640
  if (!cls) {
15454
- throw new Error(`registry.parseExpr: unknown expr kind '${json.kind}'`);
15641
+ throw new Error(`registry.parseExpr: unknown expr kind '${json2.kind}'`);
15455
15642
  }
15456
- return cls.from(json, this);
15643
+ return cls.from(json2, this);
15457
15644
  }
15458
15645
  /** The `kind → Shape<Expr>` map, built from every Expr class that owns a `SHAPE`. */
15459
15646
  checkedExprShapes() {
@@ -15474,17 +15661,17 @@ var Registry = class {
15474
15661
  * active gate (zod still gates `parseQueryInput`). Only kinds that declare a
15475
15662
  * `static SHAPE` participate — others surface as an unknown-kind problem.
15476
15663
  */
15477
- parseCheckedExpr(json, problems) {
15478
- if (json instanceof Expr) return json;
15479
- if (!isRecord3(json)) {
15480
- const got = describeInput(json);
15664
+ parseCheckedExpr(json2, problems) {
15665
+ if (json2 instanceof Expr) return json2;
15666
+ if (!isRecord3(json2)) {
15667
+ const got = describeInput(json2);
15481
15668
  problems.error(
15482
15669
  "shape.not-object",
15483
15670
  `expected ${aidInfo("Expr").label}${got !== void 0 ? `, got ${got}` : ""}`
15484
15671
  );
15485
15672
  return void 0;
15486
15673
  }
15487
- const kind = json["kind"];
15674
+ const kind = json2["kind"];
15488
15675
  if (typeof kind !== "string") {
15489
15676
  problems.error("shape.missing-kind", `expected ${aidInfo("Expr").label} with a string \`kind\` discriminant`);
15490
15677
  return void 0;
@@ -15499,7 +15686,7 @@ var Registry = class {
15499
15686
  );
15500
15687
  return void 0;
15501
15688
  }
15502
- const built = shape.check(json, { problems, registry: this });
15689
+ const built = shape.check(json2, { problems, registry: this });
15503
15690
  return built === INVALID ? void 0 : built;
15504
15691
  }
15505
15692
  /**
@@ -15507,12 +15694,12 @@ var Registry = class {
15507
15694
  * registered class's static `from`. Children (sub-selects, CTE arms, …) are
15508
15695
  * parsed recursively by the class's `from` calling back into this method.
15509
15696
  */
15510
- parseQuery(json) {
15511
- const cls = this.queryClasses.get(json.kind);
15697
+ parseQuery(json2) {
15698
+ const cls = this.queryClasses.get(json2.kind);
15512
15699
  if (!cls) {
15513
- throw new Error(`registry.parseQuery: unknown query kind '${json.kind}'`);
15700
+ throw new Error(`registry.parseQuery: unknown query kind '${json2.kind}'`);
15514
15701
  }
15515
- return cls.from(json, this);
15702
+ return cls.from(json2, this);
15516
15703
  }
15517
15704
  /** The `kind → Shape<Query>` map, built from every Query class that owns a `SHAPE`. */
15518
15705
  checkedQueryShapes() {
@@ -15530,16 +15717,16 @@ var Registry = class {
15530
15717
  * class's owned `SHAPE` (see `shape/`), accumulating every structural problem
15531
15718
  * in a single pass. Only query kinds that declare a `static SHAPE` participate.
15532
15719
  */
15533
- parseCheckedQuery(json, problems) {
15534
- if (!isRecord3(json)) {
15535
- const got = describeInput(json);
15720
+ parseCheckedQuery(json2, problems) {
15721
+ if (!isRecord3(json2)) {
15722
+ const got = describeInput(json2);
15536
15723
  problems.error(
15537
15724
  "shape.not-object",
15538
15725
  `expected ${aidInfo("Query").label}${got !== void 0 ? `, got ${got}` : ""}`
15539
15726
  );
15540
15727
  return void 0;
15541
15728
  }
15542
- const kind = json["kind"];
15729
+ const kind = json2["kind"];
15543
15730
  if (typeof kind !== "string") {
15544
15731
  problems.error("shape.missing-kind", `expected ${aidInfo("Query").label} with a string \`kind\` discriminant`);
15545
15732
  return void 0;
@@ -15554,7 +15741,7 @@ var Registry = class {
15554
15741
  );
15555
15742
  return void 0;
15556
15743
  }
15557
- const built = shape.check(json, { problems, registry: this });
15744
+ const built = shape.check(json2, { problems, registry: this });
15558
15745
  return built === INVALID ? void 0 : built;
15559
15746
  }
15560
15747
  /**
@@ -15563,16 +15750,16 @@ var Registry = class {
15563
15750
  * NEVER throws: records problems and returns the built `QuerySource` or
15564
15751
  * `undefined`. Dispatches on the source `kind` over `QuerySource.SHAPES`.
15565
15752
  */
15566
- parseCheckedSource(json, problems) {
15567
- if (!isRecord3(json)) {
15568
- const got = describeInput(json);
15753
+ parseCheckedSource(json2, problems) {
15754
+ if (!isRecord3(json2)) {
15755
+ const got = describeInput(json2);
15569
15756
  problems.error(
15570
15757
  "shape.not-object",
15571
15758
  `expected ${aidInfo("Source").label}${got !== void 0 ? `, got ${got}` : ""}`
15572
15759
  );
15573
15760
  return void 0;
15574
15761
  }
15575
- const kind = json["kind"];
15762
+ const kind = json2["kind"];
15576
15763
  if (typeof kind !== "string") {
15577
15764
  problems.error("shape.missing-kind", `expected ${aidInfo("Source").label} with a string \`kind\` discriminant`);
15578
15765
  return void 0;
@@ -15586,7 +15773,7 @@ var Registry = class {
15586
15773
  );
15587
15774
  return void 0;
15588
15775
  }
15589
- const built = shape.check(json, { problems, registry: this });
15776
+ const built = shape.check(json2, { problems, registry: this });
15590
15777
  return built === INVALID ? void 0 : built;
15591
15778
  }
15592
15779
  };
@@ -16097,41 +16284,41 @@ var QueryFunction = class _QueryFunction {
16097
16284
  this.references = spec.references ?? [];
16098
16285
  }
16099
16286
  /** Build a runtime function from its JSON, parsing field/Type references. */
16100
- static from(json, registry) {
16101
- const params = json.params.map((p) => ({
16287
+ static from(json2, registry) {
16288
+ const params = json2.params.map((p) => ({
16102
16289
  name: p.name,
16103
16290
  fieldType: p.type === "any" ? void 0 : registry.parseFieldType(p.type),
16104
16291
  optional: p.optional ?? false
16105
16292
  }));
16106
16293
  let output2;
16107
- if (json.output === "inferred") {
16294
+ if (json2.output === "inferred") {
16108
16295
  output2 = { tag: "inferred" };
16109
- } else if (isFieldTypeDef(json.output)) {
16110
- output2 = { tag: "field", fieldType: registry.parseFieldType(json.output) };
16296
+ } else if (isFieldTypeDef(json2.output)) {
16297
+ output2 = { tag: "field", fieldType: registry.parseFieldType(json2.output) };
16111
16298
  } else {
16112
- if (!isTypeRef(json.output)) return assertNever9(json.output);
16113
- const type = registry.type(json.output.type);
16299
+ if (!isTypeRef(json2.output)) return assertNever9(json2.output);
16300
+ const type = registry.type(json2.output.type);
16114
16301
  if (!type) {
16115
16302
  throw new Error(
16116
- `QueryFunction.from: function '${json.name}' output references unknown Type '${json.output.type}'`
16303
+ `QueryFunction.from: function '${json2.name}' output references unknown Type '${json2.output.type}'`
16117
16304
  );
16118
16305
  }
16119
16306
  output2 = { tag: "type", type };
16120
16307
  }
16121
16308
  return new _QueryFunction({
16122
- name: json.name,
16123
- shape: json.shape,
16309
+ name: json2.name,
16310
+ shape: json2.shape,
16124
16311
  params,
16125
16312
  output: output2,
16126
- sql: json.sql,
16127
- rawArgs: json.rawArgs,
16128
- instructions: json.instructions,
16129
- examples: json.examples,
16130
- unaggregate: json.unaggregate,
16131
- unaggregateEmpty: json.unaggregateEmpty,
16132
- cost: json.cost,
16133
- changes: json.changes,
16134
- references: json.references
16313
+ sql: json2.sql,
16314
+ rawArgs: json2.rawArgs,
16315
+ instructions: json2.instructions,
16316
+ examples: json2.examples,
16317
+ unaggregate: json2.unaggregate,
16318
+ unaggregateEmpty: json2.unaggregateEmpty,
16319
+ cost: json2.cost,
16320
+ changes: json2.changes,
16321
+ references: json2.references
16135
16322
  });
16136
16323
  }
16137
16324
  /**
@@ -17266,14 +17453,18 @@ function uniqueParamName(field, taken) {
17266
17453
  taken.add(name);
17267
17454
  return name;
17268
17455
  }
17269
- function expandStar(select, engine) {
17456
+ function expandStar(select, engine, projected) {
17270
17457
  const from = select.from;
17271
17458
  if (from.sourceKind !== "type" || from.typeName === void 0) return void 0;
17272
17459
  const type = engine.type(from.typeName);
17273
17460
  if (!type) return void 0;
17274
- return type.fields.map((f) => ({
17275
- expr: { kind: "field-ref", source: from.alias, field: f.name }
17276
- }));
17461
+ const fields = [];
17462
+ for (const f of type.fields) {
17463
+ const expr = { kind: "field-ref", source: from.alias, field: f.name };
17464
+ if (projected.has(exprDigest(expr))) continue;
17465
+ fields.push({ expr });
17466
+ }
17467
+ return fields;
17277
17468
  }
17278
17469
  function drillDown(select, engine) {
17279
17470
  const sq = expandSelectOutputs(asSelectQuery(select, engine), engine);
@@ -17306,6 +17497,10 @@ function drillDown(select, engine) {
17306
17497
  canon: canonicalize(c.expr),
17307
17498
  name: nameOf(c.expr, c.as, i)
17308
17499
  }));
17500
+ const projected = /* @__PURE__ */ new Set();
17501
+ sq.fields.forEach((c, i) => {
17502
+ if (!c.expr.containsAggregate()) projected.add(colInfo[i].canon);
17503
+ });
17309
17504
  const taken = referencedParamNames(sq);
17310
17505
  const params = [];
17311
17506
  const pinned = [];
@@ -17322,7 +17517,7 @@ function drillDown(select, engine) {
17322
17517
  sq.fields.forEach((c, i) => {
17323
17518
  const e2 = c.expr;
17324
17519
  if (e2 instanceof AggregateExpr && e2.valueArg() === void 0) {
17325
- const expanded = expandStar(sq, engine);
17520
+ const expanded = expandStar(sq, engine, projected);
17326
17521
  if (!expanded) {
17327
17522
  errors.at(
17328
17523
  ["fields", i],
@@ -17881,8 +18076,10 @@ function fieldTypeSentence(ft) {
17881
18076
  }
17882
18077
  case "bool":
17883
18078
  return "A true/false flag";
17884
- case "relation":
17885
- return def.count === 1 ? `Belongs to one ${def.to}` : `Has many ${def.to} (\u2248${def.count} per row)`;
18079
+ case "relation": {
18080
+ const belongsTo = ft instanceof RelationFieldType ? ft.isBelongsTo() : def.count === 1;
18081
+ return belongsTo ? `Belongs to one ${def.to}` : `Has many ${def.to} (\u2248${def.count} per row)`;
18082
+ }
17886
18083
  case "date":
17887
18084
  return "A calendar date";
17888
18085
  case "timestamp":