@cyphra/runtime 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -15,14 +15,21 @@ async function toPlainRecord(result) {
15
15
  // src/client.ts
16
16
  var CyphraClient = class {
17
17
  driver;
18
+ ownsDriver;
18
19
  database;
19
20
  debug;
20
21
  constructor(opts) {
21
- this.driver = neo4j.driver(
22
- opts.uri,
23
- neo4j.auth.basic(opts.user, opts.password),
24
- opts.driverConfig
25
- );
22
+ if (opts.driver) {
23
+ this.driver = opts.driver;
24
+ this.ownsDriver = false;
25
+ } else {
26
+ this.driver = neo4j.driver(
27
+ opts.uri,
28
+ neo4j.auth.basic(opts.user, opts.password),
29
+ opts.driverConfig
30
+ );
31
+ this.ownsDriver = true;
32
+ }
26
33
  this.database = opts.database;
27
34
  this.debug = opts.debug ?? false;
28
35
  }
@@ -150,9 +157,12 @@ var CyphraClient = class {
150
157
  await session.close();
151
158
  }
152
159
  }
153
- /** Close the driver (call on shutdown). */
160
+ /**
161
+ * Close the driver (call on shutdown). A driver passed in with `{ driver }` is left open: its
162
+ * owner closes it.
163
+ */
154
164
  async close() {
155
- await this.driver.close();
165
+ if (this.ownsDriver) await this.driver.close();
156
166
  }
157
167
  };
158
168
 
@@ -161,7 +171,7 @@ import { compileCypher as compileCypher2 } from "@cyphra/query";
161
171
 
162
172
  // src/orm/engine.ts
163
173
  import { randomUUID, getRandomValues } from "crypto";
164
- import { isInt as isInt2 } from "neo4j-driver";
174
+ import { isInt as isInt3 } from "neo4j-driver";
165
175
 
166
176
  // src/orm/compile.ts
167
177
  import neo4j3 from "neo4j-driver";
@@ -186,6 +196,9 @@ function integerToNumber(v) {
186
196
  }
187
197
  return v.toNumber();
188
198
  }
199
+ function decodeCount(v) {
200
+ return isInt(v) ? integerToNumber(v) : Number(v ?? 0);
201
+ }
189
202
  function utcDateTime(d) {
190
203
  return new neo4j2.types.DateTime(
191
204
  d.getUTCFullYear(),
@@ -527,7 +540,24 @@ function compileWhere(ctx, model, alias, where) {
527
540
  }
528
541
  return and(parts);
529
542
  }
530
- function compileOrderBy(model, alias, orderBy) {
543
+ function compileRelationCount(ctx, model, alias, rel, where) {
544
+ if (!rel.many) {
545
+ throw new CyphraValidationError(
546
+ `${model.name}.${rel.name} is a to-one relation; only to-many relations can be counted.`
547
+ );
548
+ }
549
+ const m = ctx.variable();
550
+ const pattern = relationPattern(ctx, alias, rel, m);
551
+ const inner = compileWhere(ctx, ctx.node(rel.target), m, where);
552
+ return inner ? `COUNT { MATCH ${pattern} WHERE ${inner} }` : `COUNT { MATCH ${pattern} }`;
553
+ }
554
+ function sortDirection(dir, what) {
555
+ if (dir !== "asc" && dir !== "desc") {
556
+ throw new CyphraValidationError(`orderBy ${what} must be "asc" or "desc".`);
557
+ }
558
+ return dir.toUpperCase();
559
+ }
560
+ function compileOrderBy(ctx, model, alias, orderBy) {
531
561
  if (orderBy === void 0 || orderBy === null) return null;
532
562
  const list = Array.isArray(orderBy) ? orderBy : [orderBy];
533
563
  const parts = [];
@@ -535,11 +565,20 @@ function compileOrderBy(model, alias, orderBy) {
535
565
  if (!isPlainObject(item)) throw new CyphraValidationError("orderBy entries must be objects.");
536
566
  for (const [key, dir] of Object.entries(item)) {
537
567
  if (dir === void 0) continue;
538
- scalarOrThrow(model, key);
539
- if (dir !== "asc" && dir !== "desc") {
540
- throw new CyphraValidationError(`orderBy ${model.name}.${key} must be "asc" or "desc".`);
568
+ const rel = relationField(model, key);
569
+ if (rel) {
570
+ if (!isPlainObject(dir) || Object.keys(dir).some((k) => k !== "_count")) {
571
+ throw new CyphraValidationError(
572
+ `orderBy ${model.name}.${key} takes { _count: "asc" | "desc" }.`
573
+ );
574
+ }
575
+ if (dir._count === void 0) continue;
576
+ const d = sortDirection(dir._count, `${model.name}.${key}._count`);
577
+ parts.push(`${compileRelationCount(ctx, model, alias, rel)} ${d}`);
578
+ continue;
541
579
  }
542
- parts.push(`${alias}.${q(key)} ${dir.toUpperCase()}`);
580
+ scalarOrThrow(model, key);
581
+ parts.push(`${alias}.${q(key)} ${sortDirection(dir, `${model.name}.${key}`)}`);
543
582
  }
544
583
  }
545
584
  return parts.length ? parts.join(", ") : null;
@@ -552,7 +591,7 @@ function nonNegativeInt(v, name) {
552
591
  }
553
592
  function compilePaging(ctx, model, alias, args) {
554
593
  let s = "";
555
- const order = compileOrderBy(model, alias, args.orderBy);
594
+ const order = compileOrderBy(ctx, model, alias, args.orderBy);
556
595
  if (order) s += ` ORDER BY ${order}`;
557
596
  if (args.skip !== void 0)
558
597
  s += ` SKIP ${ctx.param(intParam(nonNegativeInt(args.skip, "skip")))}`;
@@ -570,9 +609,14 @@ function compileProjection(ctx, model, alias, args, extraEntries = []) {
570
609
  const scalars = [];
571
610
  const rels = [];
572
611
  const allScalars = model.fields.filter((f) => f.kind === "scalar");
612
+ let counts;
573
613
  const takeRelations = (spec, label) => {
574
614
  for (const [key, v] of Object.entries(spec)) {
575
615
  if (v === void 0 || v === false) continue;
616
+ if (key === "_count") {
617
+ counts = relationCounts(model, v, label);
618
+ continue;
619
+ }
576
620
  const f = model.fields.find((x) => x.name === key);
577
621
  if (!f) throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in ${label}.`);
578
622
  if (f.kind === "scalar") {
@@ -625,12 +669,60 @@ function compileProjection(ctx, model, alias, args, extraEntries = []) {
625
669
  ...edgeModel ? { edge: edgeModel.properties } : {}
626
670
  });
627
671
  }
672
+ if (counts) {
673
+ const map = counts.map(
674
+ ({ field, where }) => `${q(field.name)}: ${compileRelationCount(ctx, model, alias, field, where)}`
675
+ );
676
+ entries.push(`${q("_count")}: {${map.join(", ")}}`);
677
+ }
628
678
  entries.push(...extraEntries);
629
679
  return {
630
680
  expr: `${alias}{${entries.join(", ")}}`,
631
- shape: { model, scalars, relations: relShapes }
681
+ shape: {
682
+ model,
683
+ scalars,
684
+ relations: relShapes,
685
+ ...counts ? { counts: counts.map((c) => c.field) } : {}
686
+ }
632
687
  };
633
688
  }
689
+ function relationCounts(model, spec, label) {
690
+ if (spec === true) {
691
+ return model.fields.filter((f) => f.kind === "relation" && f.many).map((field) => ({ field, where: void 0 }));
692
+ }
693
+ if (!isPlainObject(spec) || Object.keys(spec).some((k) => k !== "select")) {
694
+ throw new CyphraValidationError(
695
+ `${label}._count on ${model.name} takes true or { select: { <relation>: true | { where } } }.`
696
+ );
697
+ }
698
+ if (!isPlainObject(spec.select)) {
699
+ throw new CyphraValidationError(`${label}._count.select on ${model.name} must be an object.`);
700
+ }
701
+ const out = [];
702
+ for (const [key, v] of Object.entries(spec.select)) {
703
+ if (v === void 0 || v === false) continue;
704
+ const field = relationField(model, key);
705
+ if (!field) {
706
+ throw new CyphraValidationError(
707
+ `Unknown relation "${model.name}.${key}" in ${label}._count.select.`
708
+ );
709
+ }
710
+ if (!field.many) {
711
+ throw new CyphraValidationError(
712
+ `${model.name}.${key} is a to-one relation; only to-many relations can be counted.`
713
+ );
714
+ }
715
+ if (v === true) out.push({ field, where: void 0 });
716
+ else if (isPlainObject(v) && Object.keys(v).every((k) => k === "where")) {
717
+ out.push({ field, where: v.where });
718
+ } else {
719
+ throw new CyphraValidationError(
720
+ `${label}._count.select.${key} on ${model.name} takes true or { where }.`
721
+ );
722
+ }
723
+ }
724
+ return out;
725
+ }
634
726
  function decodeRow(shape, row) {
635
727
  if (row === null || row === void 0) return null;
636
728
  const src = row;
@@ -650,15 +742,699 @@ function decodeRow(shape, row) {
650
742
  const v = src[r.field.name];
651
743
  out[r.field.name] = r.field.many ? (v ?? []).map(decodeItem) : decodeItem(v);
652
744
  }
745
+ if (shape.counts) {
746
+ const raw = src["_count"] ?? {};
747
+ const counts = {};
748
+ for (const f of shape.counts) counts[f.name] = decodeCount(raw[f.name]);
749
+ out._count = counts;
750
+ }
653
751
  return out;
654
752
  }
655
753
 
656
- // src/orm/engine.ts
754
+ // src/orm/aggregate.ts
755
+ import { isInt as isInt2 } from "neo4j-driver";
756
+ var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
757
+ var AGG_SET = new Set(AGGREGATES);
758
+ var NUMERIC = /* @__PURE__ */ new Set(["Int", "Float"]);
759
+ var ORDERABLE = /* @__PURE__ */ new Set(["Int", "Float", "String", "DateTime", "Date"]);
657
760
  function isPlainObject2(v) {
658
761
  return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
659
762
  }
763
+ function aggTarget(model, op, name) {
764
+ if (name === "_all") {
765
+ if (op !== "_count") throw new CyphraValidationError(`${op} does not take "_all".`);
766
+ return "_all";
767
+ }
768
+ const f = scalarField(model, name);
769
+ if (!f) throw new CyphraValidationError(`Unknown scalar field "${model.name}.${name}" in ${op}.`);
770
+ if (op === "_count") return f;
771
+ const ok = !f.list && (op === "_sum" || op === "_avg" ? NUMERIC : ORDERABLE).has(f.type);
772
+ if (!ok) {
773
+ const allowed = op === "_sum" || op === "_avg" ? "Int and Float" : "Int, Float, String, DateTime and Date";
774
+ throw new CyphraValidationError(
775
+ `${op} is not valid on ${model.name}.${name} (${f.type}${f.list ? "[]" : ""}); it takes ${allowed} fields.`
776
+ );
777
+ }
778
+ return f;
779
+ }
780
+ function aggExpr(alias, op, target) {
781
+ if (target === "_all") return `count(${alias})`;
782
+ const ref = `${alias}.${q(target.name)}`;
783
+ switch (op) {
784
+ case "_count":
785
+ return `count(${ref})`;
786
+ // Cypher's sum() is 0 on an empty set; SQL (and Prisma) return null.
787
+ case "_sum":
788
+ return `CASE WHEN count(${ref}) = 0 THEN null ELSE sum(${ref}) END`;
789
+ case "_avg":
790
+ return `avg(${ref})`;
791
+ case "_min":
792
+ return `min(${ref})`;
793
+ case "_max":
794
+ return `max(${ref})`;
795
+ }
796
+ }
797
+ function decodeAgg(op, target, v) {
798
+ if (op === "_count") return decodeCount(v);
799
+ if (v === null || v === void 0) return null;
800
+ if (op === "_avg") return isInt2(v) ? integerToNumber(v) : Number(v);
801
+ return decodeScalar(target, v);
802
+ }
803
+ function aggResultField(op, target) {
804
+ const base = target === "_all" ? void 0 : target;
805
+ const name = `${base?.name ?? "_all"}.${op}`;
806
+ const type = op === "_count" ? "Int" : op === "_sum" || op === "_avg" ? "Float" : base.type;
807
+ return {
808
+ kind: "scalar",
809
+ name,
810
+ type,
811
+ optional: op !== "_count",
812
+ list: false,
813
+ id: false,
814
+ unique: false,
815
+ index: false
816
+ };
817
+ }
818
+ var AggColumns = class {
819
+ constructor(ctx, alias) {
820
+ this.ctx = ctx;
821
+ this.alias = alias;
822
+ }
823
+ ctx;
824
+ alias;
825
+ columns = [];
826
+ aliases = [];
827
+ byExpr = /* @__PURE__ */ new Map();
828
+ add(op, target) {
829
+ const expr = aggExpr(this.alias, op, target);
830
+ let v = this.byExpr.get(expr);
831
+ if (!v) {
832
+ v = this.ctx.variable("a");
833
+ this.byExpr.set(expr, v);
834
+ this.columns.push(`${expr} AS ${v}`);
835
+ this.aliases.push(v);
836
+ }
837
+ return v;
838
+ }
839
+ };
840
+ function asFlag(v, where) {
841
+ if (v === void 0 || v === false) return false;
842
+ if (v === true) return true;
843
+ throw new CyphraValidationError(`${where} must be true or false.`);
844
+ }
845
+ function compileSelection(model, args, cols) {
846
+ const out = [];
847
+ for (const op of AGGREGATES) {
848
+ const spec = args[op];
849
+ if (spec === void 0 || spec === false) continue;
850
+ if (op === "_count" && spec === true) {
851
+ out.push({ op, key: null, target: "_all", column: cols.add(op, "_all") });
852
+ continue;
853
+ }
854
+ if (!isPlainObject2(spec)) {
855
+ throw new CyphraValidationError(
856
+ `${op} must be an object of fields${op === "_count" ? " or true" : ""}.`
857
+ );
858
+ }
859
+ for (const [name, flag] of Object.entries(spec)) {
860
+ if (!asFlag(flag, `${op}.${name}`)) continue;
861
+ const target = aggTarget(model, op, name);
862
+ out.push({ op, key: name, target, column: cols.add(op, target) });
863
+ }
864
+ if (out.every((o) => o.op !== op)) {
865
+ out.push({ op, key: "", target: "_all", column: "" });
866
+ }
867
+ }
868
+ return out;
869
+ }
870
+ function decodeSelection(outputs, row, into) {
871
+ for (const o of outputs) {
872
+ if (o.key === null) {
873
+ into[o.op] = decodeAgg(o.op, o.target, row[o.column]);
874
+ continue;
875
+ }
876
+ const bucket = into[o.op] ??= {};
877
+ if (o.key !== "") bucket[o.key] = decodeAgg(o.op, o.target, row[o.column]);
878
+ }
879
+ }
880
+ function compileAggregate(ctx, model, args) {
881
+ checkKeys(args, ["where", "orderBy", "skip", "take", ...AGGREGATES], "aggregate");
882
+ const whereClause = compileWhere(ctx, model, "n", args.where);
883
+ const cols = new AggColumns(ctx, "n");
884
+ const outputs = compileSelection(model, args, cols);
885
+ const paging = compilePaging(ctx, model, "n", args);
886
+ let text = `MATCH (n:${q(model.label)})`;
887
+ if (whereClause) text += ` WHERE ${whereClause}`;
888
+ if (paging) text += ` WITH n${paging}`;
889
+ text += ` RETURN ${cols.columns.length ? cols.columns.join(", ") : "count(n) AS _"}`;
890
+ return {
891
+ text,
892
+ params: ctx.params,
893
+ decode: (rows) => {
894
+ const out = {};
895
+ decodeSelection(outputs, rows[0] ?? {}, out);
896
+ return out;
897
+ }
898
+ };
899
+ }
900
+ function checkKeys(args, allowed, op) {
901
+ for (const k of Object.keys(args)) {
902
+ if (args[k] !== void 0 && !allowed.includes(k)) {
903
+ throw new CyphraValidationError(`Unknown ${op} argument "${k}".`);
904
+ }
905
+ }
906
+ }
907
+ function compileGroupKeys(ctx, model, by) {
908
+ const list = Array.isArray(by) ? by : [by];
909
+ if (list.length === 0 || list.some((x) => typeof x !== "string")) {
910
+ throw new CyphraValidationError(
911
+ "groupBy: by must be a field name or a non-empty array of them."
912
+ );
913
+ }
914
+ const keys = [];
915
+ const related = [];
916
+ const relVars = /* @__PURE__ */ new Map();
917
+ const keyColumns = [];
918
+ for (const path of new Set(list)) {
919
+ const dot = path.indexOf(".");
920
+ const column = ctx.variable("k");
921
+ if (dot === -1) {
922
+ const field2 = scalarField(model, path);
923
+ if (!field2) {
924
+ throw new CyphraValidationError(
925
+ `Unknown scalar field "${model.name}.${path}" in groupBy.by.`
926
+ );
927
+ }
928
+ keys.push({ path, column, field: field2 });
929
+ keyColumns.push(`n.${q(field2.name)} AS ${column}`);
930
+ continue;
931
+ }
932
+ const relName = path.slice(0, dot);
933
+ const fieldName = path.slice(dot + 1);
934
+ const relation = relationField(model, relName);
935
+ if (!relation) {
936
+ throw new CyphraValidationError(`Unknown relation "${model.name}.${relName}" in groupBy.by.`);
937
+ }
938
+ if (relation.many) {
939
+ throw new CyphraValidationError(
940
+ `groupBy.by "${path}": only fields of to-one relations can be grouped by (${model.name}.${relName} is a list).`
941
+ );
942
+ }
943
+ const target = ctx.node(relation.target);
944
+ const field = scalarField(target, fieldName);
945
+ if (!field) {
946
+ throw new CyphraValidationError(
947
+ `Unknown scalar field "${target.name}.${fieldName}" in groupBy.by.`
948
+ );
949
+ }
950
+ let g = relVars.get(relName);
951
+ if (!g) {
952
+ g = ctx.variable("g");
953
+ relVars.set(relName, g);
954
+ const m = ctx.variable();
955
+ related.push(
956
+ `head(COLLECT { MATCH ${relationPattern(ctx, "n", relation, m)} RETURN ${m} }) AS ${g}`
957
+ );
958
+ }
959
+ keys.push({ path, column, field, relation });
960
+ keyColumns.push(`${g}.${q(field.name)} AS ${column}`);
961
+ }
962
+ return { keys, related, keyColumns };
963
+ }
964
+ function keyFor(keys, path, clause) {
965
+ const k = keys.find((x) => x.path === path);
966
+ if (!k) throw new CyphraValidationError(`groupBy ${clause}: "${path}" must be listed in by.`);
967
+ return k;
968
+ }
969
+ function compileHaving(ctx, model, keys, cols, having) {
970
+ if (having === void 0 || having === null) return null;
971
+ if (!isPlainObject2(having)) throw new CyphraValidationError("groupBy having must be an object.");
972
+ const parts = [];
973
+ for (const [key, value] of Object.entries(having)) {
974
+ if (value === void 0) continue;
975
+ if (key === "AND" || key === "OR" || key === "NOT") {
976
+ const list = Array.isArray(value) ? value : [value];
977
+ const compiled = list.map((h) => compileHaving(ctx, model, keys, cols, h)).filter((x) => Boolean(x));
978
+ if (key === "AND") {
979
+ if (compiled.length) parts.push(compiled.map((x) => `(${x})`).join(" AND "));
980
+ } else if (key === "OR") {
981
+ if (list.length === 0) parts.push("false");
982
+ else if (compiled.length === list.length)
983
+ parts.push(compiled.map((x) => `(${x})`).join(" OR "));
984
+ } else for (const c of compiled) parts.push(`NOT (${c})`);
985
+ continue;
986
+ }
987
+ const field = scalarField(model, key);
988
+ if (field) {
989
+ const rest = {};
990
+ let hasRest = !isPlainObject2(value);
991
+ if (isPlainObject2(value)) {
992
+ for (const [op, filter] of Object.entries(value)) {
993
+ if (filter === void 0) continue;
994
+ if (AGG_SET.has(op)) {
995
+ const agg = op;
996
+ const target = aggTarget(model, agg, key);
997
+ const c = compileScalarFilter(
998
+ ctx,
999
+ model,
1000
+ aggResultField(agg, target),
1001
+ cols.add(agg, target),
1002
+ filter
1003
+ );
1004
+ if (c) parts.push(c);
1005
+ } else {
1006
+ rest[op] = filter;
1007
+ hasRest = true;
1008
+ }
1009
+ }
1010
+ }
1011
+ if (hasRest) {
1012
+ const k = keyFor(keys, key, "having");
1013
+ const c = compileScalarFilter(
1014
+ ctx,
1015
+ model,
1016
+ field,
1017
+ k.column,
1018
+ isPlainObject2(value) ? rest : value
1019
+ );
1020
+ if (c) parts.push(c);
1021
+ }
1022
+ continue;
1023
+ }
1024
+ const rel = relationField(model, key);
1025
+ if (rel && !rel.many) {
1026
+ if (!isPlainObject2(value)) {
1027
+ throw new CyphraValidationError(
1028
+ `groupBy having.${key} must be an object of ${rel.target} fields.`
1029
+ );
1030
+ }
1031
+ const target = ctx.node(rel.target);
1032
+ for (const [name, filter] of Object.entries(value)) {
1033
+ const k = keyFor(keys, `${key}.${name}`, "having");
1034
+ const c = compileScalarFilter(ctx, target, k.field, k.column, filter);
1035
+ if (c) parts.push(c);
1036
+ }
1037
+ continue;
1038
+ }
1039
+ throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in having.`);
1040
+ }
1041
+ if (parts.length === 0) return null;
1042
+ return parts.length === 1 ? parts[0] : parts.map((x) => `(${x})`).join(" AND ");
1043
+ }
1044
+ function sortDir(dir, where) {
1045
+ if (dir !== "asc" && dir !== "desc") {
1046
+ throw new CyphraValidationError(`orderBy ${where} must be "asc" or "desc".`);
1047
+ }
1048
+ return dir.toUpperCase();
1049
+ }
1050
+ function compileGroupOrder(model, keys, cols, orderBy) {
1051
+ if (orderBy === void 0 || orderBy === null) return null;
1052
+ const list = Array.isArray(orderBy) ? orderBy : [orderBy];
1053
+ const parts = [];
1054
+ for (const item of list) {
1055
+ if (!isPlainObject2(item)) throw new CyphraValidationError("orderBy entries must be objects.");
1056
+ for (const [key, dir] of Object.entries(item)) {
1057
+ if (dir === void 0) continue;
1058
+ if (AGG_SET.has(key)) {
1059
+ const op = key;
1060
+ if (!isPlainObject2(dir)) {
1061
+ throw new CyphraValidationError(`orderBy ${op} must be an object of fields.`);
1062
+ }
1063
+ for (const [name, d] of Object.entries(dir)) {
1064
+ if (d === void 0) continue;
1065
+ parts.push(`${cols.add(op, aggTarget(model, op, name))} ${sortDir(d, `${op}.${name}`)}`);
1066
+ }
1067
+ continue;
1068
+ }
1069
+ if (isPlainObject2(dir)) {
1070
+ const rel = relationField(model, key);
1071
+ if (!rel || rel.many) {
1072
+ throw new CyphraValidationError(
1073
+ `Unknown to-one relation "${model.name}.${key}" in orderBy.`
1074
+ );
1075
+ }
1076
+ for (const [name, d] of Object.entries(dir)) {
1077
+ if (d === void 0) continue;
1078
+ parts.push(
1079
+ `${keyFor(keys, `${key}.${name}`, "orderBy").column} ${sortDir(d, `${key}.${name}`)}`
1080
+ );
1081
+ }
1082
+ continue;
1083
+ }
1084
+ if (!scalarField(model, key)) {
1085
+ throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in orderBy.`);
1086
+ }
1087
+ parts.push(`${keyFor(keys, key, "orderBy").column} ${sortDir(dir, key)}`);
1088
+ }
1089
+ }
1090
+ return parts.length ? parts.join(", ") : null;
1091
+ }
1092
+ function compileGroupBy(ctx, model, args) {
1093
+ checkKeys(args, ["by", "where", "having", "orderBy", "skip", "take", ...AGGREGATES], "groupBy");
1094
+ const whereClause = compileWhere(ctx, model, "n", args.where);
1095
+ const { keys, related, keyColumns } = compileGroupKeys(ctx, model, args.by);
1096
+ const cols = new AggColumns(ctx, "n");
1097
+ const outputs = compileSelection(model, args, cols);
1098
+ const having = compileHaving(ctx, model, keys, cols, args.having);
1099
+ const order = compileGroupOrder(model, keys, cols, args.orderBy);
1100
+ if (cols.columns.length === 0) cols.add("_count", "_all");
1101
+ let text = `MATCH (n:${q(model.label)})`;
1102
+ if (whereClause) text += ` WHERE ${whereClause}`;
1103
+ if (related.length) text += ` WITH n, ${related.join(", ")}`;
1104
+ text += ` WITH ${[...keyColumns, ...cols.columns].join(", ")}`;
1105
+ if (having) text += ` WHERE ${having}`;
1106
+ const returned = [...keys.map((k) => k.column), ...cols.aliases];
1107
+ text += ` RETURN ${returned.join(", ")}`;
1108
+ if (order) text += ` ORDER BY ${order}`;
1109
+ if (args.skip !== void 0)
1110
+ text += ` SKIP ${ctx.param(intParam(nonNegativeInt(args.skip, "skip")))}`;
1111
+ if (args.take !== void 0)
1112
+ text += ` LIMIT ${ctx.param(intParam(nonNegativeInt(args.take, "take")))}`;
1113
+ return {
1114
+ text,
1115
+ params: ctx.params,
1116
+ decode: (rows) => rows.map((row) => {
1117
+ const out = {};
1118
+ for (const k of keys) {
1119
+ const v = decodeScalar(k.field, row[k.column]);
1120
+ if (k.relation) {
1121
+ const bucket = out[k.relation.name] ??= {};
1122
+ bucket[k.field.name] = v;
1123
+ } else out[k.field.name] = v;
1124
+ }
1125
+ decodeSelection(outputs, row, out);
1126
+ return out;
1127
+ })
1128
+ };
1129
+ }
1130
+
1131
+ // src/orm/path.ts
1132
+ function compilePath(ctx, path) {
1133
+ const x = ctx.variable("x");
1134
+ const i = ctx.variable("i");
1135
+ const rel = `relationships(${path})[${i}]`;
1136
+ const nodes = `[${x} IN nodes(${path}) | {labels: labels(${x}), properties: properties(${x})}]`;
1137
+ const edges = `[${i} IN range(0, length(${path}) - 1) | {type: type(${rel}), properties: properties(${rel}), out: startNode(${rel}) = nodes(${path})[${i}]}]`;
1138
+ return `{nodes: ${nodes}, edges: ${edges}}`;
1139
+ }
1140
+ function decodeProps(fields, raw) {
1141
+ const src = raw ?? {};
1142
+ const out = {};
1143
+ for (const f of fields) out[f.name] = decodeScalar(f, src[f.name]);
1144
+ return out;
1145
+ }
1146
+ function scalarsOf(model) {
1147
+ return model.fields.filter((f) => f.kind === "scalar");
1148
+ }
1149
+ function decodePath(schema, raw) {
1150
+ const src = raw ?? {};
1151
+ const rawNodes = src.nodes ?? [];
1152
+ const models = rawNodes.map((n) => schema.nodes.find((m) => (n.labels ?? []).includes(m.label)));
1153
+ const nodes = rawNodes.map((n, i) => {
1154
+ const model = models[i];
1155
+ return model ? decodeProps(scalarsOf(model), n.properties) : toNative(n.properties ?? {});
1156
+ });
1157
+ const rawEdges = src.edges ?? [];
1158
+ const edges = rawEdges.map((e, i) => {
1159
+ const type = String(e.type);
1160
+ const out = e.out === true;
1161
+ const start = models[out ? i : i + 1]?.name;
1162
+ const end = models[out ? i + 1 : i]?.name;
1163
+ const candidates = schema.relationships.filter((r) => r.relType === type);
1164
+ const edgeModel = candidates.find((r) => r.from === start && r.to === end) ?? (candidates.length === 1 ? candidates[0] : void 0);
1165
+ return {
1166
+ type,
1167
+ direction: out ? "out" : "in",
1168
+ properties: edgeModel ? decodeProps(edgeModel.properties, e.properties) : {}
1169
+ };
1170
+ });
1171
+ return { nodes, edges };
1172
+ }
1173
+
1174
+ // src/orm/traverse.ts
1175
+ var DEFAULT_MAX_TRAVERSAL_DEPTH = 10;
1176
+ var ARG_KEYS = /* @__PURE__ */ new Set([
1177
+ "from",
1178
+ "via",
1179
+ "direction",
1180
+ "depth",
1181
+ "where",
1182
+ "edgeWhere",
1183
+ "distinct",
1184
+ "select",
1185
+ "include",
1186
+ "orderBy",
1187
+ "skip",
1188
+ "take",
1189
+ "returnPaths"
1190
+ ]);
1191
+ function isPlainObject3(v) {
1192
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1193
+ }
1194
+ function hopBound(v, name, min, cap, op = "traverse") {
1195
+ if (typeof v !== "number" || !Number.isInteger(v) || v < min) {
1196
+ throw new CyphraValidationError(`${op}: ${name} must be an integer >= ${min}.`);
1197
+ }
1198
+ if (cap !== void 0 && v > cap) {
1199
+ throw new CyphraValidationError(
1200
+ `${op}: ${name} is ${v}, above the maximum traversal depth of ${cap} (client option maxTraversalDepth).`
1201
+ );
1202
+ }
1203
+ return v;
1204
+ }
1205
+ function parseDepth(depth, cap) {
1206
+ if (!isPlainObject3(depth) || depth.max === void 0) {
1207
+ throw new CyphraValidationError(
1208
+ "traverse: depth.max is required (depth: { min?: number, max: number })."
1209
+ );
1210
+ }
1211
+ for (const k of Object.keys(depth)) {
1212
+ if (k !== "min" && k !== "max") {
1213
+ throw new CyphraValidationError(`traverse: unknown depth option "${k}".`);
1214
+ }
1215
+ }
1216
+ const max = hopBound(depth.max, "depth.max", 1, cap);
1217
+ const min = depth.min === void 0 ? 1 : hopBound(depth.min, "depth.min", 0);
1218
+ if (min > max) {
1219
+ throw new CyphraValidationError(`traverse: depth.min (${min}) is above depth.max (${max}).`);
1220
+ }
1221
+ return { min, max };
1222
+ }
1223
+ function viaRelations(model, via, op = "traverse") {
1224
+ const names = Array.isArray(via) ? via : [via];
1225
+ if (via === void 0 || names.length === 0) {
1226
+ throw new CyphraValidationError(
1227
+ `${op} on ${model.name}: via is required (a relation name or a list of them).`
1228
+ );
1229
+ }
1230
+ const out = [];
1231
+ for (const name of names) {
1232
+ const rel = typeof name === "string" ? relationField(model, name) : void 0;
1233
+ if (!rel) {
1234
+ throw new CyphraValidationError(
1235
+ `${op}: unknown relation "${model.name}.${String(name)}" in via.`
1236
+ );
1237
+ }
1238
+ if (rel.target !== model.name) {
1239
+ throw new CyphraValidationError(
1240
+ `${op}: ${model.name}.${rel.name} leads to ${rel.target}; via takes relations from ${model.name} to ${model.name}.`
1241
+ );
1242
+ }
1243
+ if (!out.includes(rel)) out.push(rel);
1244
+ }
1245
+ return out;
1246
+ }
1247
+ function compileHop(ctx, model, rels, direction, edgePredicate, target, op = "traverse") {
1248
+ if (direction !== void 0 && direction !== "out" && direction !== "in" && direction !== "both") {
1249
+ throw new CyphraValidationError(`${op}: direction must be "out", "in" or "both".`);
1250
+ }
1251
+ const byType = /* @__PURE__ */ new Map();
1252
+ for (const rel of rels) {
1253
+ const dirs = byType.get(rel.relType) ?? /* @__PURE__ */ new Set();
1254
+ if (direction === "both") dirs.add("OUT").add("IN");
1255
+ else dirs.add(direction === "out" ? "OUT" : direction === "in" ? "IN" : rel.direction);
1256
+ byType.set(rel.relType, dirs);
1257
+ }
1258
+ const kinds = new Set([...byType.values()].map((d) => d.size === 2 ? "BOTH" : [...d][0]));
1259
+ const e = ctx.variable("e");
1260
+ const types = [...byType.keys()].map(q).join("|");
1261
+ const label = `:${q(model.label)}`;
1262
+ const preds = [];
1263
+ let pattern;
1264
+ if (kinds.size === 1) {
1265
+ const kind = [...kinds][0];
1266
+ const edge = `[${e}:${types}]`;
1267
+ const arrow = kind === "OUT" ? `-${edge}->` : kind === "IN" ? `<-${edge}-` : `-${edge}-`;
1268
+ pattern = `(${label})${arrow}(${target ?? ""}${label})`;
1269
+ } else {
1270
+ const x = ctx.variable("x");
1271
+ const y = target ?? ctx.variable("y");
1272
+ pattern = `(${x}${label})-[${e}:${types}]-(${y}${label})`;
1273
+ const alts = [...byType].map(([type, dirs]) => {
1274
+ const t = `type(${e}) = ${ctx.param(type)}`;
1275
+ if (dirs.size === 2) return t;
1276
+ return `${t} AND ${dirs.has("OUT") ? "startNode" : "endNode"}(${e}) = ${x}`;
1277
+ });
1278
+ preds.push(alts.map((a) => `(${a})`).join(" OR "));
1279
+ }
1280
+ const edgeWhere = edgePredicate(e);
1281
+ if (edgeWhere) preds.push(edgeWhere);
1282
+ const where = preds.length === 0 ? "" : ` WHERE ${preds.map((p) => `(${p})`).join(" AND ")}`;
1283
+ return `${pattern}${where}`;
1284
+ }
1285
+ function edgeWhereModel(schema, model, rels, op = "traverse") {
1286
+ const names = new Set(rels.map((r) => r.edge));
1287
+ const name = rels[0].edge;
1288
+ const edge = name ? schema.relationships.find((r) => r.name === name) : void 0;
1289
+ if (!edge || names.size !== 1) {
1290
+ throw new CyphraValidationError(
1291
+ `${op}: edgeWhere needs every relation in via (${rels.map((r) => `${model.name}.${r.name}`).join(", ")}) to share one relationship { \u2026 } model.`
1292
+ );
1293
+ }
1294
+ return { name: edge.name, label: edge.relType, uniqueFields: [], fields: edge.properties };
1295
+ }
1296
+ function compileTraverse(ctx, model, args, maxDepth) {
1297
+ for (const k of Object.keys(args)) {
1298
+ if (!ARG_KEYS.has(k)) throw new CyphraValidationError(`traverse: unknown argument "${k}".`);
1299
+ }
1300
+ if (!isPlainObject3(args.from)) {
1301
+ throw new CyphraValidationError(
1302
+ `traverse on ${model.name}: from is required (a where filter on the start nodes).`
1303
+ );
1304
+ }
1305
+ const rels = viaRelations(model, args.via);
1306
+ const { min, max } = parseDepth(args.depth, maxDepth);
1307
+ const distinct = args.distinct ?? true;
1308
+ const returnPaths = args.returnPaths ?? false;
1309
+ if (typeof distinct !== "boolean") throw new CyphraValidationError("distinct must be a boolean.");
1310
+ if (typeof returnPaths !== "boolean") {
1311
+ throw new CyphraValidationError("returnPaths must be a boolean.");
1312
+ }
1313
+ const label = q(model.label);
1314
+ const from = compileWhere(ctx, model, "s", args.from);
1315
+ const hop = compileHop(
1316
+ ctx,
1317
+ model,
1318
+ rels,
1319
+ args.direction,
1320
+ (e) => args.edgeWhere === void 0 ? null : compileWhere(ctx, edgeWhereModel(ctx.schema, model, rels), e, args.edgeWhere)
1321
+ );
1322
+ const reached = [min > 0 ? "n <> s" : null, compileWhere(ctx, model, "n", args.where)].filter(
1323
+ (x) => Boolean(x)
1324
+ );
1325
+ let text = `MATCH (s:${label})${from ? ` WHERE ${from}` : ""} `;
1326
+ text += `MATCH ${returnPaths ? "p = " : ""}(s)(${hop}){${min},${max}}(n:${label})`;
1327
+ if (reached.length) text += ` WHERE ${reached.map((x) => `(${x})`).join(" AND ")}`;
1328
+ const paging = compilePaging(ctx, model, "n", args);
1329
+ const keep = returnPaths ? "n, p" : "n";
1330
+ if (returnPaths && distinct) {
1331
+ const x = ctx.variable("x");
1332
+ text += ` WITH n, collect(p) AS ps, min(length(p)) AS d`;
1333
+ text += ` WITH n, [${x} IN ps WHERE length(${x}) = d][0] AS p`;
1334
+ if (paging) text += ` WITH n, p${paging}`;
1335
+ } else {
1336
+ text += ` WITH ${distinct ? "DISTINCT " : ""}${keep}${paging}`;
1337
+ }
1338
+ const { expr, shape } = compileProjection(ctx, model, "n", args);
1339
+ text += ` RETURN ${expr} AS row`;
1340
+ if (returnPaths) text += `, ${compilePath(ctx, "p")} AS path`;
1341
+ const order = compileOrderBy(ctx, model, "n", args.orderBy);
1342
+ if (order) text += ` ORDER BY ${order}`;
1343
+ return {
1344
+ text,
1345
+ params: ctx.params,
1346
+ decode: (rows) => rows.map((r) => {
1347
+ const node = decodeRow(shape, r.row);
1348
+ return returnPaths ? { node, path: decodePath(ctx.schema, r.path) } : node;
1349
+ })
1350
+ };
1351
+ }
1352
+
1353
+ // src/orm/shortest.ts
1354
+ var ARG_KEYS2 = /* @__PURE__ */ new Set([
1355
+ "from",
1356
+ "to",
1357
+ "via",
1358
+ "direction",
1359
+ "maxDepth",
1360
+ "where",
1361
+ "edgeWhere",
1362
+ "select",
1363
+ "include"
1364
+ ]);
1365
+ function isPlainObject4(v) {
1366
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1367
+ }
1368
+ function compileShortestPath(ctx, model, args, cap, all) {
1369
+ const op = all ? "allShortestPaths" : "shortestPath";
1370
+ for (const k of Object.keys(args)) {
1371
+ if (!ARG_KEYS2.has(k) && !(all && k === "take")) {
1372
+ throw new CyphraValidationError(`${op}: unknown argument "${k}".`);
1373
+ }
1374
+ }
1375
+ for (const end of ["from", "to"]) {
1376
+ if (!isPlainObject4(args[end])) {
1377
+ throw new CyphraValidationError(
1378
+ `${op} on ${model.name}: ${end} is required (a where filter on the ${end === "from" ? "start" : "end"} nodes).`
1379
+ );
1380
+ }
1381
+ }
1382
+ if (args.maxDepth === void 0) {
1383
+ throw new CyphraValidationError(`${op} on ${model.name}: maxDepth is required.`);
1384
+ }
1385
+ const max = hopBound(args.maxDepth, "maxDepth", 1, cap, op);
1386
+ const rels = viaRelations(model, args.via, op);
1387
+ const label = q(model.label);
1388
+ const from = compileWhere(ctx, model, "s", args.from);
1389
+ const to = compileWhere(ctx, model, "t", args.to);
1390
+ const y = args.where === void 0 ? void 0 : ctx.variable("y");
1391
+ const hop = compileHop(
1392
+ ctx,
1393
+ model,
1394
+ rels,
1395
+ args.direction,
1396
+ (e) => args.edgeWhere === void 0 ? null : compileWhere(ctx, edgeWhereModel(ctx.schema, model, rels, op), e, args.edgeWhere),
1397
+ y,
1398
+ op
1399
+ );
1400
+ let pattern = `(s)(${hop}){0,${max}}(t)`;
1401
+ if (y) {
1402
+ const x = ctx.variable("x");
1403
+ const where = compileWhere(ctx, model, x, args.where);
1404
+ if (where) pattern = `(${pattern} WHERE all(${x} IN ${y}[..-1] WHERE ${where}))`;
1405
+ }
1406
+ let text = `MATCH (s:${label})${from ? ` WHERE ${from}` : ""} `;
1407
+ text += `MATCH (t:${label})${to ? ` WHERE ${to}` : ""} `;
1408
+ text += `MATCH p = ${all ? "ALL SHORTEST" : "SHORTEST 1"} ${pattern}`;
1409
+ if (all) {
1410
+ const x = ctx.variable("x");
1411
+ text += ` WITH collect(p) AS ps, min(length(p)) AS d`;
1412
+ text += ` UNWIND [${x} IN ps WHERE length(${x}) = d] AS p`;
1413
+ if (args.take !== void 0) {
1414
+ text += ` WITH p LIMIT ${ctx.param(intParam(nonNegativeInt(args.take, "take")))}`;
1415
+ }
1416
+ } else {
1417
+ text += ` WITH p ORDER BY length(p) LIMIT 1`;
1418
+ }
1419
+ const n = ctx.variable("n");
1420
+ const { expr, shape } = compileProjection(ctx, model, n, args);
1421
+ text += ` RETURN [${n} IN nodes(p) | ${expr}] AS nodes, ${compilePath(ctx, "p")} AS path`;
1422
+ return {
1423
+ text,
1424
+ params: ctx.params,
1425
+ decode: (rows) => rows.map((r) => ({
1426
+ nodes: (r.nodes ?? []).map((node) => decodeRow(shape, node)),
1427
+ edges: decodePath(ctx.schema, r.path).edges
1428
+ }))
1429
+ };
1430
+ }
1431
+
1432
+ // src/orm/engine.ts
1433
+ function isPlainObject5(v) {
1434
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1435
+ }
660
1436
  function toCount(v) {
661
- return isInt2(v) ? integerToNumber(v) : Number(v ?? 0);
1437
+ return isInt3(v) ? integerToNumber(v) : Number(v ?? 0);
662
1438
  }
663
1439
  var ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
664
1440
  function createCuid() {
@@ -678,14 +1454,16 @@ function asArray(v) {
678
1454
  return Array.isArray(v) ? v : [v];
679
1455
  }
680
1456
  var ModelEngine = class _ModelEngine {
681
- constructor(schema, model, runner) {
1457
+ constructor(schema, model, runner, options = {}) {
682
1458
  this.schema = schema;
683
1459
  this.model = model;
684
1460
  this.runner = runner;
1461
+ this.options = options;
685
1462
  }
686
1463
  schema;
687
1464
  model;
688
1465
  runner;
1466
+ options;
689
1467
  ctx() {
690
1468
  return new QueryContext(this.schema);
691
1469
  }
@@ -704,7 +1482,7 @@ var ModelEngine = class _ModelEngine {
704
1482
  if (where) text += ` WHERE ${where}`;
705
1483
  if (paging) text += ` WITH n${paging}`;
706
1484
  text += ` RETURN ${expr} AS row`;
707
- const order = compileOrderBy(this.model, "n", args.orderBy);
1485
+ const order = compileOrderBy(ctx, this.model, "n", args.orderBy);
708
1486
  if (order) text += ` ORDER BY ${order}`;
709
1487
  const rows = await exec(text, ctx.params);
710
1488
  return rows.map((r) => decodeRow(shape, r.row));
@@ -720,9 +1498,9 @@ var ModelEngine = class _ModelEngine {
720
1498
  return decodeRow(shape, rows[0].row);
721
1499
  }
722
1500
  assertUnique(where, op) {
723
- const ok = isPlainObject2(where) && this.model.uniqueFields.some((k) => {
1501
+ const ok = isPlainObject5(where) && this.model.uniqueFields.some((k) => {
724
1502
  const v = where[k];
725
- return v !== void 0 && v !== null && !isPlainObject2(v);
1503
+ return v !== void 0 && v !== null && !isPlainObject5(v);
726
1504
  });
727
1505
  if (!ok) {
728
1506
  throw new CyphraValidationError(
@@ -769,6 +1547,52 @@ var ModelEngine = class _ModelEngine {
769
1547
  return toCount(rows[0]?.c);
770
1548
  });
771
1549
  }
1550
+ /** One statement; see {@link compileAggregate}. */
1551
+ aggregate(args = {}) {
1552
+ return this.runner.read(async (exec) => {
1553
+ if (!isPlainObject5(args))
1554
+ throw new CyphraValidationError("aggregate args must be an object.");
1555
+ const c = compileAggregate(this.ctx(), this.model, args);
1556
+ return c.decode(await exec(c.text, c.params));
1557
+ });
1558
+ }
1559
+ /** One statement; see {@link compileGroupBy}. */
1560
+ groupBy(args) {
1561
+ return this.runner.read(async (exec) => {
1562
+ if (!isPlainObject5(args)) throw new CyphraValidationError("groupBy args must be an object.");
1563
+ const c = compileGroupBy(this.ctx(), this.model, args);
1564
+ return c.decode(await exec(c.text, c.params));
1565
+ });
1566
+ }
1567
+ /** One statement; see {@link compileTraverse}. */
1568
+ traverse(args) {
1569
+ return this.runner.read(async (exec) => {
1570
+ if (!isPlainObject5(args)) throw new CyphraValidationError("traverse args must be an object.");
1571
+ const max = this.options.maxTraversalDepth ?? DEFAULT_MAX_TRAVERSAL_DEPTH;
1572
+ const c = compileTraverse(this.ctx(), this.model, args, max);
1573
+ return c.decode(await exec(c.text, c.params));
1574
+ });
1575
+ }
1576
+ /** One statement; see {@link compileShortestPath}. */
1577
+ async shortestPath(args) {
1578
+ return (await this.shortest(args, false))[0] ?? null;
1579
+ }
1580
+ /** One statement; see {@link compileShortestPath}. */
1581
+ allShortestPaths(args) {
1582
+ return this.shortest(args, true);
1583
+ }
1584
+ shortest(args, all) {
1585
+ return this.runner.read(async (exec) => {
1586
+ if (!isPlainObject5(args)) {
1587
+ throw new CyphraValidationError(
1588
+ `${all ? "allShortestPaths" : "shortestPath"} args must be an object.`
1589
+ );
1590
+ }
1591
+ const max = this.options.maxTraversalDepth ?? DEFAULT_MAX_TRAVERSAL_DEPTH;
1592
+ const c = compileShortestPath(this.ctx(), this.model, args, max, all);
1593
+ return c.decode(await exec(c.text, c.params));
1594
+ });
1595
+ }
772
1596
  // -------------------------------------------------------------------------
773
1597
  // Write helpers
774
1598
  // -------------------------------------------------------------------------
@@ -776,7 +1600,7 @@ var ModelEngine = class _ModelEngine {
776
1600
  return new QueryContext(this.schema).node(name);
777
1601
  }
778
1602
  engineFor(model) {
779
- return model === this.model ? this : new _ModelEngine(this.schema, model, this.runner);
1603
+ return model === this.model ? this : new _ModelEngine(this.schema, model, this.runner, this.options);
780
1604
  }
781
1605
  /** Encode scalar data for CREATE, applying defaults and checking required fields. */
782
1606
  static createProps(owner, fields, data) {
@@ -803,7 +1627,7 @@ var ModelEngine = class _ModelEngine {
803
1627
  return props;
804
1628
  }
805
1629
  splitData(data, op) {
806
- if (!isPlainObject2(data))
1630
+ if (!isPlainObject5(data))
807
1631
  throw new CyphraValidationError(`${this.model.name}.${op}: data must be an object.`);
808
1632
  const scalars = {};
809
1633
  const relations = {};
@@ -827,7 +1651,7 @@ var ModelEngine = class _ModelEngine {
827
1651
  `${this.model.name}.${rel.name}: $edge given but no relationship model types this edge.`
828
1652
  );
829
1653
  }
830
- if (!isPlainObject2(input)) throw new CyphraValidationError("$edge must be an object.");
1654
+ if (!isPlainObject5(input)) throw new CyphraValidationError("$edge must be an object.");
831
1655
  for (const k of Object.keys(input)) {
832
1656
  if (!edgeModel.properties.some((p) => p.name === k)) {
833
1657
  throw new CyphraValidationError(`Unknown edge property "${edgeModel.name}.${k}".`);
@@ -846,7 +1670,7 @@ var ModelEngine = class _ModelEngine {
846
1670
  }
847
1671
  /** Only the `$edge` properties the caller set (no defaults), for updating an existing edge. */
848
1672
  explicitEdgeProps(rel, input) {
849
- if (!rel.edge || !isPlainObject2(input)) return {};
1673
+ if (!rel.edge || !isPlainObject5(input)) return {};
850
1674
  const edgeModel = this.schema.relationships.find((r) => r.name === rel.edge);
851
1675
  const props = {};
852
1676
  for (const f of edgeModel.properties) {
@@ -883,7 +1707,7 @@ var ModelEngine = class _ModelEngine {
883
1707
  * defaults, e.g. `@default(now())`, are kept).
884
1708
  */
885
1709
  async connect(exec, id, rel, item) {
886
- if (!isPlainObject2(item))
1710
+ if (!isPlainObject5(item))
887
1711
  throw new CyphraValidationError(`${rel.name}.connect expects unique where objects.`);
888
1712
  const { $edge, ...where } = item;
889
1713
  const target = this.node(rel.target);
@@ -916,7 +1740,7 @@ var ModelEngine = class _ModelEngine {
916
1740
  }
917
1741
  }
918
1742
  async createRelated(exec, id, rel, item) {
919
- if (!isPlainObject2(item))
1743
+ if (!isPlainObject5(item))
920
1744
  throw new CyphraValidationError(`${rel.name}.create expects objects.`);
921
1745
  const { $edge, ...data } = item;
922
1746
  const props = this.edgeProps(rel, $edge);
@@ -938,7 +1762,7 @@ var ModelEngine = class _ModelEngine {
938
1762
  return toCount(rows[0]?.c);
939
1763
  }
940
1764
  async writeRelation(exec, id, rel, spec, mode) {
941
- if (!isPlainObject2(spec)) {
1765
+ if (!isPlainObject5(spec)) {
942
1766
  throw new CyphraValidationError(
943
1767
  `${this.model.name}.${rel.name}: relation writes take { create, connect, \u2026 }.`
944
1768
  );
@@ -971,7 +1795,7 @@ var ModelEngine = class _ModelEngine {
971
1795
  if (rel.many) {
972
1796
  if (disconnect !== void 0) {
973
1797
  for (const item of asArray(disconnect)) {
974
- if (!isPlainObject2(item))
1798
+ if (!isPlainObject5(item))
975
1799
  throw new CyphraValidationError(`${rel.name}.disconnect expects unique where objects.`);
976
1800
  this.engineFor(this.node(rel.target)).assertUnique(
977
1801
  item,
@@ -1004,7 +1828,7 @@ var ModelEngine = class _ModelEngine {
1004
1828
  for (const [k, v] of Object.entries(scalars)) {
1005
1829
  const f = scalarField(this.model, k);
1006
1830
  const ref = `n.${q(k)}`;
1007
- if (isPlainObject2(v) && !f.list) {
1831
+ if (isPlainObject5(v) && !f.list) {
1008
1832
  if (f.type !== "Int" && f.type !== "Float") {
1009
1833
  throw new CyphraValidationError(
1010
1834
  `${this.model.name}.${k}: object updates are only for numbers.`
@@ -1111,7 +1935,7 @@ var ModelEngine = class _ModelEngine {
1111
1935
  const where = args.where;
1112
1936
  const key = this.model.uniqueFields.find((k) => {
1113
1937
  const v = where[k];
1114
- return v !== void 0 && v !== null && !isPlainObject2(v);
1938
+ return v !== void 0 && v !== null && !isPlainObject5(v);
1115
1939
  });
1116
1940
  const keyField = scalarField(this.model, key);
1117
1941
  const create = this.splitData(args.create, "upsert create");
@@ -1205,12 +2029,12 @@ function txExecutor(tx, debug) {
1205
2029
  return res.records.map((r) => r.toObject());
1206
2030
  };
1207
2031
  }
1208
- function buildDelegates(schema, runner) {
2032
+ function buildDelegates(schema, runner, options) {
1209
2033
  const out = {};
1210
2034
  for (const node of schema.nodes) {
1211
2035
  const key = delegateKey(node.name);
1212
2036
  if (key.startsWith("$")) throw new Error(`Model name "${node.name}" is reserved.`);
1213
- out[key] = new ModelEngine(schema, node, runner);
2037
+ out[key] = new ModelEngine(schema, node, runner, options);
1214
2038
  }
1215
2039
  return out;
1216
2040
  }
@@ -1222,6 +2046,11 @@ function rawFor(runner) {
1222
2046
  };
1223
2047
  }
1224
2048
  function createOrm(schema, options) {
2049
+ const { maxTraversalDepth } = options;
2050
+ if (maxTraversalDepth !== void 0 && (!Number.isInteger(maxTraversalDepth) || maxTraversalDepth < 1)) {
2051
+ throw new CyphraValidationError("maxTraversalDepth must be a positive integer.");
2052
+ }
2053
+ const engineOptions = { maxTraversalDepth };
1225
2054
  const owns = !("client" in options);
1226
2055
  const client = "client" in options ? options.client : new CyphraClient(options);
1227
2056
  const debug = options.debug ?? false;
@@ -1232,11 +2061,11 @@ function createOrm(schema, options) {
1232
2061
  const transaction = (fn) => client.withWriteTransaction((tx) => {
1233
2062
  const exec = txExecutor(tx, debug);
1234
2063
  const inTx = { read: (f) => f(exec), write: (f) => f(exec) };
1235
- const txClient = { ...buildDelegates(schema, inTx), $cypher: rawFor(inTx) };
2064
+ const txClient = { ...buildDelegates(schema, inTx, engineOptions), $cypher: rawFor(inTx) };
1236
2065
  return fn(txClient);
1237
2066
  });
1238
2067
  return {
1239
- ...buildDelegates(schema, runner),
2068
+ ...buildDelegates(schema, runner, engineOptions),
1240
2069
  $cypher: rawFor(runner),
1241
2070
  $transaction: transaction,
1242
2071
  $client: client,