@cyphra/runtime 0.5.0 → 0.7.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
@@ -196,6 +196,9 @@ function integerToNumber(v) {
196
196
  }
197
197
  return v.toNumber();
198
198
  }
199
+ function decodeCount(v) {
200
+ return isInt(v) ? integerToNumber(v) : Number(v ?? 0);
201
+ }
199
202
  function utcDateTime(d) {
200
203
  return new neo4j2.types.DateTime(
201
204
  d.getUTCFullYear(),
@@ -236,6 +239,26 @@ function encodeOne(type, value, where) {
236
239
  }
237
240
  throw new CyphraValidationError(`${where}: expected ${type}, got ${describe(value)}.`);
238
241
  }
242
+ function encodeVector(value, dimensions, where) {
243
+ if (!Array.isArray(value) && !ArrayBuffer.isView(value)) {
244
+ throw new CyphraValidationError(
245
+ `${where}: expected a vector (number[] of length ${dimensions}), got ${describe(value)}.`
246
+ );
247
+ }
248
+ const arr = Array.from(value);
249
+ if (arr.length !== dimensions) {
250
+ throw new CyphraValidationError(
251
+ `${where}: expected a vector of ${dimensions} dimensions, got ${arr.length}.`
252
+ );
253
+ }
254
+ for (let i = 0; i < arr.length; i++) {
255
+ const x = arr[i];
256
+ if (typeof x !== "number" || !Number.isFinite(x)) {
257
+ throw new CyphraValidationError(`${where}[${i}]: expected a finite number.`);
258
+ }
259
+ }
260
+ return arr;
261
+ }
239
262
  function describe(v) {
240
263
  if (v === null) return "null";
241
264
  if (v instanceof Date) return "Date";
@@ -250,6 +273,7 @@ function encodeScalar(field, value, owner) {
250
273
  }
251
274
  return null;
252
275
  }
276
+ if (field.type === "Vector") return encodeVector(value, field.dimensions ?? 0, where);
253
277
  if (field.list) {
254
278
  if (!Array.isArray(value)) {
255
279
  throw new CyphraValidationError(`${where}: expected an array.`);
@@ -259,6 +283,11 @@ function encodeScalar(field, value, owner) {
259
283
  return encodeOne(field.type, value, where);
260
284
  }
261
285
  function encodeFilterValue(field, value, owner) {
286
+ if (field.type === "Vector") {
287
+ throw new CyphraValidationError(
288
+ `${owner}.${field.name}: Vector fields can only be filtered on null (use findSimilar to search them).`
289
+ );
290
+ }
262
291
  return encodeOne(field.type, value, `${owner}.${field.name}`);
263
292
  }
264
293
  function decodeOne(type, value) {
@@ -276,6 +305,10 @@ function decodeOne(type, value) {
276
305
  return value;
277
306
  }
278
307
  function decodeScalar(field, value) {
308
+ if (field.type === "Vector") {
309
+ if (value === null || value === void 0) return null;
310
+ return Array.from(value, (x) => isInt(x) ? integerToNumber(x) : x);
311
+ }
279
312
  if (field.list) {
280
313
  if (value === null || value === void 0) return [];
281
314
  return value.map((v) => decodeOne(field.type, v));
@@ -392,8 +425,20 @@ function compileListFilter(ctx, model, field, ref, filter) {
392
425
  }
393
426
  return and(parts);
394
427
  }
428
+ function compileVectorFilter(model, field, ref, filter) {
429
+ if (filter === null) return `${ref} IS NULL`;
430
+ const keys = isPlainObject(filter) ? Object.keys(filter).filter((k) => filter[k] !== void 0) : [];
431
+ if (isPlainObject(filter) && keys.every((k) => (k === "equals" || k === "not") && filter[k] === null)) {
432
+ const parts = keys.map((k) => k === "equals" ? `${ref} IS NULL` : `${ref} IS NOT NULL`);
433
+ return and(parts);
434
+ }
435
+ throw new CyphraValidationError(
436
+ `${model.name}.${field.name}: Vector fields can only be filtered on null (null, { equals: null }, { not: null }); use findSimilar to search them.`
437
+ );
438
+ }
395
439
  function compileScalarFilter(ctx, model, field, ref, filter, inheritedMode = "default") {
396
440
  if (filter === void 0) return null;
441
+ if (field.type === "Vector") return compileVectorFilter(model, field, ref, filter);
397
442
  if (field.list) return compileListFilter(ctx, model, field, ref, filter);
398
443
  const enc = (v) => encodeFilterValue(field, v, model.name);
399
444
  if (filter === null) return `${ref} IS NULL`;
@@ -537,7 +582,24 @@ function compileWhere(ctx, model, alias, where) {
537
582
  }
538
583
  return and(parts);
539
584
  }
540
- function compileOrderBy(model, alias, orderBy) {
585
+ function compileRelationCount(ctx, model, alias, rel, where) {
586
+ if (!rel.many) {
587
+ throw new CyphraValidationError(
588
+ `${model.name}.${rel.name} is a to-one relation; only to-many relations can be counted.`
589
+ );
590
+ }
591
+ const m = ctx.variable();
592
+ const pattern = relationPattern(ctx, alias, rel, m);
593
+ const inner = compileWhere(ctx, ctx.node(rel.target), m, where);
594
+ return inner ? `COUNT { MATCH ${pattern} WHERE ${inner} }` : `COUNT { MATCH ${pattern} }`;
595
+ }
596
+ function sortDirection(dir, what) {
597
+ if (dir !== "asc" && dir !== "desc") {
598
+ throw new CyphraValidationError(`orderBy ${what} must be "asc" or "desc".`);
599
+ }
600
+ return dir.toUpperCase();
601
+ }
602
+ function compileOrderBy(ctx, model, alias, orderBy) {
541
603
  if (orderBy === void 0 || orderBy === null) return null;
542
604
  const list = Array.isArray(orderBy) ? orderBy : [orderBy];
543
605
  const parts = [];
@@ -545,11 +607,24 @@ function compileOrderBy(model, alias, orderBy) {
545
607
  if (!isPlainObject(item)) throw new CyphraValidationError("orderBy entries must be objects.");
546
608
  for (const [key, dir] of Object.entries(item)) {
547
609
  if (dir === void 0) continue;
548
- scalarOrThrow(model, key);
549
- if (dir !== "asc" && dir !== "desc") {
550
- throw new CyphraValidationError(`orderBy ${model.name}.${key} must be "asc" or "desc".`);
610
+ const rel = relationField(model, key);
611
+ if (rel) {
612
+ if (!isPlainObject(dir) || Object.keys(dir).some((k) => k !== "_count")) {
613
+ throw new CyphraValidationError(
614
+ `orderBy ${model.name}.${key} takes { _count: "asc" | "desc" }.`
615
+ );
616
+ }
617
+ if (dir._count === void 0) continue;
618
+ const d = sortDirection(dir._count, `${model.name}.${key}._count`);
619
+ parts.push(`${compileRelationCount(ctx, model, alias, rel)} ${d}`);
620
+ continue;
621
+ }
622
+ if (scalarOrThrow(model, key).type === "Vector") {
623
+ throw new CyphraValidationError(
624
+ `orderBy ${model.name}.${key}: Vector fields cannot be sorted.`
625
+ );
551
626
  }
552
- parts.push(`${alias}.${q(key)} ${dir.toUpperCase()}`);
627
+ parts.push(`${alias}.${q(key)} ${sortDirection(dir, `${model.name}.${key}`)}`);
553
628
  }
554
629
  }
555
630
  return parts.length ? parts.join(", ") : null;
@@ -562,7 +637,7 @@ function nonNegativeInt(v, name) {
562
637
  }
563
638
  function compilePaging(ctx, model, alias, args) {
564
639
  let s = "";
565
- const order = compileOrderBy(model, alias, args.orderBy);
640
+ const order = compileOrderBy(ctx, model, alias, args.orderBy);
566
641
  if (order) s += ` ORDER BY ${order}`;
567
642
  if (args.skip !== void 0)
568
643
  s += ` SKIP ${ctx.param(intParam(nonNegativeInt(args.skip, "skip")))}`;
@@ -580,9 +655,14 @@ function compileProjection(ctx, model, alias, args, extraEntries = []) {
580
655
  const scalars = [];
581
656
  const rels = [];
582
657
  const allScalars = model.fields.filter((f) => f.kind === "scalar");
658
+ let counts;
583
659
  const takeRelations = (spec, label) => {
584
660
  for (const [key, v] of Object.entries(spec)) {
585
661
  if (v === void 0 || v === false) continue;
662
+ if (key === "_count") {
663
+ counts = relationCounts(model, v, label);
664
+ continue;
665
+ }
586
666
  const f = model.fields.find((x) => x.name === key);
587
667
  if (!f) throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in ${label}.`);
588
668
  if (f.kind === "scalar") {
@@ -635,12 +715,60 @@ function compileProjection(ctx, model, alias, args, extraEntries = []) {
635
715
  ...edgeModel ? { edge: edgeModel.properties } : {}
636
716
  });
637
717
  }
718
+ if (counts) {
719
+ const map = counts.map(
720
+ ({ field, where }) => `${q(field.name)}: ${compileRelationCount(ctx, model, alias, field, where)}`
721
+ );
722
+ entries.push(`${q("_count")}: {${map.join(", ")}}`);
723
+ }
638
724
  entries.push(...extraEntries);
639
725
  return {
640
726
  expr: `${alias}{${entries.join(", ")}}`,
641
- shape: { model, scalars, relations: relShapes }
727
+ shape: {
728
+ model,
729
+ scalars,
730
+ relations: relShapes,
731
+ ...counts ? { counts: counts.map((c) => c.field) } : {}
732
+ }
642
733
  };
643
734
  }
735
+ function relationCounts(model, spec, label) {
736
+ if (spec === true) {
737
+ return model.fields.filter((f) => f.kind === "relation" && f.many).map((field) => ({ field, where: void 0 }));
738
+ }
739
+ if (!isPlainObject(spec) || Object.keys(spec).some((k) => k !== "select")) {
740
+ throw new CyphraValidationError(
741
+ `${label}._count on ${model.name} takes true or { select: { <relation>: true | { where } } }.`
742
+ );
743
+ }
744
+ if (!isPlainObject(spec.select)) {
745
+ throw new CyphraValidationError(`${label}._count.select on ${model.name} must be an object.`);
746
+ }
747
+ const out = [];
748
+ for (const [key, v] of Object.entries(spec.select)) {
749
+ if (v === void 0 || v === false) continue;
750
+ const field = relationField(model, key);
751
+ if (!field) {
752
+ throw new CyphraValidationError(
753
+ `Unknown relation "${model.name}.${key}" in ${label}._count.select.`
754
+ );
755
+ }
756
+ if (!field.many) {
757
+ throw new CyphraValidationError(
758
+ `${model.name}.${key} is a to-one relation; only to-many relations can be counted.`
759
+ );
760
+ }
761
+ if (v === true) out.push({ field, where: void 0 });
762
+ else if (isPlainObject(v) && Object.keys(v).every((k) => k === "where")) {
763
+ out.push({ field, where: v.where });
764
+ } else {
765
+ throw new CyphraValidationError(
766
+ `${label}._count.select.${key} on ${model.name} takes true or { where }.`
767
+ );
768
+ }
769
+ }
770
+ return out;
771
+ }
644
772
  function decodeRow(shape, row) {
645
773
  if (row === null || row === void 0) return null;
646
774
  const src = row;
@@ -660,6 +788,12 @@ function decodeRow(shape, row) {
660
788
  const v = src[r.field.name];
661
789
  out[r.field.name] = r.field.many ? (v ?? []).map(decodeItem) : decodeItem(v);
662
790
  }
791
+ if (shape.counts) {
792
+ const raw = src["_count"] ?? {};
793
+ const counts = {};
794
+ for (const f of shape.counts) counts[f.name] = decodeCount(raw[f.name]);
795
+ out._count = counts;
796
+ }
663
797
  return out;
664
798
  }
665
799
 
@@ -707,7 +841,7 @@ function aggExpr(alias, op, target) {
707
841
  }
708
842
  }
709
843
  function decodeAgg(op, target, v) {
710
- if (op === "_count") return isInt2(v) ? integerToNumber(v) : Number(v ?? 0);
844
+ if (op === "_count") return decodeCount(v);
711
845
  if (v === null || v === void 0) return null;
712
846
  if (op === "_avg") return isInt2(v) ? integerToNumber(v) : Number(v);
713
847
  return decodeScalar(target, v);
@@ -1040,10 +1174,505 @@ function compileGroupBy(ctx, model, args) {
1040
1174
  };
1041
1175
  }
1042
1176
 
1043
- // src/orm/engine.ts
1177
+ // src/orm/path.ts
1178
+ function compilePath(ctx, path) {
1179
+ const x = ctx.variable("x");
1180
+ const i = ctx.variable("i");
1181
+ const rel = `relationships(${path})[${i}]`;
1182
+ const nodes = `[${x} IN nodes(${path}) | {labels: labels(${x}), properties: properties(${x})}]`;
1183
+ const edges = `[${i} IN range(0, length(${path}) - 1) | {type: type(${rel}), properties: properties(${rel}), out: startNode(${rel}) = nodes(${path})[${i}]}]`;
1184
+ return `{nodes: ${nodes}, edges: ${edges}}`;
1185
+ }
1186
+ function decodeProps(fields, raw) {
1187
+ const src = raw ?? {};
1188
+ const out = {};
1189
+ for (const f of fields) out[f.name] = decodeScalar(f, src[f.name]);
1190
+ return out;
1191
+ }
1192
+ function scalarsOf(model) {
1193
+ return model.fields.filter((f) => f.kind === "scalar");
1194
+ }
1195
+ function decodePath(schema, raw) {
1196
+ const src = raw ?? {};
1197
+ const rawNodes = src.nodes ?? [];
1198
+ const models = rawNodes.map((n) => schema.nodes.find((m) => (n.labels ?? []).includes(m.label)));
1199
+ const nodes = rawNodes.map((n, i) => {
1200
+ const model = models[i];
1201
+ return model ? decodeProps(scalarsOf(model), n.properties) : toNative(n.properties ?? {});
1202
+ });
1203
+ const rawEdges = src.edges ?? [];
1204
+ const edges = rawEdges.map((e, i) => {
1205
+ const type = String(e.type);
1206
+ const out = e.out === true;
1207
+ const start = models[out ? i : i + 1]?.name;
1208
+ const end = models[out ? i + 1 : i]?.name;
1209
+ const candidates = schema.relationships.filter((r) => r.relType === type);
1210
+ const edgeModel = candidates.find((r) => r.from === start && r.to === end) ?? (candidates.length === 1 ? candidates[0] : void 0);
1211
+ return {
1212
+ type,
1213
+ direction: out ? "out" : "in",
1214
+ properties: edgeModel ? decodeProps(edgeModel.properties, e.properties) : {}
1215
+ };
1216
+ });
1217
+ return { nodes, edges };
1218
+ }
1219
+
1220
+ // src/orm/traverse.ts
1221
+ var DEFAULT_MAX_TRAVERSAL_DEPTH = 10;
1222
+ var ARG_KEYS = /* @__PURE__ */ new Set([
1223
+ "from",
1224
+ "via",
1225
+ "direction",
1226
+ "depth",
1227
+ "where",
1228
+ "edgeWhere",
1229
+ "distinct",
1230
+ "select",
1231
+ "include",
1232
+ "orderBy",
1233
+ "skip",
1234
+ "take",
1235
+ "returnPaths"
1236
+ ]);
1044
1237
  function isPlainObject3(v) {
1045
1238
  return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1046
1239
  }
1240
+ function hopBound(v, name, min, cap, op = "traverse") {
1241
+ if (typeof v !== "number" || !Number.isInteger(v) || v < min) {
1242
+ throw new CyphraValidationError(`${op}: ${name} must be an integer >= ${min}.`);
1243
+ }
1244
+ if (cap !== void 0 && v > cap) {
1245
+ throw new CyphraValidationError(
1246
+ `${op}: ${name} is ${v}, above the maximum traversal depth of ${cap} (client option maxTraversalDepth).`
1247
+ );
1248
+ }
1249
+ return v;
1250
+ }
1251
+ function parseDepth(depth, cap) {
1252
+ if (!isPlainObject3(depth) || depth.max === void 0) {
1253
+ throw new CyphraValidationError(
1254
+ "traverse: depth.max is required (depth: { min?: number, max: number })."
1255
+ );
1256
+ }
1257
+ for (const k of Object.keys(depth)) {
1258
+ if (k !== "min" && k !== "max") {
1259
+ throw new CyphraValidationError(`traverse: unknown depth option "${k}".`);
1260
+ }
1261
+ }
1262
+ const max = hopBound(depth.max, "depth.max", 1, cap);
1263
+ const min = depth.min === void 0 ? 1 : hopBound(depth.min, "depth.min", 0);
1264
+ if (min > max) {
1265
+ throw new CyphraValidationError(`traverse: depth.min (${min}) is above depth.max (${max}).`);
1266
+ }
1267
+ return { min, max };
1268
+ }
1269
+ function viaRelations(model, via, op = "traverse") {
1270
+ const names = Array.isArray(via) ? via : [via];
1271
+ if (via === void 0 || names.length === 0) {
1272
+ throw new CyphraValidationError(
1273
+ `${op} on ${model.name}: via is required (a relation name or a list of them).`
1274
+ );
1275
+ }
1276
+ const out = [];
1277
+ for (const name of names) {
1278
+ const rel = typeof name === "string" ? relationField(model, name) : void 0;
1279
+ if (!rel) {
1280
+ throw new CyphraValidationError(
1281
+ `${op}: unknown relation "${model.name}.${String(name)}" in via.`
1282
+ );
1283
+ }
1284
+ if (rel.target !== model.name) {
1285
+ throw new CyphraValidationError(
1286
+ `${op}: ${model.name}.${rel.name} leads to ${rel.target}; via takes relations from ${model.name} to ${model.name}.`
1287
+ );
1288
+ }
1289
+ if (!out.includes(rel)) out.push(rel);
1290
+ }
1291
+ return out;
1292
+ }
1293
+ function compileHop(ctx, model, rels, direction, edgePredicate, target, op = "traverse") {
1294
+ if (direction !== void 0 && direction !== "out" && direction !== "in" && direction !== "both") {
1295
+ throw new CyphraValidationError(`${op}: direction must be "out", "in" or "both".`);
1296
+ }
1297
+ const byType = /* @__PURE__ */ new Map();
1298
+ for (const rel of rels) {
1299
+ const dirs = byType.get(rel.relType) ?? /* @__PURE__ */ new Set();
1300
+ if (direction === "both") dirs.add("OUT").add("IN");
1301
+ else dirs.add(direction === "out" ? "OUT" : direction === "in" ? "IN" : rel.direction);
1302
+ byType.set(rel.relType, dirs);
1303
+ }
1304
+ const kinds = new Set([...byType.values()].map((d) => d.size === 2 ? "BOTH" : [...d][0]));
1305
+ const e = ctx.variable("e");
1306
+ const types = [...byType.keys()].map(q).join("|");
1307
+ const label = `:${q(model.label)}`;
1308
+ const preds = [];
1309
+ let pattern;
1310
+ if (kinds.size === 1) {
1311
+ const kind = [...kinds][0];
1312
+ const edge = `[${e}:${types}]`;
1313
+ const arrow = kind === "OUT" ? `-${edge}->` : kind === "IN" ? `<-${edge}-` : `-${edge}-`;
1314
+ pattern = `(${label})${arrow}(${target ?? ""}${label})`;
1315
+ } else {
1316
+ const x = ctx.variable("x");
1317
+ const y = target ?? ctx.variable("y");
1318
+ pattern = `(${x}${label})-[${e}:${types}]-(${y}${label})`;
1319
+ const alts = [...byType].map(([type, dirs]) => {
1320
+ const t = `type(${e}) = ${ctx.param(type)}`;
1321
+ if (dirs.size === 2) return t;
1322
+ return `${t} AND ${dirs.has("OUT") ? "startNode" : "endNode"}(${e}) = ${x}`;
1323
+ });
1324
+ preds.push(alts.map((a) => `(${a})`).join(" OR "));
1325
+ }
1326
+ const edgeWhere = edgePredicate(e);
1327
+ if (edgeWhere) preds.push(edgeWhere);
1328
+ const where = preds.length === 0 ? "" : ` WHERE ${preds.map((p) => `(${p})`).join(" AND ")}`;
1329
+ return `${pattern}${where}`;
1330
+ }
1331
+ function edgeWhereModel(schema, model, rels, op = "traverse") {
1332
+ const names = new Set(rels.map((r) => r.edge));
1333
+ const name = rels[0].edge;
1334
+ const edge = name ? schema.relationships.find((r) => r.name === name) : void 0;
1335
+ if (!edge || names.size !== 1) {
1336
+ throw new CyphraValidationError(
1337
+ `${op}: edgeWhere needs every relation in via (${rels.map((r) => `${model.name}.${r.name}`).join(", ")}) to share one relationship { \u2026 } model.`
1338
+ );
1339
+ }
1340
+ return { name: edge.name, label: edge.relType, uniqueFields: [], fields: edge.properties };
1341
+ }
1342
+ function compileTraverse(ctx, model, args, maxDepth) {
1343
+ for (const k of Object.keys(args)) {
1344
+ if (!ARG_KEYS.has(k)) throw new CyphraValidationError(`traverse: unknown argument "${k}".`);
1345
+ }
1346
+ if (!isPlainObject3(args.from)) {
1347
+ throw new CyphraValidationError(
1348
+ `traverse on ${model.name}: from is required (a where filter on the start nodes).`
1349
+ );
1350
+ }
1351
+ const rels = viaRelations(model, args.via);
1352
+ const { min, max } = parseDepth(args.depth, maxDepth);
1353
+ const distinct = args.distinct ?? true;
1354
+ const returnPaths = args.returnPaths ?? false;
1355
+ if (typeof distinct !== "boolean") throw new CyphraValidationError("distinct must be a boolean.");
1356
+ if (typeof returnPaths !== "boolean") {
1357
+ throw new CyphraValidationError("returnPaths must be a boolean.");
1358
+ }
1359
+ const label = q(model.label);
1360
+ const from = compileWhere(ctx, model, "s", args.from);
1361
+ const hop = compileHop(
1362
+ ctx,
1363
+ model,
1364
+ rels,
1365
+ args.direction,
1366
+ (e) => args.edgeWhere === void 0 ? null : compileWhere(ctx, edgeWhereModel(ctx.schema, model, rels), e, args.edgeWhere)
1367
+ );
1368
+ const reached = [min > 0 ? "n <> s" : null, compileWhere(ctx, model, "n", args.where)].filter(
1369
+ (x) => Boolean(x)
1370
+ );
1371
+ let text = `MATCH (s:${label})${from ? ` WHERE ${from}` : ""} `;
1372
+ text += `MATCH ${returnPaths ? "p = " : ""}(s)(${hop}){${min},${max}}(n:${label})`;
1373
+ if (reached.length) text += ` WHERE ${reached.map((x) => `(${x})`).join(" AND ")}`;
1374
+ const paging = compilePaging(ctx, model, "n", args);
1375
+ const keep = returnPaths ? "n, p" : "n";
1376
+ if (returnPaths && distinct) {
1377
+ const x = ctx.variable("x");
1378
+ text += ` WITH n, collect(p) AS ps, min(length(p)) AS d`;
1379
+ text += ` WITH n, [${x} IN ps WHERE length(${x}) = d][0] AS p`;
1380
+ if (paging) text += ` WITH n, p${paging}`;
1381
+ } else {
1382
+ text += ` WITH ${distinct ? "DISTINCT " : ""}${keep}${paging}`;
1383
+ }
1384
+ const { expr, shape } = compileProjection(ctx, model, "n", args);
1385
+ text += ` RETURN ${expr} AS row`;
1386
+ if (returnPaths) text += `, ${compilePath(ctx, "p")} AS path`;
1387
+ const order = compileOrderBy(ctx, model, "n", args.orderBy);
1388
+ if (order) text += ` ORDER BY ${order}`;
1389
+ return {
1390
+ text,
1391
+ params: ctx.params,
1392
+ decode: (rows) => rows.map((r) => {
1393
+ const node = decodeRow(shape, r.row);
1394
+ return returnPaths ? { node, path: decodePath(ctx.schema, r.path) } : node;
1395
+ })
1396
+ };
1397
+ }
1398
+
1399
+ // src/orm/shortest.ts
1400
+ var ARG_KEYS2 = /* @__PURE__ */ new Set([
1401
+ "from",
1402
+ "to",
1403
+ "via",
1404
+ "direction",
1405
+ "maxDepth",
1406
+ "where",
1407
+ "edgeWhere",
1408
+ "select",
1409
+ "include"
1410
+ ]);
1411
+ function isPlainObject4(v) {
1412
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1413
+ }
1414
+ function compileShortestPath(ctx, model, args, cap, all) {
1415
+ const op = all ? "allShortestPaths" : "shortestPath";
1416
+ for (const k of Object.keys(args)) {
1417
+ if (!ARG_KEYS2.has(k) && !(all && k === "take")) {
1418
+ throw new CyphraValidationError(`${op}: unknown argument "${k}".`);
1419
+ }
1420
+ }
1421
+ for (const end of ["from", "to"]) {
1422
+ if (!isPlainObject4(args[end])) {
1423
+ throw new CyphraValidationError(
1424
+ `${op} on ${model.name}: ${end} is required (a where filter on the ${end === "from" ? "start" : "end"} nodes).`
1425
+ );
1426
+ }
1427
+ }
1428
+ if (args.maxDepth === void 0) {
1429
+ throw new CyphraValidationError(`${op} on ${model.name}: maxDepth is required.`);
1430
+ }
1431
+ const max = hopBound(args.maxDepth, "maxDepth", 1, cap, op);
1432
+ const rels = viaRelations(model, args.via, op);
1433
+ const label = q(model.label);
1434
+ const from = compileWhere(ctx, model, "s", args.from);
1435
+ const to = compileWhere(ctx, model, "t", args.to);
1436
+ const y = args.where === void 0 ? void 0 : ctx.variable("y");
1437
+ const hop = compileHop(
1438
+ ctx,
1439
+ model,
1440
+ rels,
1441
+ args.direction,
1442
+ (e) => args.edgeWhere === void 0 ? null : compileWhere(ctx, edgeWhereModel(ctx.schema, model, rels, op), e, args.edgeWhere),
1443
+ y,
1444
+ op
1445
+ );
1446
+ let pattern = `(s)(${hop}){0,${max}}(t)`;
1447
+ if (y) {
1448
+ const x = ctx.variable("x");
1449
+ const where = compileWhere(ctx, model, x, args.where);
1450
+ if (where) pattern = `(${pattern} WHERE all(${x} IN ${y}[..-1] WHERE ${where}))`;
1451
+ }
1452
+ let text = `MATCH (s:${label})${from ? ` WHERE ${from}` : ""} `;
1453
+ text += `MATCH (t:${label})${to ? ` WHERE ${to}` : ""} `;
1454
+ text += `MATCH p = ${all ? "ALL SHORTEST" : "SHORTEST 1"} ${pattern}`;
1455
+ if (all) {
1456
+ const x = ctx.variable("x");
1457
+ text += ` WITH collect(p) AS ps, min(length(p)) AS d`;
1458
+ text += ` UNWIND [${x} IN ps WHERE length(${x}) = d] AS p`;
1459
+ if (args.take !== void 0) {
1460
+ text += ` WITH p LIMIT ${ctx.param(intParam(nonNegativeInt(args.take, "take")))}`;
1461
+ }
1462
+ } else {
1463
+ text += ` WITH p ORDER BY length(p) LIMIT 1`;
1464
+ }
1465
+ const n = ctx.variable("n");
1466
+ const { expr, shape } = compileProjection(ctx, model, n, args);
1467
+ text += ` RETURN [${n} IN nodes(p) | ${expr}] AS nodes, ${compilePath(ctx, "p")} AS path`;
1468
+ return {
1469
+ text,
1470
+ params: ctx.params,
1471
+ decode: (rows) => rows.map((r) => ({
1472
+ nodes: (r.nodes ?? []).map((node) => decodeRow(shape, node)),
1473
+ edges: decodePath(ctx.schema, r.path).edges
1474
+ }))
1475
+ };
1476
+ }
1477
+
1478
+ // src/orm/vector.ts
1479
+ var ARG_KEYS3 = /* @__PURE__ */ new Set([
1480
+ "field",
1481
+ "vector",
1482
+ "k",
1483
+ "where",
1484
+ "select",
1485
+ "include",
1486
+ "minScore",
1487
+ "candidates",
1488
+ "maxCandidates",
1489
+ "exact"
1490
+ ]);
1491
+ var CANDIDATE_GROWTH = 4;
1492
+ function positiveInt(v, name, op) {
1493
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {
1494
+ throw new CyphraValidationError(`${op}: ${name} must be a positive integer.`);
1495
+ }
1496
+ return v;
1497
+ }
1498
+ function toScore(v) {
1499
+ return typeof v === "number" ? v : Number(v);
1500
+ }
1501
+ function vectorField(model, name, op) {
1502
+ const indexed = model.fields.filter(
1503
+ (f2) => f2.kind === "scalar" && Boolean(f2.vectorIndex)
1504
+ );
1505
+ if (typeof name !== "string") {
1506
+ throw new CyphraValidationError(
1507
+ `${op}: field is required (${indexed.map((f2) => f2.name).join(", ") || `${model.name} has no @vectorIndex field`}).`
1508
+ );
1509
+ }
1510
+ const f = model.fields.find((x) => x.name === name);
1511
+ if (!f || f.kind !== "scalar" || f.type !== "Vector") {
1512
+ throw new CyphraValidationError(`${op}: ${model.name}.${name} is not a Vector field.`);
1513
+ }
1514
+ if (!f.vectorIndex) {
1515
+ throw new CyphraValidationError(
1516
+ `${op}: ${model.name}.${name} has no @vectorIndex; declare one to search it.`
1517
+ );
1518
+ }
1519
+ return f;
1520
+ }
1521
+ async function findSimilar(exec, ctxFactory, model, args) {
1522
+ const op = `${model.name}.findSimilar`;
1523
+ for (const key of Object.keys(args)) {
1524
+ if (!ARG_KEYS3.has(key)) throw new CyphraValidationError(`${op}: unknown argument "${key}".`);
1525
+ }
1526
+ const field = vectorField(model, args.field, op);
1527
+ const index = field.vectorIndex;
1528
+ const vector = encodeVector(args.vector, field.dimensions ?? 0, `${op} vector`);
1529
+ if (args.k === void 0) throw new CyphraValidationError(`${op}: k is required.`);
1530
+ const k = positiveInt(args.k, "k", op);
1531
+ const minScore = args.minScore;
1532
+ if (minScore !== void 0 && (typeof minScore !== "number" || !Number.isFinite(minScore))) {
1533
+ throw new CyphraValidationError(`${op}: minScore must be a finite number.`);
1534
+ }
1535
+ if (args.exact !== void 0 && typeof args.exact !== "boolean") {
1536
+ throw new CyphraValidationError(`${op}: exact must be a boolean.`);
1537
+ }
1538
+ const ctx = ctxFactory();
1539
+ const where = compileWhere(ctx, model, "n", args.where);
1540
+ const candidates = args.candidates === void 0 ? where ? Math.max(10 * k, 100) : k : positiveInt(args.candidates, "candidates", op);
1541
+ if (candidates < k) {
1542
+ throw new CyphraValidationError(`${op}: candidates must be at least k (${k}).`);
1543
+ }
1544
+ const maxCandidates = args.maxCandidates === void 0 ? Number.POSITIVE_INFINITY : positiveInt(args.maxCandidates, "maxCandidates", op);
1545
+ if (maxCandidates < candidates) {
1546
+ throw new CyphraValidationError(`${op}: maxCandidates must be at least candidates.`);
1547
+ }
1548
+ const prop = q(field.name);
1549
+ const vec = ctx.param(vector);
1550
+ const limit = ctx.param(intParam(k));
1551
+ const scoreOk = minScore === void 0 ? null : `score >= ${ctx.param(minScore)}`;
1552
+ const { expr, shape } = compileProjection(ctx, model, "n", args);
1553
+ const decode = (rows) => rows.map((r) => ({ ...decodeRow(shape, r.row), $score: toScore(r.score) })).sort((a, b) => b.$score - a.$score).slice(0, k);
1554
+ if (args.exact === true) {
1555
+ const fn = index.similarity === "euclidean" ? "vector.similarity.euclidean" : "vector.similarity.cosine";
1556
+ const filters = [
1557
+ `n.${prop} IS NOT NULL`,
1558
+ `size(n.${prop}) = ${ctx.param(intParam(vector.length))}`
1559
+ ];
1560
+ if (where) filters.push(`(${where})`);
1561
+ let text2 = `MATCH (n:${q(model.label)}) WHERE ${filters.join(" AND ")}`;
1562
+ text2 += ` WITH n, ${fn}(n.${prop}, ${vec}) AS score`;
1563
+ if (scoreOk) text2 += ` WHERE ${scoreOk}`;
1564
+ text2 += ` WITH n, score ORDER BY score DESC LIMIT ${limit}`;
1565
+ text2 += ` RETURN ${expr} AS row, score ORDER BY score DESC`;
1566
+ const rows = await exec(text2, ctx.params);
1567
+ return decode(rows);
1568
+ }
1569
+ const name = ctx.param(index.name);
1570
+ const call = (count2) => `CALL db.index.vector.queryNodes(${name}, ${count2}, ${vec}) YIELD node, score`;
1571
+ if (!where) {
1572
+ let text2 = `${call(ctx.param(intParam(candidates)))} WITH node AS n, score`;
1573
+ if (scoreOk) text2 += ` WHERE ${scoreOk}`;
1574
+ text2 += ` WITH n, score ORDER BY score DESC LIMIT ${limit}`;
1575
+ text2 += ` RETURN ${expr} AS row, score ORDER BY score DESC`;
1576
+ const rows = await exec(text2, ctx.params);
1577
+ return decode(rows);
1578
+ }
1579
+ const count = "$cyphraCandidates";
1580
+ const filter = [scoreOk, where].filter(Boolean).join(" AND ");
1581
+ const text = `${call(count)} WITH collect({n: node, s: score}) AS hits CALL { WITH hits UNWIND hits AS h WITH h.n AS n, h.s AS score WHERE ${filter} WITH n, score ORDER BY score DESC LIMIT ${limit} RETURN collect({row: ${expr}, score: score}) AS rows } RETURN size(hits) AS fetched, hits[-1].s AS lowest, rows`;
1582
+ let asked = Math.min(candidates, maxCandidates);
1583
+ for (; ; ) {
1584
+ const [res] = await exec(text, { ...ctx.params, cyphraCandidates: intParam(asked) });
1585
+ const rows = res?.rows ?? [];
1586
+ const fetched = decodeCount(res?.fetched);
1587
+ const lowest = res?.lowest;
1588
+ const exhausted = fetched < asked || asked >= maxCandidates || minScore !== void 0 && lowest !== null && lowest !== void 0 && toScore(lowest) < minScore;
1589
+ if (rows.length >= k || exhausted) return decode(rows);
1590
+ asked = Math.min(asked * CANDIDATE_GROWTH, maxCandidates);
1591
+ }
1592
+ }
1593
+
1594
+ // src/orm/fulltext.ts
1595
+ var ARG_KEYS4 = /* @__PURE__ */ new Set([
1596
+ "index",
1597
+ "query",
1598
+ "mode",
1599
+ "where",
1600
+ "minScore",
1601
+ "skip",
1602
+ "take",
1603
+ "select",
1604
+ "include"
1605
+ ]);
1606
+ var MODES = ["lucene", "terms", "phrase"];
1607
+ var LUCENE_SPECIAL = /[+\-&|!(){}[\]^"~*?:\\/]/g;
1608
+ var LUCENE_OPERATORS = /\b(AND|OR|NOT)\b/g;
1609
+ function escapeLucene(text) {
1610
+ return text.replace(LUCENE_SPECIAL, "\\$&").replace(LUCENE_OPERATORS, "\\$1");
1611
+ }
1612
+ function luceneQuery(query, mode) {
1613
+ if (mode === "terms") return escapeLucene(query);
1614
+ if (mode === "phrase") return `"${escapeLucene(query)}"`;
1615
+ return query;
1616
+ }
1617
+ async function search(exec, ctxFactory, model, args) {
1618
+ const op = `${model.name}.search`;
1619
+ for (const key of Object.keys(args)) {
1620
+ if (!ARG_KEYS4.has(key)) throw new CyphraValidationError(`${op}: unknown argument "${key}".`);
1621
+ }
1622
+ const indexes = model.fulltextIndexes ?? [];
1623
+ const names = indexes.map((i) => i.name);
1624
+ if (typeof args.index !== "string") {
1625
+ throw new CyphraValidationError(
1626
+ `${op}: index is required (${names.join(", ") || `${model.name} has no @@fulltext index`}).`
1627
+ );
1628
+ }
1629
+ if (!names.includes(args.index)) {
1630
+ throw new CyphraValidationError(
1631
+ `${op}: ${JSON.stringify(args.index)} is not a full-text index of ${model.name} (${names.join(", ") || "declare one with @@fulltext"}).`
1632
+ );
1633
+ }
1634
+ if (typeof args.query !== "string") {
1635
+ throw new CyphraValidationError(`${op}: query must be a string.`);
1636
+ }
1637
+ const mode = args.mode ?? "lucene";
1638
+ if (!MODES.includes(mode)) {
1639
+ throw new CyphraValidationError(`${op}: mode must be ${MODES.join(", ")}.`);
1640
+ }
1641
+ const minScore = args.minScore;
1642
+ if (minScore !== void 0 && (typeof minScore !== "number" || !Number.isFinite(minScore))) {
1643
+ throw new CyphraValidationError(`${op}: minScore must be a finite number.`);
1644
+ }
1645
+ const skip = args.skip === void 0 ? void 0 : nonNegativeInt(args.skip, `${op}: skip`);
1646
+ const take = args.take === void 0 ? void 0 : nonNegativeInt(args.take, `${op}: take`);
1647
+ const ctx = ctxFactory();
1648
+ const where = compileWhere(ctx, model, "n", args.where);
1649
+ const { expr, shape } = compileProjection(ctx, model, "n", args);
1650
+ if (args.query.trim() === "" || take === 0) return [];
1651
+ const name = ctx.param(args.index);
1652
+ const query = ctx.param(luceneQuery(args.query, mode));
1653
+ const filters = [
1654
+ ...minScore === void 0 ? [] : [`score >= ${ctx.param(minScore)}`],
1655
+ ...where ? [`(${where})`] : []
1656
+ ];
1657
+ const options = filters.length === 0 && take !== void 0 ? `, {limit: ${ctx.param(intParam((skip ?? 0) + take))}}` : "";
1658
+ let text = `CALL db.index.fulltext.queryNodes(${name}, ${query}${options}) YIELD node, score`;
1659
+ text += " WITH node AS n, score";
1660
+ if (filters.length) text += ` WHERE ${filters.join(" AND ")}`;
1661
+ text += " WITH n, score ORDER BY score DESC";
1662
+ if (skip !== void 0) text += ` SKIP ${ctx.param(intParam(skip))}`;
1663
+ if (take !== void 0) text += ` LIMIT ${ctx.param(intParam(take))}`;
1664
+ text += ` RETURN ${expr} AS row, score ORDER BY score DESC`;
1665
+ const rows = await exec(text, ctx.params);
1666
+ return rows.map((r) => ({
1667
+ ...decodeRow(shape, r.row),
1668
+ $score: typeof r.score === "number" ? r.score : Number(r.score)
1669
+ }));
1670
+ }
1671
+
1672
+ // src/orm/engine.ts
1673
+ function isPlainObject5(v) {
1674
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1675
+ }
1047
1676
  function toCount(v) {
1048
1677
  return isInt3(v) ? integerToNumber(v) : Number(v ?? 0);
1049
1678
  }
@@ -1065,14 +1694,16 @@ function asArray(v) {
1065
1694
  return Array.isArray(v) ? v : [v];
1066
1695
  }
1067
1696
  var ModelEngine = class _ModelEngine {
1068
- constructor(schema, model, runner) {
1697
+ constructor(schema, model, runner, options = {}) {
1069
1698
  this.schema = schema;
1070
1699
  this.model = model;
1071
1700
  this.runner = runner;
1701
+ this.options = options;
1072
1702
  }
1073
1703
  schema;
1074
1704
  model;
1075
1705
  runner;
1706
+ options;
1076
1707
  ctx() {
1077
1708
  return new QueryContext(this.schema);
1078
1709
  }
@@ -1091,7 +1722,7 @@ var ModelEngine = class _ModelEngine {
1091
1722
  if (where) text += ` WHERE ${where}`;
1092
1723
  if (paging) text += ` WITH n${paging}`;
1093
1724
  text += ` RETURN ${expr} AS row`;
1094
- const order = compileOrderBy(this.model, "n", args.orderBy);
1725
+ const order = compileOrderBy(ctx, this.model, "n", args.orderBy);
1095
1726
  if (order) text += ` ORDER BY ${order}`;
1096
1727
  const rows = await exec(text, ctx.params);
1097
1728
  return rows.map((r) => decodeRow(shape, r.row));
@@ -1107,9 +1738,9 @@ var ModelEngine = class _ModelEngine {
1107
1738
  return decodeRow(shape, rows[0].row);
1108
1739
  }
1109
1740
  assertUnique(where, op) {
1110
- const ok = isPlainObject3(where) && this.model.uniqueFields.some((k) => {
1741
+ const ok = isPlainObject5(where) && this.model.uniqueFields.some((k) => {
1111
1742
  const v = where[k];
1112
- return v !== void 0 && v !== null && !isPlainObject3(v);
1743
+ return v !== void 0 && v !== null && !isPlainObject5(v);
1113
1744
  });
1114
1745
  if (!ok) {
1115
1746
  throw new CyphraValidationError(
@@ -1159,7 +1790,7 @@ var ModelEngine = class _ModelEngine {
1159
1790
  /** One statement; see {@link compileAggregate}. */
1160
1791
  aggregate(args = {}) {
1161
1792
  return this.runner.read(async (exec) => {
1162
- if (!isPlainObject3(args))
1793
+ if (!isPlainObject5(args))
1163
1794
  throw new CyphraValidationError("aggregate args must be an object.");
1164
1795
  const c = compileAggregate(this.ctx(), this.model, args);
1165
1796
  return c.decode(await exec(c.text, c.params));
@@ -1168,11 +1799,55 @@ var ModelEngine = class _ModelEngine {
1168
1799
  /** One statement; see {@link compileGroupBy}. */
1169
1800
  groupBy(args) {
1170
1801
  return this.runner.read(async (exec) => {
1171
- if (!isPlainObject3(args)) throw new CyphraValidationError("groupBy args must be an object.");
1802
+ if (!isPlainObject5(args)) throw new CyphraValidationError("groupBy args must be an object.");
1172
1803
  const c = compileGroupBy(this.ctx(), this.model, args);
1173
1804
  return c.decode(await exec(c.text, c.params));
1174
1805
  });
1175
1806
  }
1807
+ /** One statement; see {@link compileTraverse}. */
1808
+ traverse(args) {
1809
+ return this.runner.read(async (exec) => {
1810
+ if (!isPlainObject5(args)) throw new CyphraValidationError("traverse args must be an object.");
1811
+ const max = this.options.maxTraversalDepth ?? DEFAULT_MAX_TRAVERSAL_DEPTH;
1812
+ const c = compileTraverse(this.ctx(), this.model, args, max);
1813
+ return c.decode(await exec(c.text, c.params));
1814
+ });
1815
+ }
1816
+ /** One statement; see {@link compileShortestPath}. */
1817
+ async shortestPath(args) {
1818
+ return (await this.shortest(args, false))[0] ?? null;
1819
+ }
1820
+ /** One statement; see {@link compileShortestPath}. */
1821
+ allShortestPaths(args) {
1822
+ return this.shortest(args, true);
1823
+ }
1824
+ shortest(args, all) {
1825
+ return this.runner.read(async (exec) => {
1826
+ if (!isPlainObject5(args)) {
1827
+ throw new CyphraValidationError(
1828
+ `${all ? "allShortestPaths" : "shortestPath"} args must be an object.`
1829
+ );
1830
+ }
1831
+ const max = this.options.maxTraversalDepth ?? DEFAULT_MAX_TRAVERSAL_DEPTH;
1832
+ const c = compileShortestPath(this.ctx(), this.model, args, max, all);
1833
+ return c.decode(await exec(c.text, c.params));
1834
+ });
1835
+ }
1836
+ /** Nearest neighbours on a `@vectorIndex` field; see {@link findSimilar}. */
1837
+ findSimilar(args) {
1838
+ return this.runner.read(async (exec) => {
1839
+ if (!isPlainObject5(args))
1840
+ throw new CyphraValidationError("findSimilar args must be an object.");
1841
+ return findSimilar(exec, () => this.ctx(), this.model, args);
1842
+ });
1843
+ }
1844
+ /** Full-text search through a `@@fulltext` index; see {@link search}. */
1845
+ search(args) {
1846
+ return this.runner.read(async (exec) => {
1847
+ if (!isPlainObject5(args)) throw new CyphraValidationError("search args must be an object.");
1848
+ return search(exec, () => this.ctx(), this.model, args);
1849
+ });
1850
+ }
1176
1851
  // -------------------------------------------------------------------------
1177
1852
  // Write helpers
1178
1853
  // -------------------------------------------------------------------------
@@ -1180,7 +1855,7 @@ var ModelEngine = class _ModelEngine {
1180
1855
  return new QueryContext(this.schema).node(name);
1181
1856
  }
1182
1857
  engineFor(model) {
1183
- return model === this.model ? this : new _ModelEngine(this.schema, model, this.runner);
1858
+ return model === this.model ? this : new _ModelEngine(this.schema, model, this.runner, this.options);
1184
1859
  }
1185
1860
  /** Encode scalar data for CREATE, applying defaults and checking required fields. */
1186
1861
  static createProps(owner, fields, data) {
@@ -1207,7 +1882,7 @@ var ModelEngine = class _ModelEngine {
1207
1882
  return props;
1208
1883
  }
1209
1884
  splitData(data, op) {
1210
- if (!isPlainObject3(data))
1885
+ if (!isPlainObject5(data))
1211
1886
  throw new CyphraValidationError(`${this.model.name}.${op}: data must be an object.`);
1212
1887
  const scalars = {};
1213
1888
  const relations = {};
@@ -1231,7 +1906,7 @@ var ModelEngine = class _ModelEngine {
1231
1906
  `${this.model.name}.${rel.name}: $edge given but no relationship model types this edge.`
1232
1907
  );
1233
1908
  }
1234
- if (!isPlainObject3(input)) throw new CyphraValidationError("$edge must be an object.");
1909
+ if (!isPlainObject5(input)) throw new CyphraValidationError("$edge must be an object.");
1235
1910
  for (const k of Object.keys(input)) {
1236
1911
  if (!edgeModel.properties.some((p) => p.name === k)) {
1237
1912
  throw new CyphraValidationError(`Unknown edge property "${edgeModel.name}.${k}".`);
@@ -1250,7 +1925,7 @@ var ModelEngine = class _ModelEngine {
1250
1925
  }
1251
1926
  /** Only the `$edge` properties the caller set (no defaults), for updating an existing edge. */
1252
1927
  explicitEdgeProps(rel, input) {
1253
- if (!rel.edge || !isPlainObject3(input)) return {};
1928
+ if (!rel.edge || !isPlainObject5(input)) return {};
1254
1929
  const edgeModel = this.schema.relationships.find((r) => r.name === rel.edge);
1255
1930
  const props = {};
1256
1931
  for (const f of edgeModel.properties) {
@@ -1287,7 +1962,7 @@ var ModelEngine = class _ModelEngine {
1287
1962
  * defaults, e.g. `@default(now())`, are kept).
1288
1963
  */
1289
1964
  async connect(exec, id, rel, item) {
1290
- if (!isPlainObject3(item))
1965
+ if (!isPlainObject5(item))
1291
1966
  throw new CyphraValidationError(`${rel.name}.connect expects unique where objects.`);
1292
1967
  const { $edge, ...where } = item;
1293
1968
  const target = this.node(rel.target);
@@ -1320,7 +1995,7 @@ var ModelEngine = class _ModelEngine {
1320
1995
  }
1321
1996
  }
1322
1997
  async createRelated(exec, id, rel, item) {
1323
- if (!isPlainObject3(item))
1998
+ if (!isPlainObject5(item))
1324
1999
  throw new CyphraValidationError(`${rel.name}.create expects objects.`);
1325
2000
  const { $edge, ...data } = item;
1326
2001
  const props = this.edgeProps(rel, $edge);
@@ -1342,7 +2017,7 @@ var ModelEngine = class _ModelEngine {
1342
2017
  return toCount(rows[0]?.c);
1343
2018
  }
1344
2019
  async writeRelation(exec, id, rel, spec, mode) {
1345
- if (!isPlainObject3(spec)) {
2020
+ if (!isPlainObject5(spec)) {
1346
2021
  throw new CyphraValidationError(
1347
2022
  `${this.model.name}.${rel.name}: relation writes take { create, connect, \u2026 }.`
1348
2023
  );
@@ -1375,7 +2050,7 @@ var ModelEngine = class _ModelEngine {
1375
2050
  if (rel.many) {
1376
2051
  if (disconnect !== void 0) {
1377
2052
  for (const item of asArray(disconnect)) {
1378
- if (!isPlainObject3(item))
2053
+ if (!isPlainObject5(item))
1379
2054
  throw new CyphraValidationError(`${rel.name}.disconnect expects unique where objects.`);
1380
2055
  this.engineFor(this.node(rel.target)).assertUnique(
1381
2056
  item,
@@ -1408,7 +2083,7 @@ var ModelEngine = class _ModelEngine {
1408
2083
  for (const [k, v] of Object.entries(scalars)) {
1409
2084
  const f = scalarField(this.model, k);
1410
2085
  const ref = `n.${q(k)}`;
1411
- if (isPlainObject3(v) && !f.list) {
2086
+ if (isPlainObject5(v) && !f.list) {
1412
2087
  if (f.type !== "Int" && f.type !== "Float") {
1413
2088
  throw new CyphraValidationError(
1414
2089
  `${this.model.name}.${k}: object updates are only for numbers.`
@@ -1515,7 +2190,7 @@ var ModelEngine = class _ModelEngine {
1515
2190
  const where = args.where;
1516
2191
  const key = this.model.uniqueFields.find((k) => {
1517
2192
  const v = where[k];
1518
- return v !== void 0 && v !== null && !isPlainObject3(v);
2193
+ return v !== void 0 && v !== null && !isPlainObject5(v);
1519
2194
  });
1520
2195
  const keyField = scalarField(this.model, key);
1521
2196
  const create = this.splitData(args.create, "upsert create");
@@ -1609,12 +2284,12 @@ function txExecutor(tx, debug) {
1609
2284
  return res.records.map((r) => r.toObject());
1610
2285
  };
1611
2286
  }
1612
- function buildDelegates(schema, runner) {
2287
+ function buildDelegates(schema, runner, options) {
1613
2288
  const out = {};
1614
2289
  for (const node of schema.nodes) {
1615
2290
  const key = delegateKey(node.name);
1616
2291
  if (key.startsWith("$")) throw new Error(`Model name "${node.name}" is reserved.`);
1617
- out[key] = new ModelEngine(schema, node, runner);
2292
+ out[key] = new ModelEngine(schema, node, runner, options);
1618
2293
  }
1619
2294
  return out;
1620
2295
  }
@@ -1626,6 +2301,11 @@ function rawFor(runner) {
1626
2301
  };
1627
2302
  }
1628
2303
  function createOrm(schema, options) {
2304
+ const { maxTraversalDepth } = options;
2305
+ if (maxTraversalDepth !== void 0 && (!Number.isInteger(maxTraversalDepth) || maxTraversalDepth < 1)) {
2306
+ throw new CyphraValidationError("maxTraversalDepth must be a positive integer.");
2307
+ }
2308
+ const engineOptions = { maxTraversalDepth };
1629
2309
  const owns = !("client" in options);
1630
2310
  const client = "client" in options ? options.client : new CyphraClient(options);
1631
2311
  const debug = options.debug ?? false;
@@ -1636,11 +2316,11 @@ function createOrm(schema, options) {
1636
2316
  const transaction = (fn) => client.withWriteTransaction((tx) => {
1637
2317
  const exec = txExecutor(tx, debug);
1638
2318
  const inTx = { read: (f) => f(exec), write: (f) => f(exec) };
1639
- const txClient = { ...buildDelegates(schema, inTx), $cypher: rawFor(inTx) };
2319
+ const txClient = { ...buildDelegates(schema, inTx, engineOptions), $cypher: rawFor(inTx) };
1640
2320
  return fn(txClient);
1641
2321
  });
1642
2322
  return {
1643
- ...buildDelegates(schema, runner),
2323
+ ...buildDelegates(schema, runner, engineOptions),
1644
2324
  $cypher: rawFor(runner),
1645
2325
  $transaction: transaction,
1646
2326
  $client: client,
@@ -1657,6 +2337,7 @@ export {
1657
2337
  NotFoundError,
1658
2338
  createCuid,
1659
2339
  createOrm,
2340
+ escapeLucene,
1660
2341
  toNative,
1661
2342
  toPlainRecord,
1662
2343
  toPlainRecords