@cyphra/graphql 0.6.0 → 0.9.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
@@ -17,6 +17,7 @@ __export(v7_exports, {
17
17
  readTypeDefs: () => readTypeDefs
18
18
  });
19
19
  import {
20
+ GraphQLError as GraphQLError6,
20
21
  isObjectType
21
22
  } from "graphql";
22
23
  import { resolveSchema as resolveSchema2 } from "@cyphra/schema";
@@ -30,8 +31,8 @@ import {
30
31
  } from "graphql";
31
32
 
32
33
  // src/import/mappings.ts
33
- import { Kind } from "graphql";
34
- var NOT_YET = "is not supported by Cyphra yet";
34
+ import { Kind, valueFromASTUntyped } from "graphql";
35
+ import { isValidTemporalText } from "@cyphra/schema";
35
36
  var SCALARS = {
36
37
  ID: { type: "String" },
37
38
  String: { type: "String" },
@@ -40,17 +41,21 @@ var SCALARS = {
40
41
  Boolean: { type: "Boolean" },
41
42
  DateTime: { type: "DateTime" },
42
43
  Date: { type: "Date" },
43
- BigInt: { unsupported: `BigInt ${NOT_YET}` },
44
- Time: { unsupported: `Time ${NOT_YET}` },
45
- LocalTime: { unsupported: `LocalTime ${NOT_YET}` },
46
- LocalDateTime: { unsupported: `LocalDateTime ${NOT_YET}` },
47
- Duration: { unsupported: `Duration ${NOT_YET}` },
48
- Point: { unsupported: `Point ${NOT_YET}` },
49
- CartesianPoint: { unsupported: `CartesianPoint ${NOT_YET}` }
44
+ BigInt: { type: "BigInt" },
45
+ // Same Neo4j types: `Time` keeps its offset, `Point` is WGS-84, `CartesianPoint` Cartesian.
46
+ Time: { type: "Time" },
47
+ LocalTime: { type: "LocalTime" },
48
+ LocalDateTime: { type: "LocalDateTime" },
49
+ Duration: { type: "Duration" },
50
+ Point: { type: "Point" },
51
+ CartesianPoint: { type: "CartesianPoint" }
50
52
  };
51
- var ENUM_FIELD = {
53
+ function enumField(name) {
54
+ return { type: "Enum", enum: name };
55
+ }
56
+ var ENUM_AS_STRING = {
52
57
  type: "String",
53
- note: "enums are not supported by Cyphra yet: mapped to String, allowed values are not enforced"
58
+ note: "this enum name cannot be a Cyphra enum (it clashes with a type or node name): mapped to String, allowed values are not enforced"
54
59
  };
55
60
  var CUSTOM_SCALAR_FIELD = {
56
61
  unsupported: "custom scalars are not supported by Cyphra"
@@ -60,6 +65,14 @@ var UNIQUE = { name: "unique", args: [] };
60
65
  function defaultFn(fn) {
61
66
  return { name: "default", args: [{ key: "fn", value: { kind: "identifier", value: fn } }] };
62
67
  }
68
+ function defaultEnum(value) {
69
+ return { name: "default", args: [{ key: "value", value: { kind: "identifier", value } }] };
70
+ }
71
+ function defaultBigInt(digits) {
72
+ const value = Number(digits);
73
+ const v = Number.isSafeInteger(value) ? { kind: "number", value } : { kind: "number", value, raw: digits };
74
+ return { name: "default", args: [{ key: "value", value: v }] };
75
+ }
63
76
  function defaultLiteral(value) {
64
77
  const v = typeof value === "string" ? { kind: "string", value } : typeof value === "number" ? { kind: "number", value } : { kind: "boolean", value };
65
78
  return { name: "default", args: [{ key: "value", value: v }] };
@@ -78,13 +91,21 @@ function enumListArg(d, name) {
78
91
  return items.flatMap((i) => i.kind === Kind.ENUM || i.kind === Kind.STRING ? [i.value] : []);
79
92
  }
80
93
  var API_ONLY = "API setting of @neo4j/graphql, no effect on the data model";
81
- var AUTH = "authorization rules are not part of a Cyphra schema: enforce them in your resolvers or services";
94
+ var AUTH = "authorization rules are not part of a Cyphra schema: compat.v7 still applies them; enforce them yourself around the typed client";
82
95
  function issue(severity, feature, message) {
83
96
  return { severity, feature, message };
84
97
  }
85
98
  function defaultFromValue(v, ctx) {
86
99
  if (ctx.list) return { error: "Cyphra has no defaults for list fields" };
87
100
  switch (ctx.type) {
101
+ case "Enum":
102
+ if (v.kind === Kind.ENUM) return defaultEnum(v.value);
103
+ break;
104
+ case "BigInt":
105
+ if ((v.kind === Kind.INT || v.kind === Kind.STRING) && /^-?[0-9]+$/.test(v.value)) {
106
+ return defaultBigInt(v.value);
107
+ }
108
+ break;
88
109
  case "String":
89
110
  if (v.kind === Kind.STRING) return v.value;
90
111
  if (ctx.isEnum && v.kind === Kind.ENUM) return v.value;
@@ -101,6 +122,11 @@ function defaultFromValue(v, ctx) {
101
122
  case "DateTime":
102
123
  case "Date":
103
124
  return { error: `Cyphra only supports @default(now()) on ${ctx.type} fields` };
125
+ case "Time":
126
+ case "LocalTime":
127
+ case "LocalDateTime":
128
+ if (v.kind === Kind.STRING && isValidTemporalText(ctx.type, v.value)) return v.value;
129
+ break;
104
130
  }
105
131
  return { error: `the default does not match type ${ctx.graphqlType}` };
106
132
  }
@@ -159,9 +185,11 @@ var FIELD_DIRECTIVES = {
159
185
  kind: "scalar",
160
186
  apply: (d, ctx) => {
161
187
  const ops = enumListArg(d, "operations") ?? ["CREATE", "UPDATE"];
162
- if (ctx.type !== "DateTime" || ctx.list) {
188
+ if (ctx.type !== "DateTime" && ctx.type !== "Time" || ctx.list) {
163
189
  return {
164
- issues: [issue("unsupported", "@timestamp", "@timestamp is only converted on DateTime")]
190
+ issues: [
191
+ issue("unsupported", "@timestamp", "@timestamp is only converted on DateTime and Time")
192
+ ]
165
193
  };
166
194
  }
167
195
  if (!ops.includes("CREATE")) {
@@ -191,10 +219,10 @@ var FIELD_DIRECTIVES = {
191
219
  apply: (d, ctx) => {
192
220
  const v = arg(d, "value");
193
221
  const value = v ? defaultFromValue(v, ctx) : { error: "missing value" };
194
- if (typeof value === "object") {
222
+ if (typeof value === "object" && "error" in value) {
195
223
  return { issues: [issue("unsupported", "@default", `${value.error}; not converted`)] };
196
224
  }
197
- return { decorators: [defaultLiteral(value)] };
225
+ return { decorators: [typeof value === "object" ? value : defaultLiteral(value)] };
198
226
  }
199
227
  },
200
228
  unique: {
@@ -248,7 +276,7 @@ var FIELD_DIRECTIVES = {
248
276
  },
249
277
  cypher: {
250
278
  kind: "drop",
251
- message: "@cypher fields are computed by a Cypher query: not converted, write it as a query"
279
+ message: "@cypher fields are computed by a Cypher query: not converted (compat.v7 still serves it); with the typed client, write it as a query"
252
280
  },
253
281
  customResolver: {
254
282
  kind: "drop",
@@ -316,11 +344,47 @@ var TYPE_DIRECTIVES = {
316
344
  }
317
345
  return rename ? { rename, issues } : { issues };
318
346
  },
319
- fulltext: reportType(
347
+ fulltext: (d) => {
348
+ const raw = arg(d, "indexes");
349
+ const indexes = raw ? valueFromASTUntyped(raw) : void 0;
350
+ const list2 = Array.isArray(indexes) ? indexes : indexes === void 0 ? [] : [indexes];
351
+ const fulltext = [];
352
+ const issues = [];
353
+ for (const ix of list2) {
354
+ const { indexName, queryName, fields } = ix ?? {};
355
+ if (typeof indexName !== "string" || !Array.isArray(fields) || fields.length === 0 || !fields.every((f) => typeof f === "string")) {
356
+ issues.push(
357
+ issue("unsupported", "@fulltext", "an index needs indexName and fields: not converted")
358
+ );
359
+ continue;
360
+ }
361
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(indexName)) {
362
+ issues.push(
363
+ issue(
364
+ "unsupported",
365
+ "@fulltext",
366
+ `index name "${indexName}" is not letters, digits and underscores: not converted`
367
+ )
368
+ );
369
+ continue;
370
+ }
371
+ fulltext.push({ name: indexName, fields });
372
+ if (typeof queryName === "string") {
373
+ issues.push(
374
+ issue(
375
+ "ignored",
376
+ "@fulltext(queryName)",
377
+ `query field "${queryName}" is part of the GraphQL API (compat.v7 still serves it)`
378
+ )
379
+ );
380
+ }
381
+ }
382
+ return { fulltext, issues };
383
+ },
384
+ vector: reportType(
320
385
  "unsupported",
321
- "fulltext indexes are not supported: create them in a migration"
386
+ "vector indexes are not converted: the type definitions carry neither the dimensions nor the similarity; declare the embedding as a Vector(N) field with @vectorIndex(name: ...)"
322
387
  ),
323
- vector: reportType("unsupported", "vector indexes are not supported: create them in a migration"),
324
388
  authentication: reportType("unsupported", AUTH),
325
389
  authorization: reportType("unsupported", AUTH),
326
390
  subscriptionsAuthorization: reportType("unsupported", AUTH),
@@ -426,6 +490,11 @@ function collectTypes(sources) {
426
490
  fields: [
427
491
  ...(def.kind === Kind2.OBJECT_TYPE_DEFINITION || def.kind === Kind2.INTERFACE_TYPE_DEFINITION ? def.fields : void 0) ?? []
428
492
  ],
493
+ values: [
494
+ ...((def.kind === Kind2.ENUM_TYPE_DEFINITION ? def.values : void 0) ?? []).map(
495
+ (v) => v.name.value
496
+ )
497
+ ],
429
498
  source: src.name
430
499
  });
431
500
  }
@@ -440,6 +509,9 @@ function collectTypes(sources) {
440
509
  if ((def.kind === Kind2.OBJECT_TYPE_EXTENSION || def.kind === Kind2.INTERFACE_TYPE_EXTENSION) && def.fields) {
441
510
  base.fields.push(...def.fields);
442
511
  }
512
+ if (def.kind === Kind2.ENUM_TYPE_EXTENSION && def.values) {
513
+ base.values.push(...def.values.map((v) => v.name.value));
514
+ }
443
515
  }
444
516
  return types;
445
517
  }
@@ -482,15 +554,6 @@ function convertGraphQLTypeDefs(input) {
482
554
  }
483
555
  switch (t.kind) {
484
556
  case "enum":
485
- if ("unsupported" in ENUM_FIELD) {
486
- report(t.name, {
487
- severity: "unsupported",
488
- feature: "enum",
489
- message: ENUM_FIELD.unsupported
490
- });
491
- } else if (ENUM_FIELD.note) {
492
- report(t.name, { severity: "changed", feature: "enum", message: ENUM_FIELD.note });
493
- }
494
557
  break;
495
558
  case "interface":
496
559
  report(t.name, {
@@ -525,7 +588,7 @@ function convertGraphQLTypeDefs(input) {
525
588
  report(t.name, {
526
589
  severity: "unsupported",
527
590
  feature: t.name,
528
- message: `custom ${t.name} fields (@cypher, resolvers) are not converted: write them as Cyphra queries`
591
+ message: `custom ${t.name} fields (@cypher, resolvers) are not converted (compat.v7 still serves @cypher fields); with the typed client, write them as queries`
529
592
  });
530
593
  } else if (directive(t.directives, "jwt")) {
531
594
  report(t.name, {
@@ -544,6 +607,7 @@ function convertGraphQLTypeDefs(input) {
544
607
  }
545
608
  }
546
609
  const usedNames = new Set(types.keys());
610
+ const fulltextOf = /* @__PURE__ */ new Map();
547
611
  for (const t of nodeTypes) {
548
612
  let name = t.name;
549
613
  for (const d of t.directives) {
@@ -567,6 +631,9 @@ function convertGraphQLTypeDefs(input) {
567
631
  }
568
632
  const effect = rule(d, t.name);
569
633
  for (const i of effect.issues ?? []) report(t.name, i);
634
+ if (effect.fulltext?.length) {
635
+ fulltextOf.set(t.name, [...fulltextOf.get(t.name) ?? [], ...effect.fulltext]);
636
+ }
570
637
  if (effect.rename && effect.rename !== name) {
571
638
  if (usedNames.has(effect.rename) || [...nodeName.values()].includes(effect.rename)) {
572
639
  report(t.name, {
@@ -581,11 +648,19 @@ function convertGraphQLTypeDefs(input) {
581
648
  }
582
649
  nodeName.set(t.name, name);
583
650
  }
651
+ const enumMap = enumMappings(types, new Set(nodeName.values()), report);
652
+ const usedEnums = /* @__PURE__ */ new Set();
653
+ const mapScalar = (named) => {
654
+ const m = scalarMapping(named, types, enumMap);
655
+ if ("enum" in m && m.enum) usedEnums.add(m.enum);
656
+ return m;
657
+ };
584
658
  const usages = [];
585
659
  const declarations = [];
586
660
  for (const t of nodeTypes) {
587
661
  const declName = nodeName.get(t.name);
588
662
  const fields = [];
663
+ const scalarOf = /* @__PURE__ */ new Map();
589
664
  let hasId = false;
590
665
  for (const f of t.fields) {
591
666
  const at = `${t.name}.${f.name.value}`;
@@ -606,18 +681,30 @@ function convertGraphQLTypeDefs(input) {
606
681
  if (rel.usage) usages.push(rel.usage);
607
682
  continue;
608
683
  }
609
- const scalar = convertScalar(f, u, at, "node", hasId, types, report);
684
+ const scalar = convertScalar(f, u, at, "node", hasId, mapScalar, report);
610
685
  if (!scalar) {
611
686
  note(declName, skippedLine(f, "type not supported"));
612
687
  continue;
613
688
  }
614
689
  if (scalar.takesId) hasId = true;
615
690
  fields.push(scalar.field);
691
+ scalarOf.set(f.name.value, scalar.field);
616
692
  }
693
+ const kept = dedupeNames(fields, t.name, report);
694
+ const attributes = fulltextAttributes(
695
+ t.name,
696
+ fulltextOf.get(t.name) ?? [],
697
+ (name) => {
698
+ const f = scalarOf.get(name);
699
+ return f && kept.includes(f) ? f : void 0;
700
+ },
701
+ report
702
+ );
617
703
  declarations.push({
618
704
  kind: "Node",
619
705
  name: declName,
620
- fields: dedupeNames(fields, t.name, report)
706
+ fields: kept,
707
+ ...attributes.length ? { attributes } : {}
621
708
  });
622
709
  }
623
710
  const relationships = [];
@@ -668,7 +755,7 @@ function convertGraphQLTypeDefs(input) {
668
755
  propNotes.push(skippedLine(f, "not a scalar"));
669
756
  continue;
670
757
  }
671
- const scalar = convertScalar(f, u, at, "relationship", false, types, report);
758
+ const scalar = convertScalar(f, u, at, "relationship", false, mapScalar, report);
672
759
  if (!scalar) {
673
760
  propNotes.push(skippedLine(f, "type not supported"));
674
761
  continue;
@@ -701,12 +788,56 @@ function convertGraphQLTypeDefs(input) {
701
788
  if (propNotes.length) notes.set(name, [...propNotes]);
702
789
  }
703
790
  }
791
+ const enums = [...types.values()].filter((t) => usedEnums.has(t.name)).map((t) => ({ kind: "Enum", name: t.name, values: [...t.values] }));
704
792
  return {
705
- document: { kind: "Document", declarations: [...declarations, ...relationships] },
793
+ document: {
794
+ kind: "Document",
795
+ declarations: [...enums, ...declarations, ...relationships]
796
+ },
706
797
  issues,
707
798
  notes
708
799
  };
709
800
  }
801
+ function fulltextAttributes(typeName, drafts, fieldOf, report) {
802
+ const out = [];
803
+ const names = /* @__PURE__ */ new Set();
804
+ for (const ix of drafts) {
805
+ if (names.has(ix.name)) {
806
+ report(typeName, {
807
+ severity: "unsupported",
808
+ feature: "@fulltext",
809
+ message: `index "${ix.name}" is declared twice: kept the first`
810
+ });
811
+ continue;
812
+ }
813
+ const fields = [];
814
+ let problem;
815
+ for (const name of ix.fields) {
816
+ const f = fieldOf(name);
817
+ if (!f) problem = `field "${name}" was not converted`;
818
+ else if (f.type.name !== "String") problem = `field "${name}" is not a String or ID field`;
819
+ else if (fields.includes(f.name)) problem = `field "${name}" is listed twice`;
820
+ else fields.push(f.name);
821
+ if (problem) break;
822
+ }
823
+ if (problem) {
824
+ report(typeName, {
825
+ severity: "unsupported",
826
+ feature: "@fulltext",
827
+ message: `index "${ix.name}": ${problem}; not converted`
828
+ });
829
+ continue;
830
+ }
831
+ names.add(ix.name);
832
+ out.push({
833
+ kind: "ModelAttribute",
834
+ name: "fulltext",
835
+ fields,
836
+ args: [{ key: "name", value: { kind: "string", value: ix.name } }]
837
+ });
838
+ }
839
+ return out;
840
+ }
710
841
  function skippedLine(f, why) {
711
842
  return `${f.name.value}: ${print(f.type)} (not converted: ${why})`;
712
843
  }
@@ -737,15 +868,47 @@ function dedupeNames(fields, typeName, report) {
737
868
  }
738
869
  return out;
739
870
  }
740
- function scalarMapping(named, types) {
871
+ var CYPHRA_TYPE_NAMES = /* @__PURE__ */ new Set([
872
+ "String",
873
+ "Int",
874
+ "Float",
875
+ "Boolean",
876
+ "DateTime",
877
+ "Date",
878
+ "BigInt",
879
+ "Json",
880
+ "LocalDateTime",
881
+ "LocalTime",
882
+ "Time",
883
+ "Duration",
884
+ "Point",
885
+ "CartesianPoint",
886
+ "Vector"
887
+ ]);
888
+ function enumMappings(types, nodeNames, report) {
889
+ const out = /* @__PURE__ */ new Map();
890
+ for (const t of types.values()) {
891
+ if (t.kind !== "enum") continue;
892
+ if (CYPHRA_TYPE_NAMES.has(t.name) || nodeNames.has(t.name) || t.values.length === 0) {
893
+ out.set(t.name, ENUM_AS_STRING);
894
+ if ("note" in ENUM_AS_STRING && ENUM_AS_STRING.note) {
895
+ report(t.name, { severity: "changed", feature: "enum", message: ENUM_AS_STRING.note });
896
+ }
897
+ continue;
898
+ }
899
+ out.set(t.name, enumField(t.name));
900
+ }
901
+ return out;
902
+ }
903
+ function scalarMapping(named, types, enums) {
741
904
  const builtin = SCALARS[named];
742
905
  if (builtin) return builtin;
743
906
  const t = types.get(named);
744
- if (t?.kind === "enum") return { ...ENUM_FIELD, isEnum: true };
907
+ if (t?.kind === "enum") return { ...enums.get(named) ?? ENUM_AS_STRING, isEnum: true };
745
908
  return CUSTOM_SCALAR_FIELD;
746
909
  }
747
910
  var DECORATOR_ORDER = ["id", "unique", "index", "default"];
748
- function convertScalar(f, u, at, owner, nodeHasId, types, report) {
911
+ function convertScalar(f, u, at, owner, nodeHasId, mapScalar, report) {
749
912
  if (u.nested) {
750
913
  report(at, {
751
914
  severity: "unsupported",
@@ -754,7 +917,7 @@ function convertScalar(f, u, at, owner, nodeHasId, types, report) {
754
917
  });
755
918
  return void 0;
756
919
  }
757
- const mapping = scalarMapping(u.named, types);
920
+ const mapping = mapScalar(u.named);
758
921
  if ("unsupported" in mapping) {
759
922
  report(at, {
760
923
  severity: "unsupported",
@@ -813,7 +976,12 @@ function convertScalar(f, u, at, owner, nodeHasId, types, report) {
813
976
  field: {
814
977
  kind: "Scalar",
815
978
  name,
816
- type: u.list ? { name: mapping.type, optional: false, list: true } : { name: mapping.type, optional },
979
+ type: {
980
+ name: mapping.type,
981
+ optional: u.list ? false : optional,
982
+ ...u.list ? { list: true } : {},
983
+ ...mapping.enum ? { enum: mapping.enum } : {}
984
+ },
817
985
  decorators
818
986
  },
819
987
  takesId
@@ -923,6 +1091,7 @@ function convertRelation(f, u, at, ownerType, types, nodeName, report) {
923
1091
 
924
1092
  // src/import/print.ts
925
1093
  import {
1094
+ formatModelAttribute,
926
1095
  parseSchema,
927
1096
  printSchemaDocument,
928
1097
  resolveSchema
@@ -932,7 +1101,9 @@ function printDeclaration(decl, notes) {
932
1101
  const text = printSchemaDocument({ kind: "Document", declarations: [decl] }).trimEnd();
933
1102
  if (!notes?.length) return text;
934
1103
  const lines = text.split("\n");
935
- lines.splice(lines.length - 1, 0, ...notes.map((n) => ` // ${n}`));
1104
+ const attributes = decl.kind === "Enum" ? void 0 : decl.attributes;
1105
+ const attrs = attributes?.length ? attributes.length + 1 : 0;
1106
+ lines.splice(lines.length - 1 - attrs, 0, ...notes.map((n) => ` // ${n}`));
936
1107
  return lines.join("\n");
937
1108
  }
938
1109
  function printDeclarations(result, decls) {
@@ -1010,8 +1181,7 @@ function mergeImportedSchema(existing, result) {
1010
1181
  }
1011
1182
  if (decl.kind !== "Node" || current.kind !== "Node") {
1012
1183
  const same = decl.kind === current.kind && printSchemaDocument({ kind: "Document", declarations: [decl] }) === printSchemaDocument({ kind: "Document", declarations: [current] });
1013
- if (!same)
1014
- kept(decl.name, `${current.kind === "Node" ? "node" : "relationship"} ${decl.name}`);
1184
+ if (!same) kept(decl.name, `${current.kind.toLowerCase()} ${decl.name}`);
1015
1185
  continue;
1016
1186
  }
1017
1187
  const missing = [];
@@ -1021,13 +1191,23 @@ function mergeImportedSchema(existing, result) {
1021
1191
  else if (formatField(mine) !== formatField(f))
1022
1192
  kept(`${decl.name}.${f.name}`, `field ${f.name}`);
1023
1193
  }
1194
+ const nameOf = (a) => a.args.find((x) => x.key === "name")?.value.value;
1195
+ const attrs = [];
1196
+ for (const a of decl.attributes ?? []) {
1197
+ const mine = current.attributes?.find(
1198
+ (x) => x.name === a.name && nameOf(x) === nameOf(a)
1199
+ );
1200
+ if (!mine) attrs.push(formatModelAttribute(a));
1201
+ else if (formatModelAttribute(mine) !== formatModelAttribute(a))
1202
+ kept(decl.name, `@@${a.name} ${String(nameOf(a))}`);
1203
+ }
1024
1204
  const notes = (result.notes.get(decl.name) ?? []).filter((n) => !out.includes(`// ${n}`));
1025
- if (missing.length === 0 && notes.length === 0) continue;
1205
+ if (missing.length === 0 && notes.length === 0 && attrs.length === 0) continue;
1026
1206
  const close = nodeCloseBrace(out, decl.name);
1027
1207
  if (close < 0) throw new Error(`Could not find the block of node "${decl.name}".`);
1028
1208
  const lineStart = out.lastIndexOf("\n", close - 1) + 1;
1029
1209
  const onOwnLine = out.slice(lineStart, close).trim() === "";
1030
- const added = [...missing.map(formatField), ...notes.map((n) => `// ${n}`)].map((l) => ` ${l}
1210
+ const added = [...missing.map(formatField), ...attrs, ...notes.map((n) => `// ${n}`)].map((l) => ` ${l}
1031
1211
  `).join("");
1032
1212
  out = onOwnLine ? out.slice(0, lineStart) + added + out.slice(lineStart) : `${out.slice(0, close).trimEnd()}
1033
1213
  ${added}${out.slice(close)}`;
@@ -1079,360 +1259,193 @@ import {
1079
1259
  getArgumentValues,
1080
1260
  getDirectiveValues
1081
1261
  } from "graphql";
1082
- import neo4j2, { isInt } from "neo4j-driver";
1262
+ import neo4j3, { isInt } from "neo4j-driver";
1083
1263
 
1084
- // src/v7/errors.ts
1264
+ // src/v7/auth/context.ts
1085
1265
  import { GraphQLError as GraphQLError2 } from "graphql";
1086
- var FOLLOW_UP = {
1087
- authorization: 74,
1088
- cypher: 75
1089
- };
1090
- function notImplemented(what, issue2) {
1091
- return new GraphQLError2(`Not implemented yet in @cyphra/graphql (see #${issue2}): ${what}`, {
1092
- extensions: { code: "NOT_IMPLEMENTED" }
1093
- });
1266
+ var UNAUTHENTICATED = "Unauthenticated";
1267
+ var FORBIDDEN = "Forbidden";
1268
+ function unauthenticated() {
1269
+ return new GraphQLError2(UNAUTHENTICATED);
1094
1270
  }
1095
-
1096
- // src/v7/model.ts
1097
- import {
1098
- Kind as Kind3,
1099
- parse as parse2,
1100
- valueFromASTUntyped
1101
- } from "graphql";
1102
-
1103
- // src/v7/naming.ts
1104
- import pluralizeLib from "pluralize";
1105
- function upperFirst(s) {
1106
- return s.charAt(0).toUpperCase() + s.slice(1);
1271
+ function forbidden() {
1272
+ return new GraphQLError2(FORBIDDEN);
1107
1273
  }
1108
- function camelCase(input) {
1109
- const s = input.replace(/^_+/, "");
1110
- const words = s.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_\-.]+/).filter(Boolean);
1111
- return words.map((w, i) => i === 0 ? w.toLowerCase() : upperFirst(w.toLowerCase())).join("");
1274
+ function isRecord(v) {
1275
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1112
1276
  }
1113
- function leadingUnderscores(name) {
1114
- return /^_+/.exec(name)?.[0] ?? "";
1277
+ var DISALLOWED_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
1278
+ function readPath(value, segments) {
1279
+ let cur = value;
1280
+ for (const s of segments) {
1281
+ if (DISALLOWED_KEYS.has(s)) return void 0;
1282
+ if (typeof cur !== "object" || cur === null) return void 0;
1283
+ if (!Object.prototype.hasOwnProperty.call(cur, s)) return void 0;
1284
+ cur = cur[s];
1285
+ }
1286
+ return cur;
1115
1287
  }
1116
- function pluralize(word) {
1117
- return pluralizeLib(word);
1288
+ function splitClaimPath(path) {
1289
+ return path.split(/(?<!\\)\./).map((p) => p.replaceAll("\\.", "."));
1118
1290
  }
1119
- function entityPlural(name, pluralOverride) {
1120
- if (pluralOverride !== void 0)
1121
- return `${leadingUnderscores(pluralOverride)}${camelCase(pluralOverride)}`;
1122
- return `${leadingUnderscores(name)}${pluralizeLib(camelCase(name))}`;
1291
+ async function authContextFor(contextValue, model, decoder) {
1292
+ const context = isRecord(contextValue) ? contextValue : {};
1293
+ const trusted = context.jwt;
1294
+ if (trusted !== void 0 && trusted !== null && trusted !== false && trusted !== "") {
1295
+ if (!isRecord(trusted)) {
1296
+ throw new GraphQLError2("context.jwt must be the decoded JWT payload (an object).");
1297
+ }
1298
+ return { isAuthenticated: true, jwt: trusted, claims: void 0, context };
1299
+ }
1300
+ if (decoder && typeof context.token === "string") {
1301
+ const payload = await decoder.decode(context);
1302
+ if (payload) {
1303
+ return {
1304
+ isAuthenticated: true,
1305
+ jwt: payload,
1306
+ claims: model.jwtClaims,
1307
+ context
1308
+ };
1309
+ }
1310
+ }
1311
+ return { isAuthenticated: false, jwt: void 0, claims: void 0, context };
1123
1312
  }
1124
-
1125
- // src/v7/model.ts
1126
- var SUPPORTED_SCALARS = [
1127
- "ID",
1128
- "String",
1129
- "Int",
1130
- "Float",
1131
- "Boolean",
1132
- "BigInt",
1133
- "Date",
1134
- "DateTime"
1135
- ];
1136
- var UNSUPPORTED_SCALARS = /* @__PURE__ */ new Set([
1137
- "LocalDateTime",
1138
- "Time",
1139
- "LocalTime",
1140
- "Duration",
1141
- "Point",
1142
- "CartesianPoint"
1143
- ]);
1144
- var UnsupportedTypeDefsError = class extends Error {
1145
- name = "UnsupportedTypeDefsError";
1313
+ function claimValue(auth, field) {
1314
+ const mapped = auth.claims?.get(field);
1315
+ return readPath(auth.jwt ?? {}, mapped ? splitClaimPath(mapped) : [field]);
1316
+ }
1317
+ var JWT_WHERE_KEY = /^(?<fieldName>[_A-Za-z]\w*?)(?:_(?<operator>IN|INCLUDES|MATCHES|CONTAINS|STARTS_WITH|ENDS_WITH|EQ|LT|LTE|GT|GTE))?$/;
1318
+ var GENERIC_OPERATORS = {
1319
+ eq: "EQ",
1320
+ in: "IN",
1321
+ includes: "INCLUDES",
1322
+ contains: "CONTAINS",
1323
+ startsWith: "STARTS_WITH",
1324
+ endsWith: "ENDS_WITH",
1325
+ matches: "MATCHES",
1326
+ lt: "LT",
1327
+ lte: "LTE",
1328
+ gt: "GT",
1329
+ gte: "GTE"
1146
1330
  };
1147
- function directive2(dirs, name) {
1148
- return dirs?.find((d) => d.name.value === name);
1331
+ function parseJwtWhereKey(key) {
1332
+ const m = JWT_WHERE_KEY.exec(key);
1333
+ if (!m?.groups) throw new GraphQLError2(`Invalid JWT filter ${key}`);
1334
+ return { field: m.groups.fieldName, operator: m.groups.operator };
1149
1335
  }
1150
- function arg2(d, name) {
1151
- return d?.arguments?.find((a) => a.name.value === name)?.value;
1336
+ function isPrimitive(v) {
1337
+ return ["string", "number", "boolean", "bigint"].includes(typeof v);
1152
1338
  }
1153
- function stringArg2(d, name) {
1154
- const v = arg2(d, name);
1155
- return v && (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) ? v.value : void 0;
1339
+ function ordered(received) {
1340
+ return typeof received === "string" ? BigInt(received) : received;
1156
1341
  }
1157
- function listArg(d, name) {
1158
- const v = arg2(d, name);
1159
- if (!v) return void 0;
1160
- if (v.kind === Kind3.LIST) {
1161
- return v.values.flatMap(
1162
- (x) => x.kind === Kind3.STRING || x.kind === Kind3.ENUM ? [x.value] : []
1163
- );
1342
+ function compareInJs(operator, received, value) {
1343
+ try {
1344
+ switch (operator) {
1345
+ case "EQ":
1346
+ return isPrimitive(received) && isPrimitive(value) && received == value;
1347
+ case "LT":
1348
+ return ordered(received) < value;
1349
+ case "LTE":
1350
+ return ordered(received) <= value;
1351
+ case "GT":
1352
+ return ordered(received) > value;
1353
+ case "GTE":
1354
+ return ordered(received) >= value;
1355
+ case "STARTS_WITH":
1356
+ return typeof received === "string" && typeof value === "string" && received.startsWith(value);
1357
+ case "ENDS_WITH":
1358
+ return typeof received === "string" && typeof value === "string" && received.endsWith(value);
1359
+ case "CONTAINS":
1360
+ return typeof received === "string" && typeof value === "string" && received.includes(value);
1361
+ case "INCLUDES":
1362
+ return Array.isArray(received) && received.some((v) => v === value);
1363
+ case "IN":
1364
+ return Array.isArray(value) && value.some((v) => v === received);
1365
+ }
1366
+ } catch {
1367
+ return false;
1164
1368
  }
1165
- if (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) return [v.value];
1166
- return void 0;
1369
+ throw new GraphQLError2(`Operator ${operator} is not supported in @authentication(jwt)`);
1167
1370
  }
1168
- function typeRef(t) {
1169
- let cur = t;
1170
- let required = false;
1171
- if (cur.kind === Kind3.NON_NULL_TYPE) {
1172
- required = true;
1173
- cur = cur.type;
1174
- }
1175
- if (cur.kind === Kind3.LIST_TYPE) {
1176
- let inner = cur.type;
1177
- let elementRequired = false;
1178
- if (inner.kind === Kind3.NON_NULL_TYPE) {
1179
- elementRequired = true;
1180
- inner = inner.type;
1371
+ function jwtMatches(where, auth) {
1372
+ for (const [key, value] of Object.entries(where)) {
1373
+ if (key === "AND" || key === "OR") {
1374
+ const results = (Array.isArray(value) ? value : [value]).map(
1375
+ (w) => isRecord(w) ? jwtMatches(w, auth) : false
1376
+ );
1377
+ if (key === "AND" ? !results.every(Boolean) : !results.some(Boolean)) return false;
1378
+ continue;
1379
+ }
1380
+ if (key === "NOT") {
1381
+ if (!isRecord(value) || jwtMatches(value, auth)) return false;
1382
+ continue;
1383
+ }
1384
+ const { field, operator } = parseJwtWhereKey(key);
1385
+ const received = claimValue(auth, field);
1386
+ if (!received) return false;
1387
+ if (operator) {
1388
+ if (!compareInJs(operator, received, value)) return false;
1389
+ continue;
1390
+ }
1391
+ if (!isRecord(value)) return false;
1392
+ for (const [op, v] of Object.entries(value)) {
1393
+ const legacy = GENERIC_OPERATORS[op];
1394
+ if (!legacy)
1395
+ throw new GraphQLError2(`Operator ${op} is not supported in @authentication(jwt)`);
1396
+ if (!compareInJs(legacy, received, v)) return false;
1181
1397
  }
1182
- if (inner.kind !== Kind3.NAMED_TYPE)
1183
- throw new UnsupportedTypeDefsError("Nested lists are not supported.");
1184
- return { name: inner.name.value, list: true, required, elementRequired };
1185
1398
  }
1186
- return {
1187
- name: cur.name.value,
1188
- list: false,
1189
- required,
1190
- elementRequired: false
1191
- };
1399
+ return true;
1192
1400
  }
1193
- var ACCEPTED_FIELD_DIRECTIVES = /* @__PURE__ */ new Set([
1194
- "id",
1195
- "default",
1196
- "timestamp",
1197
- "cypher",
1198
- "relationship",
1199
- "alias",
1200
- "deprecated",
1201
- "coalesce",
1202
- "unique"
1203
- ]);
1204
- var ACCEPTED_TYPE_DIRECTIVES = /* @__PURE__ */ new Set([
1205
- "node",
1206
- "plural",
1207
- "authentication",
1208
- "authorization",
1209
- "relationshipProperties",
1210
- "jwt"
1211
- ]);
1212
- function deprecationReason(dirs) {
1213
- const d = directive2(dirs, "deprecated");
1214
- if (!d) return void 0;
1215
- return stringArg2(d, "reason") ?? "No longer supported";
1401
+ function applyAuthentication(annotation, operations, auth) {
1402
+ if (!annotation || !operations.some((op) => annotation.operations.has(op))) return;
1403
+ if (!auth.isAuthenticated) throw unauthenticated();
1404
+ if (annotation.jwt && (!auth.jwt || !jwtMatches(annotation.jwt, auth))) throw unauthenticated();
1216
1405
  }
1217
- function readAttribute(owner, f, enums) {
1218
- for (const d of f.directives ?? []) {
1219
- if (!ACCEPTED_FIELD_DIRECTIVES.has(d.name.value)) {
1220
- throw new UnsupportedTypeDefsError(
1221
- `${owner}.${f.name.value}: @${d.name.value} is not supported by @cyphra/graphql yet.`
1222
- );
1223
- }
1406
+ function checkAuthentication(model, auth, node, operations, field) {
1407
+ applyAuthentication(model.authentication, operations, auth);
1408
+ if (field === void 0) {
1409
+ applyAuthentication(node.auth.authentication, operations, auth);
1410
+ } else {
1411
+ const attr = node.attributes.find((a) => a.name === field);
1412
+ applyAuthentication(attr?.auth?.authentication, operations, auth);
1224
1413
  }
1225
- if (f.arguments?.length) {
1226
- throw new UnsupportedTypeDefsError(
1227
- `${owner}.${f.name.value}: field arguments are not supported by @cyphra/graphql yet.`
1228
- );
1414
+ }
1415
+ function checkRootAuthentication(model, auth, type, field) {
1416
+ const operations = type === "Query" ? ["READ"] : ["CREATE", "UPDATE", "DELETE"];
1417
+ applyAuthentication(model.authentication, operations, auth);
1418
+ applyAuthentication(
1419
+ (type === "Query" ? model.query : model.mutation).authentication,
1420
+ operations,
1421
+ auth
1422
+ );
1423
+ applyAuthentication(field.authentication, operations, auth);
1424
+ }
1425
+
1426
+ // src/v7/auth/rules.ts
1427
+ import { GraphQLError as GraphQLError3 } from "graphql";
1428
+
1429
+ // src/v7/cypher/where.ts
1430
+ import neo4j2 from "neo4j-driver";
1431
+
1432
+ // src/v7/cypher/context.ts
1433
+ var CypherContext = class {
1434
+ params = {};
1435
+ paramCount = 0;
1436
+ varCount = 0;
1437
+ /** `$jwt` of `@cypher` statements: the decoded JWT, `{}` when not authenticated (v7). */
1438
+ jwt = {};
1439
+ /** Bind a value and return its `$placeholder`. */
1440
+ param(value) {
1441
+ const key = `p${this.paramCount++}`;
1442
+ this.params[key] = value;
1443
+ return `$${key}`;
1229
1444
  }
1230
- const type = typeRef(f.type);
1231
- const isEnum = enums.has(type.name);
1232
- if (!isEnum && !SUPPORTED_SCALARS.includes(type.name)) {
1233
- if (UNSUPPORTED_SCALARS.has(type.name)) {
1234
- throw new UnsupportedTypeDefsError(
1235
- `${owner}.${f.name.value}: ${type.name} is not supported by @cyphra/graphql yet.`
1236
- );
1237
- }
1238
- throw new UnsupportedTypeDefsError(
1239
- `${owner}.${f.name.value}: type ${type.name} is not a supported scalar or enum (fields returning objects need @relationship).`
1240
- );
1241
- }
1242
- const dirs = f.directives;
1243
- const def = directive2(dirs, "default");
1244
- const defaultAst = arg2(def, "value");
1245
- const ts = directive2(dirs, "timestamp");
1246
- const cypher = directive2(dirs, "cypher");
1247
- const alias = directive2(dirs, "alias");
1248
- return {
1249
- name: f.name.value,
1250
- property: stringArg2(alias, "property") ?? f.name.value,
1251
- type,
1252
- kind: isEnum ? "enum" : "scalar",
1253
- description: f.description?.value,
1254
- id: !!directive2(dirs, "id"),
1255
- defaultAst,
1256
- defaultValue: defaultAst ? valueFromASTUntyped(defaultAst) : void 0,
1257
- timestamp: ts ? listArg(ts, "operations") ?? ["CREATE", "UPDATE"] : void 0,
1258
- cypher: cypher ? {
1259
- statement: stringArg2(cypher, "statement") ?? "",
1260
- columnName: stringArg2(cypher, "columnName") ?? ""
1261
- } : void 0,
1262
- deprecated: deprecationReason(dirs)
1263
- };
1264
- }
1265
- var ALL_OPERATIONS = [
1266
- "READ",
1267
- "AGGREGATE",
1268
- "CREATE",
1269
- "UPDATE",
1270
- "DELETE",
1271
- "CREATE_RELATIONSHIP",
1272
- "DELETE_RELATIONSHIP",
1273
- "SUBSCRIBE"
1274
- ];
1275
- function readTypeDefs(typeDefs) {
1276
- const doc = parse2(typeDefs);
1277
- const objects = [];
1278
- const enums = /* @__PURE__ */ new Map();
1279
- for (const def of doc.definitions) {
1280
- switch (def.kind) {
1281
- case Kind3.OBJECT_TYPE_DEFINITION:
1282
- objects.push(def);
1283
- break;
1284
- case Kind3.ENUM_TYPE_DEFINITION:
1285
- enums.set(def.name.value, {
1286
- name: def.name.value,
1287
- description: def.description?.value,
1288
- values: (def.values ?? []).map((v) => ({
1289
- name: v.name.value,
1290
- description: v.description?.value,
1291
- deprecated: deprecationReason(v.directives)
1292
- }))
1293
- });
1294
- break;
1295
- case Kind3.SCALAR_TYPE_DEFINITION:
1296
- if (!SUPPORTED_SCALARS.includes(def.name.value)) {
1297
- throw new UnsupportedTypeDefsError(
1298
- `scalar ${def.name.value}: custom scalars are not supported by @cyphra/graphql yet.`
1299
- );
1300
- }
1301
- break;
1302
- case Kind3.DIRECTIVE_DEFINITION:
1303
- break;
1304
- default:
1305
- throw new UnsupportedTypeDefsError(
1306
- `${def.kind}${"name" in def && def.name ? ` ${def.name.value}` : ""}: not supported by @cyphra/graphql yet (only object types, enums and relationship properties).`
1307
- );
1308
- }
1309
- }
1310
- const enumNames = new Set(enums.keys());
1311
- const properties = /* @__PURE__ */ new Map();
1312
- const nodeDefs = [];
1313
- for (const o of objects) {
1314
- const name = o.name.value;
1315
- if (["Query", "Mutation", "Subscription"].includes(name)) {
1316
- throw new UnsupportedTypeDefsError(
1317
- `type ${name}: custom root fields are not supported by @cyphra/graphql yet.`
1318
- );
1319
- }
1320
- if (o.interfaces?.length) {
1321
- throw new UnsupportedTypeDefsError(
1322
- `type ${name}: interfaces are not supported by @cyphra/graphql yet.`
1323
- );
1324
- }
1325
- for (const d of o.directives ?? []) {
1326
- if (!ACCEPTED_TYPE_DIRECTIVES.has(d.name.value)) {
1327
- throw new UnsupportedTypeDefsError(
1328
- `type ${name}: @${d.name.value} is not supported by @cyphra/graphql yet.`
1329
- );
1330
- }
1331
- }
1332
- if (directive2(o.directives, "jwt")) continue;
1333
- if (directive2(o.directives, "relationshipProperties")) {
1334
- properties.set(name, {
1335
- name,
1336
- attributes: (o.fields ?? []).map((f) => readAttribute(name, f, enumNames))
1337
- });
1338
- continue;
1339
- }
1340
- if (!directive2(o.directives, "node")) {
1341
- throw new UnsupportedTypeDefsError(
1342
- `type ${name}: object types without @node are not supported by @cyphra/graphql yet.`
1343
- );
1344
- }
1345
- nodeDefs.push(o);
1346
- }
1347
- const nodeNames = new Set(nodeDefs.map((o) => o.name.value));
1348
- const nodes = nodeDefs.map((o) => {
1349
- const name = o.name.value;
1350
- const attributes = [];
1351
- const relationships = [];
1352
- for (const f of o.fields ?? []) {
1353
- const rel = directive2(f.directives, "relationship");
1354
- if (!rel) {
1355
- attributes.push(readAttribute(name, f, enumNames));
1356
- continue;
1357
- }
1358
- const t = typeRef(f.type);
1359
- if (!nodeNames.has(t.name)) {
1360
- throw new UnsupportedTypeDefsError(
1361
- `${name}.${f.name.value}: relationships to ${t.name} are not supported by @cyphra/graphql yet (target must be a @node type).`
1362
- );
1363
- }
1364
- for (const a of rel.arguments ?? []) {
1365
- if (!["type", "direction", "properties"].includes(a.name.value)) {
1366
- throw new UnsupportedTypeDefsError(
1367
- `${name}.${f.name.value}: @relationship(${a.name.value}) is not supported by @cyphra/graphql yet.`
1368
- );
1369
- }
1370
- }
1371
- const props = stringArg2(rel, "properties");
1372
- if (props && !properties.has(props)) {
1373
- throw new UnsupportedTypeDefsError(
1374
- `${name}.${f.name.value}: properties type ${props} must be a @relationshipProperties type.`
1375
- );
1376
- }
1377
- relationships.push({
1378
- name: f.name.value,
1379
- source: name,
1380
- target: t.name,
1381
- type: stringArg2(rel, "type") ?? "",
1382
- direction: stringArg2(rel, "direction") === "IN" ? "IN" : "OUT",
1383
- properties: props,
1384
- list: t.list,
1385
- required: t.required,
1386
- elementRequired: t.elementRequired,
1387
- description: f.description?.value,
1388
- deprecated: deprecationReason(f.directives)
1389
- });
1390
- }
1391
- const nodeDir = directive2(o.directives, "node");
1392
- const labels2 = listArg(nodeDir, "labels") ?? [name];
1393
- const pluralDir = directive2(o.directives, "plural");
1394
- const plural = entityPlural(name, stringArg2(pluralDir, "value"));
1395
- const authn = directive2(o.directives, "authentication");
1396
- return {
1397
- name,
1398
- description: o.description?.value,
1399
- labels: labels2,
1400
- plural,
1401
- pascalPlural: upperFirst(plural),
1402
- attributes,
1403
- relationships,
1404
- auth: {
1405
- authentication: authn ? listArg(authn, "operations") ?? ALL_OPERATIONS : void 0,
1406
- authorization: !!directive2(o.directives, "authorization")
1407
- }
1408
- };
1409
- });
1410
- const byName = new Map(nodes.map((n) => [n.name, n]));
1411
- return {
1412
- nodes,
1413
- properties,
1414
- enums,
1415
- node(name) {
1416
- const n = byName.get(name);
1417
- if (!n) throw new Error(`Unknown node type ${name}`);
1418
- return n;
1419
- }
1420
- };
1421
- }
1422
- function readNeedsAuth(node) {
1423
- return node.auth.authorization || (node.auth.authentication?.includes("READ") ?? false);
1424
- }
1425
-
1426
- // src/v7/cypher/context.ts
1427
- var CypherContext = class {
1428
- params = {};
1429
- paramCount = 0;
1430
- varCount = 0;
1431
- /** Bind a value and return its `$placeholder`. */
1432
- param(value) {
1433
- const key = `p${this.paramCount++}`;
1434
- this.params[key] = value;
1435
- return `$${key}`;
1445
+ /** Bind a value under a fixed name (`$jwt` of `@cypher` statements). */
1446
+ namedParam(name, value) {
1447
+ this.params[name] = value;
1448
+ return `$${name}`;
1436
1449
  }
1437
1450
  /** Fresh variable name, e.g. `this0`. */
1438
1451
  variable(prefix2 = "this") {
@@ -1462,8 +1475,105 @@ function withList(list2, l, body) {
1462
1475
  return `[${l} IN [${list2}] | ${body(l)}][0]`;
1463
1476
  }
1464
1477
 
1465
- // src/v7/cypher/where.ts
1478
+ // src/v7/cypher/custom.ts
1466
1479
  import neo4j from "neo4j-driver";
1480
+ var STATEMENT_MARK = "/* @cypher */";
1481
+ function hasStatement(...texts) {
1482
+ return texts.some((t) => t !== void 0 && t.includes(STATEMENT_MARK));
1483
+ }
1484
+ function argumentValue(arg3, value) {
1485
+ if (value === null || value === void 0) return null;
1486
+ if (Array.isArray(value)) return value.map((v) => argumentValue(arg3, v));
1487
+ if (arg3.kind === "scalar" && arg3.type.name === "Int" && typeof value === "number") {
1488
+ return neo4j.int(value);
1489
+ }
1490
+ return value;
1491
+ }
1492
+ function bindArguments(ctx, statement, args, values) {
1493
+ if (args.length === 0) return statement;
1494
+ const names = args.map((a) => a.name.replace(/[^_A-Za-z0-9]/g, ""));
1495
+ const re = new RegExp(`\\$(${names.join("|")})\\b`, "g");
1496
+ const bound = /* @__PURE__ */ new Map();
1497
+ return statement.replace(re, (_m, name) => {
1498
+ const value = values[name];
1499
+ if (value === void 0 || value === null) return "NULL";
1500
+ let p = bound.get(name);
1501
+ if (!p) {
1502
+ p = ctx.param(
1503
+ argumentValue(
1504
+ args.find((a) => a.name === name),
1505
+ value
1506
+ )
1507
+ );
1508
+ bound.set(name, p);
1509
+ }
1510
+ return p;
1511
+ });
1512
+ }
1513
+ function statementCall(ctx, cypher, args, values, variable) {
1514
+ const statement = bindArguments(ctx, cypher.statement, args, values);
1515
+ if (/\$jwt\b/.test(statement)) ctx.namedParam("jwt", ctx.jwt);
1516
+ if (variable === void 0) return `CALL () {
1517
+ ${STATEMENT_MARK}
1518
+ ${statement}
1519
+ }`;
1520
+ return `CALL (${variable}) {
1521
+ WITH ${variable} AS this
1522
+ ${STATEMENT_MARK}
1523
+ ${statement}
1524
+ }`;
1525
+ }
1526
+ function column(cypher) {
1527
+ return q(cypher.columnName);
1528
+ }
1529
+ function scalarClause(ctx, variable, cypher, args, values, list2) {
1530
+ const s = ctx.variable("cypher");
1531
+ const call = statementCall(ctx, cypher, args, values, variable);
1532
+ if (!list2) {
1533
+ return {
1534
+ clause: `CALL (${variable}) {
1535
+ ${call}
1536
+ RETURN ${column(cypher)} AS ${s}
1537
+ }`,
1538
+ variable: s
1539
+ };
1540
+ }
1541
+ const x = ctx.variable("value");
1542
+ return {
1543
+ clause: `CALL (${variable}) {
1544
+ ${call}
1545
+ UNWIND ${column(cypher)} AS ${x}
1546
+ RETURN collect(${x}) AS ${s}
1547
+ }`,
1548
+ variable: s
1549
+ };
1550
+ }
1551
+ function scalarExpr(ctx, variable, cypher, list2) {
1552
+ const call = statementCall(ctx, cypher, [], {}, variable);
1553
+ if (!list2) return `head(COLLECT {
1554
+ ${call}
1555
+ RETURN ${column(cypher)}
1556
+ })`;
1557
+ const x = ctx.variable("value");
1558
+ return `COLLECT {
1559
+ ${call}
1560
+ UNWIND ${column(cypher)} AS ${x}
1561
+ RETURN ${x}
1562
+ }`;
1563
+ }
1564
+ function nodeRows(ctx, variable, cypher, x) {
1565
+ const call = statementCall(ctx, cypher, [], {}, variable);
1566
+ return `${call}
1567
+ WITH ${column(cypher)} AS ${x} WHERE ${x} IS NOT NULL`;
1568
+ }
1569
+
1570
+ // src/v7/cypher/where.ts
1571
+ var AuthValue = class {
1572
+ constructor(value) {
1573
+ this.value = value;
1574
+ }
1575
+ value;
1576
+ };
1467
1577
  var LEGACY_OPERATORS = {
1468
1578
  EQ: "eq",
1469
1579
  IN: "in",
@@ -1483,7 +1593,9 @@ var QUANTIFIER_KEYS = {
1483
1593
  SOME: "some"
1484
1594
  };
1485
1595
  function isPlainObject(v) {
1486
- return typeof v === "object" && v !== null && !Array.isArray(v);
1596
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1597
+ const proto = Object.getPrototypeOf(v);
1598
+ return proto === Object.prototype || proto === null;
1487
1599
  }
1488
1600
  function and(parts) {
1489
1601
  const ps = parts.filter((p) => p !== void 0);
@@ -1491,11 +1603,19 @@ function and(parts) {
1491
1603
  if (ps.length === 1) return ps[0];
1492
1604
  return ps.map((p) => `(${p})`).join(" AND ");
1493
1605
  }
1606
+ function objectOrNothing(where, what) {
1607
+ return isFilterObject(where, what) ? where : void 0;
1608
+ }
1609
+ function isFilterObject(where, what) {
1610
+ if (where === null || where === void 0) return false;
1611
+ if (!isPlainObject(where)) throw new Error(`Invalid ${what}: expected an object`);
1612
+ return true;
1613
+ }
1494
1614
  function encodeValue(attr, value) {
1495
1615
  if (value === null || value === void 0) return null;
1496
1616
  if (Array.isArray(value)) return value.map((v) => encodeValue(attr, v));
1497
1617
  if (attr.kind === "scalar" && attr.type.name === "Int" && typeof value === "number") {
1498
- return neo4j.int(value);
1618
+ return neo4j2.int(value);
1499
1619
  }
1500
1620
  return value;
1501
1621
  }
@@ -1510,48 +1630,62 @@ function valueExpr(ctx, attr, value, isList) {
1510
1630
  }
1511
1631
  function attributePredicate(ctx, expr, attr, op, value) {
1512
1632
  if (value === void 0) return void 0;
1633
+ if (value instanceof AuthValue) {
1634
+ const p = ctx.param(value.value ?? null);
1635
+ const pred = attributeComparison(expr, attr, op, (isList) => castValue(attr, p, isList));
1636
+ return `(${p} IS NOT NULL AND ${pred})`;
1637
+ }
1513
1638
  if (op === "eq" && value === null) return `${expr} IS NULL`;
1514
1639
  if (value === null) return void 0;
1640
+ return attributeComparison(expr, attr, op, (isList) => valueExpr(ctx, attr, value, isList));
1641
+ }
1642
+ function attributeComparison(expr, attr, op, v) {
1515
1643
  if (attr.type.list) {
1516
1644
  switch (op) {
1517
1645
  case "eq":
1518
- return `${expr} = ${valueExpr(ctx, attr, value, true)}`;
1646
+ return `${expr} = ${v(true)}`;
1519
1647
  case "includes":
1520
- return `${valueExpr(ctx, attr, value, false)} IN ${expr}`;
1648
+ return `${v(false)} IN ${expr}`;
1521
1649
  }
1522
1650
  throw new Error(`Unsupported list filter operator ${op}`);
1523
1651
  }
1524
1652
  switch (op) {
1525
1653
  case "eq":
1526
- return `${expr} = ${valueExpr(ctx, attr, value, false)}`;
1654
+ return `${expr} = ${v(false)}`;
1527
1655
  case "in":
1528
- return `${expr} IN ${valueExpr(ctx, attr, value, true)}`;
1656
+ return `${expr} IN ${v(true)}`;
1529
1657
  case "contains":
1530
- return `${expr} CONTAINS ${valueExpr(ctx, attr, value, false)}`;
1658
+ return `${expr} CONTAINS ${v(false)}`;
1531
1659
  case "startsWith":
1532
- return `${expr} STARTS WITH ${valueExpr(ctx, attr, value, false)}`;
1660
+ return `${expr} STARTS WITH ${v(false)}`;
1533
1661
  case "endsWith":
1534
- return `${expr} ENDS WITH ${valueExpr(ctx, attr, value, false)}`;
1662
+ return `${expr} ENDS WITH ${v(false)}`;
1535
1663
  case "lt":
1536
- return `${expr} < ${valueExpr(ctx, attr, value, false)}`;
1664
+ return `${expr} < ${v(false)}`;
1537
1665
  case "lte":
1538
- return `${expr} <= ${valueExpr(ctx, attr, value, false)}`;
1666
+ return `${expr} <= ${v(false)}`;
1539
1667
  case "gt":
1540
- return `${expr} > ${valueExpr(ctx, attr, value, false)}`;
1668
+ return `${expr} > ${v(false)}`;
1541
1669
  case "gte":
1542
- return `${expr} >= ${valueExpr(ctx, attr, value, false)}`;
1670
+ return `${expr} >= ${v(false)}`;
1543
1671
  }
1544
1672
  throw new Error(`Unsupported filter operator ${op}`);
1545
1673
  }
1674
+ function attributeExpr(ctx, variable, attr) {
1675
+ if (!attr.cypher) return `${variable}.${q(attr.property)}`;
1676
+ if (attr.args.length)
1677
+ throw new Error(`Cannot filter on @cypher field ${attr.name} with arguments`);
1678
+ return scalarExpr(ctx, variable, attr.cypher, attr.type.list);
1679
+ }
1546
1680
  function attributeFilter(ctx, variable, attributes, key, value) {
1547
1681
  const direct = attributes.find((a) => a.name === key);
1548
1682
  if (direct) {
1549
1683
  if (value === null || value === void 0) return { handled: true };
1550
- if (direct.cypher) throw notImplemented(`filtering on @cypher field ${key}`, FOLLOW_UP.cypher);
1551
- const expr = `${variable}.${q(direct.property)}`;
1552
- const preds = Object.entries(value).map(
1553
- ([op, v]) => attributePredicate(ctx, expr, direct, op, v)
1554
- );
1684
+ if (!isPlainObject(value)) throw new Error(`Invalid filter on ${key}`);
1685
+ const ops = Object.entries(value).filter(([, v]) => v !== void 0);
1686
+ if (ops.length === 0) return { handled: true };
1687
+ const expr = attributeExpr(ctx, variable, direct);
1688
+ const preds = ops.map(([op, v]) => attributePredicate(ctx, expr, direct, op, v));
1555
1689
  return { handled: true, predicate: and(preds) };
1556
1690
  }
1557
1691
  const m = /^(.+)_([A-Z_]+)$/.exec(key);
@@ -1559,11 +1693,11 @@ function attributeFilter(ctx, variable, attributes, key, value) {
1559
1693
  const attr = attributes.find((a) => a.name === m[1]);
1560
1694
  const op = LEGACY_OPERATORS[m[2]];
1561
1695
  if (attr && op) {
1562
- if (attr.cypher)
1563
- throw notImplemented(`filtering on @cypher field ${attr.name}`, FOLLOW_UP.cypher);
1696
+ if (value === void 0) return { handled: true };
1697
+ if (value === null && op !== "eq") return { handled: true };
1564
1698
  return {
1565
1699
  handled: true,
1566
- predicate: attributePredicate(ctx, `${variable}.${q(attr.property)}`, attr, op, value)
1700
+ predicate: attributePredicate(ctx, attributeExpr(ctx, variable, attr), attr, op, value)
1567
1701
  };
1568
1702
  }
1569
1703
  }
@@ -1572,8 +1706,8 @@ function attributeFilter(ctx, variable, attributes, key, value) {
1572
1706
  function logical(where, key, compile) {
1573
1707
  const value = where[key];
1574
1708
  if (key === "AND" || key === "OR") {
1575
- if (!Array.isArray(value)) return { handled: true };
1576
- const parts = value.filter(isPlainObject).map(compile);
1709
+ if (value === null || value === void 0) return { handled: true };
1710
+ const parts = (Array.isArray(value) ? value : [value]).filter((w) => w !== null && w !== void 0).map((w) => compile(objectOrNothing(w, key)));
1577
1711
  if (key === "AND") return { handled: true, predicate: and(parts) };
1578
1712
  if (parts.length === 0) return { handled: true };
1579
1713
  if (parts.some((p) => p === void 0)) return { handled: true, predicate: "true" };
@@ -1583,8 +1717,9 @@ function logical(where, key, compile) {
1583
1717
  };
1584
1718
  }
1585
1719
  if (key === "NOT") {
1586
- if (!isPlainObject(value)) return { handled: true };
1587
- const inner = compile(value);
1720
+ const o = objectOrNothing(value, key);
1721
+ if (o === void 0) return { handled: true };
1722
+ const inner = compile(o);
1588
1723
  return { handled: true, predicate: inner === void 0 ? void 0 : `NOT (${inner})` };
1589
1724
  }
1590
1725
  return { handled: false };
@@ -1607,6 +1742,7 @@ function quantified(pattern, quantifier, predicate) {
1607
1742
  case "all":
1608
1743
  return `EXISTS { MATCH ${pattern} } AND NOT EXISTS { MATCH ${pattern} WHERE NOT (${predicate}) }`;
1609
1744
  }
1745
+ throw new Error(`Unknown relationship filter ${String(quantifier)}`);
1610
1746
  }
1611
1747
  var AGGREGATION_COMPARISON = {
1612
1748
  EQ: "eq",
@@ -1646,23 +1782,22 @@ function comparison(ctx, expr, op, value, attr) {
1646
1782
  if (value === void 0 || value === null) return void 0;
1647
1783
  const cmp = COMPARISON_OPERATORS[op];
1648
1784
  if (!cmp) throw new Error(`Invalid aggregation filter operator ${op}`);
1649
- const p = ctx.param(value);
1785
+ const ref = value instanceof AuthValue;
1786
+ const p = ctx.param(ref ? value.value ?? null : value);
1650
1787
  const isDateTime2 = attr?.kind === "scalar" && attr.type.name === "DateTime";
1651
- return `${expr} ${cmp} ${isDateTime2 ? `datetime(${p})` : p}`;
1788
+ const pred = `${expr} ${cmp} ${isDateTime2 ? `datetime(${p})` : p}`;
1789
+ return ref ? `(${p} IS NOT NULL AND ${pred})` : pred;
1652
1790
  }
1653
1791
  var WhereCompiler = class {
1654
- constructor(model, ctx, onTraverse = () => {
1655
- }) {
1792
+ constructor(model, ctx) {
1656
1793
  this.model = model;
1657
1794
  this.ctx = ctx;
1658
- this.onTraverse = onTraverse;
1659
1795
  }
1660
1796
  model;
1661
1797
  ctx;
1662
- onTraverse;
1663
1798
  /** Predicate for a `${Node}Where` input on `variable`, or `undefined` when it filters nothing. */
1664
1799
  node(variable, node, where) {
1665
- if (!isPlainObject(where)) return void 0;
1800
+ if (!isFilterObject(where, "filter")) return void 0;
1666
1801
  const parts = [];
1667
1802
  for (const [key, value] of Object.entries(where)) {
1668
1803
  if (value === void 0) continue;
@@ -1676,21 +1811,99 @@ var WhereCompiler = class {
1676
1811
  parts.push(a.predicate);
1677
1812
  continue;
1678
1813
  }
1814
+ const c = this.cypherNodeFilter(variable, node, key, value);
1815
+ if (c.handled) {
1816
+ parts.push(c.predicate);
1817
+ continue;
1818
+ }
1679
1819
  parts.push(this.relationshipFilter(variable, node, key, value));
1680
1820
  }
1681
1821
  return and(parts);
1682
1822
  }
1823
+ /**
1824
+ * Filters on `@cypher` fields returning nodes (v7 7.6): for a list, `actors: { some | all | none |
1825
+ * single }` (and `actors_SOME`, …) test the returned nodes with `any` / `all` / `none` / `single`
1826
+ * (so `all` holds when the statement returns nothing); for one node, `topActor: { … }` tests the
1827
+ * first returned node and `topActor: null` matches when there is none.
1828
+ */
1829
+ cypherNodeFilter(variable, node, key, value) {
1830
+ const legacy = /^(.+)_(ALL|NONE|SINGLE|SOME)$/.exec(key);
1831
+ const name = node.cypherNodes.some((c) => c.name === key) ? key : legacy?.[1];
1832
+ const field = node.cypherNodes.find((c) => c.name === name);
1833
+ if (!field) return { handled: false };
1834
+ if (field.args.length)
1835
+ throw new Error(`Cannot filter on @cypher field ${field.name} with arguments`);
1836
+ const target = this.model.node(field.target);
1837
+ if (!field.type.list) {
1838
+ if (value === void 0) return { handled: true };
1839
+ const x = this.ctx.variable("n");
1840
+ const rows = nodeRows(this.ctx, variable, field.cypher, x);
1841
+ if (value === null) return { handled: true, predicate: `NOT EXISTS {
1842
+ ${rows}
1843
+ }` };
1844
+ const pred = this.node(x, target, value);
1845
+ if (pred === void 0) return { handled: true };
1846
+ return {
1847
+ handled: true,
1848
+ predicate: `EXISTS {
1849
+ ${rows}
1850
+ WITH ${x} LIMIT 1
1851
+ WITH ${x} WHERE ${pred}
1852
+ }`
1853
+ };
1854
+ }
1855
+ const quantifiers = key === field.name ? isFilterObject(value, key) ? Object.entries(value).map(([k, w]) => [k, w]) : [] : [[QUANTIFIER_KEYS[legacy[2]], value]];
1856
+ return {
1857
+ handled: true,
1858
+ predicate: and(
1859
+ quantifiers.map(
1860
+ ([quantifier, w]) => this.cypherNodes(variable, field, target, quantifier, w)
1861
+ )
1862
+ )
1863
+ };
1864
+ }
1865
+ /** `any` / `all` / `none` / `single` of the nodes returned by the statement (v7 semantics). */
1866
+ cypherNodes(variable, field, target, quantifier, where) {
1867
+ if (!isFilterObject(where, "filter")) return void 0;
1868
+ const x = this.ctx.variable("n");
1869
+ const pred = this.node(x, target, where);
1870
+ if (pred === void 0) return void 0;
1871
+ const rows = () => nodeRows(this.ctx, variable, field.cypher, x);
1872
+ const matching = () => `COUNT {
1873
+ ${rows()}
1874
+ WITH ${x} WHERE ${pred}
1875
+ }`;
1876
+ switch (quantifier) {
1877
+ case "some":
1878
+ return `EXISTS {
1879
+ ${rows()}
1880
+ WITH ${x} WHERE ${pred}
1881
+ }`;
1882
+ case "none":
1883
+ return `NOT EXISTS {
1884
+ ${rows()}
1885
+ WITH ${x} WHERE ${pred}
1886
+ }`;
1887
+ case "single":
1888
+ return `${matching()} = 1`;
1889
+ case "all":
1890
+ return `${matching()} = COUNT {
1891
+ ${rows()}
1892
+ }`;
1893
+ }
1894
+ throw new Error(`Unknown relationship filter ${String(quantifier)}`);
1895
+ }
1683
1896
  relationshipFilter(variable, node, key, value) {
1684
1897
  const find = (name) => node.relationships.find((r) => r.name === name);
1685
1898
  let rel = find(key);
1686
1899
  if (rel) {
1687
- if (!isPlainObject(value)) return void 0;
1900
+ if (!isFilterObject(value, key)) return void 0;
1688
1901
  return and(
1689
1902
  Object.entries(value).map(([q2, w]) => this.related(variable, rel, q2, w))
1690
1903
  );
1691
1904
  }
1692
1905
  if (key.endsWith("Connection") && (rel = find(key.slice(0, -"Connection".length)))) {
1693
- if (!isPlainObject(value)) return void 0;
1906
+ if (!isFilterObject(value, key)) return void 0;
1694
1907
  return and(
1695
1908
  Object.entries(value).map(([q2, w]) => {
1696
1909
  if (q2 === "aggregate") return this.aggregate(variable, rel, w, false);
@@ -1712,10 +1925,9 @@ var WhereCompiler = class {
1712
1925
  throw new Error(`Unknown filter ${node.name}Where.${key}`);
1713
1926
  }
1714
1927
  related(variable, rel, quantifier, where) {
1715
- if (!isPlainObject(where)) return void 0;
1928
+ if (!isFilterObject(where, "filter")) return void 0;
1716
1929
  const m = this.ctx.variable("n");
1717
1930
  const target = this.model.node(rel.target);
1718
- this.onTraverse(target);
1719
1931
  return quantified(
1720
1932
  relationshipPattern(this.model, variable, rel, m),
1721
1933
  quantifier,
@@ -1723,10 +1935,9 @@ var WhereCompiler = class {
1723
1935
  );
1724
1936
  }
1725
1937
  relatedConnection(variable, rel, quantifier, where) {
1726
- if (!isPlainObject(where)) return void 0;
1938
+ if (!isFilterObject(where, "filter")) return void 0;
1727
1939
  const m = this.ctx.variable("n");
1728
1940
  const r = this.ctx.variable("r");
1729
- this.onTraverse(this.model.node(rel.target));
1730
1941
  return quantified(
1731
1942
  relationshipPattern(this.model, variable, rel, m, r),
1732
1943
  quantifier,
@@ -1738,9 +1949,8 @@ var WhereCompiler = class {
1738
1949
  * the `actorsAggregate` form): `count`, `node`, `edge`, combined with AND / OR / NOT.
1739
1950
  */
1740
1951
  aggregate(variable, rel, where, deprecated) {
1741
- if (!isPlainObject(where)) return void 0;
1952
+ if (!isFilterObject(where, "filter")) return void 0;
1742
1953
  const target = this.model.node(rel.target);
1743
- this.onTraverse(target);
1744
1954
  const m = this.ctx.variable("n");
1745
1955
  const r = this.ctx.variable("r");
1746
1956
  const pattern = relationshipPattern(this.model, variable, rel, m, r);
@@ -1755,13 +1965,13 @@ var WhereCompiler = class {
1755
1965
  continue;
1756
1966
  }
1757
1967
  if (key === "count") {
1758
- if (!isPlainObject(value)) continue;
1968
+ if (!isFilterObject(value, key)) continue;
1759
1969
  if (deprecated) {
1760
1970
  parts.push(this.countFilter(scope, false, value));
1761
1971
  continue;
1762
1972
  }
1763
1973
  for (const [what, filters] of Object.entries(value)) {
1764
- if (!isPlainObject(filters)) continue;
1974
+ if (!isFilterObject(filters, what)) continue;
1765
1975
  if (what === "nodes") parts.push(this.countFilter(scope, true, filters));
1766
1976
  else if (what === "edges") parts.push(this.countFilter(scope, false, filters));
1767
1977
  else throw new Error(`Unknown aggregation count filter ${what}`);
@@ -1802,7 +2012,7 @@ var WhereCompiler = class {
1802
2012
  }
1803
2013
  /** `${…}NodeAggregationWhereInput` / `${Properties}AggregationWhereInput`. */
1804
2014
  aggregationWhere(scope, attributes, on, distinct, where) {
1805
- if (!isPlainObject(where)) return void 0;
2015
+ if (!isFilterObject(where, "filter")) return void 0;
1806
2016
  const parts = [];
1807
2017
  for (const [key, value] of Object.entries(where)) {
1808
2018
  if (value === void 0 || value === null) continue;
@@ -1817,9 +2027,9 @@ var WhereCompiler = class {
1817
2027
  }
1818
2028
  const direct = attributes.find((a) => a.name === key);
1819
2029
  if (direct) {
1820
- if (!isPlainObject(value)) continue;
2030
+ if (!isFilterObject(value, key)) continue;
1821
2031
  for (const [aggOp, filters] of Object.entries(value)) {
1822
- if (!isPlainObject(filters)) continue;
2032
+ if (!isFilterObject(filters, aggOp)) continue;
1823
2033
  const fn = GENERIC_AGGREGATES[aggOp];
1824
2034
  if (!fn) throw new Error(`Invalid aggregation operator ${aggOp}`);
1825
2035
  const agg2 = this.aggregated(scope, direct, on, distinct, fn);
@@ -1850,7 +2060,7 @@ var WhereCompiler = class {
1850
2060
  }
1851
2061
  /** Predicate for a `${Source}${Rel}ConnectionWhere` input (`node` / `edge`, AND / OR / NOT). */
1852
2062
  connection(relVar, nodeVar, rel, where) {
1853
- if (!isPlainObject(where)) return void 0;
2063
+ if (!isFilterObject(where, "filter")) return void 0;
1854
2064
  const parts = [];
1855
2065
  for (const [key, value] of Object.entries(where)) {
1856
2066
  if (value === void 0) continue;
@@ -1874,7 +2084,7 @@ var WhereCompiler = class {
1874
2084
  }
1875
2085
  /** Predicate for a `${Properties}Where` input on a relationship variable. */
1876
2086
  edge(relVar, props, where) {
1877
- if (!isPlainObject(where)) return void 0;
2087
+ if (!isFilterObject(where, "filter")) return void 0;
1878
2088
  const parts = [];
1879
2089
  for (const [key, value] of Object.entries(where)) {
1880
2090
  if (value === void 0) continue;
@@ -1891,7 +2101,977 @@ var WhereCompiler = class {
1891
2101
  }
1892
2102
  };
1893
2103
 
2104
+ // src/v7/auth/rules.ts
2105
+ function isRecord2(v) {
2106
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
2107
+ const proto = Object.getPrototypeOf(v);
2108
+ return proto === Object.prototype || proto === null;
2109
+ }
2110
+ function and2(parts) {
2111
+ const ps = parts.filter((p) => p !== void 0);
2112
+ if (ps.length === 0) return void 0;
2113
+ if (ps.length === 1) return ps[0];
2114
+ return ps.map((p) => `(${p})`).join(" AND ");
2115
+ }
2116
+ function or(parts) {
2117
+ const ps = parts.filter((p) => p !== void 0);
2118
+ if (ps.length === 0) return void 0;
2119
+ if (ps.length === 1) return ps[0];
2120
+ return ps.map((p) => `(${p})`).join(" OR ");
2121
+ }
2122
+ function jwtComparison(operator, claim, value) {
2123
+ switch (operator) {
2124
+ case "EQ":
2125
+ return `${claim} = ${value}`;
2126
+ case "IN":
2127
+ return `${claim} IN ${value}`;
2128
+ case "INCLUDES":
2129
+ return `${value} IN ${claim}`;
2130
+ case "CONTAINS":
2131
+ return `${claim} CONTAINS ${value}`;
2132
+ case "STARTS_WITH":
2133
+ return `${claim} STARTS WITH ${value}`;
2134
+ case "ENDS_WITH":
2135
+ return `${claim} ENDS WITH ${value}`;
2136
+ case "MATCHES":
2137
+ return `${claim} =~ ${value}`;
2138
+ case "LT":
2139
+ return `${claim} < ${value}`;
2140
+ case "LTE":
2141
+ return `${claim} <= ${value}`;
2142
+ case "GT":
2143
+ return `${claim} > ${value}`;
2144
+ case "GTE":
2145
+ return `${claim} >= ${value}`;
2146
+ }
2147
+ throw new GraphQLError3(`Invalid operator ${operator} in an authorization JWT filter`);
2148
+ }
2149
+ function annotations(node, attributes) {
2150
+ return [node.auth, ...attributes.map((a) => a.auth)];
2151
+ }
2152
+ var AuthRules = class {
2153
+ constructor(model, ctx, auth) {
2154
+ this.ctx = ctx;
2155
+ this.auth = auth;
2156
+ this.where = new WhereCompiler(model, ctx);
2157
+ }
2158
+ ctx;
2159
+ auth;
2160
+ where;
2161
+ isAuthenticatedParam;
2162
+ forbiddenParam;
2163
+ /** `$pN` holding the "Forbidden" message (one parameter per statement). */
2164
+ forbiddenMessage() {
2165
+ this.forbiddenParam ??= this.ctx.param("Forbidden");
2166
+ return this.forbiddenParam;
2167
+ }
2168
+ isAuthenticated() {
2169
+ this.isAuthenticatedParam ??= this.ctx.param(this.auth.isAuthenticated);
2170
+ return this.isAuthenticatedParam;
2171
+ }
2172
+ /**
2173
+ * Filter of the `filter` rules for `operation` on `variable` (type rules AND the rules of each of
2174
+ * `attributes`), or `undefined` when no rule applies.
2175
+ */
2176
+ filter(variable, node, operation, attributes = []) {
2177
+ return and2(
2178
+ annotations(node, attributes).map(
2179
+ (a) => or(
2180
+ (a?.authorization?.filter ?? []).filter((r) => r.operations.includes(operation)).map((r) => this.rule(variable, node, r))
2181
+ )
2182
+ )
2183
+ );
2184
+ }
2185
+ /**
2186
+ * Predicates of the `validate` rules for `operation` / `when`, one per annotation (type, then each
2187
+ * of `attributes`); each must hold.
2188
+ */
2189
+ validations(variable, node, operation, when, attributes = []) {
2190
+ const out = [];
2191
+ for (const a of annotations(node, attributes)) {
2192
+ const p = or(
2193
+ (a?.authorization?.validate ?? []).filter((r) => r.operations.includes(operation) && r.when.includes(when)).map((r) => this.rule(variable, node, r))
2194
+ );
2195
+ if (p !== void 0) out.push(p);
2196
+ }
2197
+ return out;
2198
+ }
2199
+ /**
2200
+ * `true` when one of `validations` does not hold for the node (`null` counts as not holding), or
2201
+ * `undefined` when there is nothing to check.
2202
+ */
2203
+ failure(validations) {
2204
+ if (!validations.length) return void 0;
2205
+ return or(validations.map((v) => `NOT coalesce(${v}, false)`));
2206
+ }
2207
+ /** {@link failure} of the validations of `operation` / `when`. */
2208
+ fails(variable, node, operation, when, attributes = []) {
2209
+ return this.failure(this.validations(variable, node, operation, when, attributes));
2210
+ }
2211
+ /** `CASE WHEN <failure> THEN 'Forbidden' END` (a failed-check message for mutations). */
2212
+ check(failure) {
2213
+ return failure === void 0 ? void 0 : `CASE WHEN ${failure} THEN ${this.forbiddenMessage()} END`;
2214
+ }
2215
+ rule(variable, node, rule) {
2216
+ const auth = rule.requireAuthentication ? `${this.isAuthenticated()} = true` : void 0;
2217
+ const where = this.ruleWhere(variable, node, this.populate(rule.where));
2218
+ return and2([auth, where]);
2219
+ }
2220
+ /** `{ node, jwt, AND, OR, NOT }`: keys combined with AND. */
2221
+ ruleWhere(variable, node, where) {
2222
+ const parts = [];
2223
+ for (const [key, value] of Object.entries(where)) {
2224
+ if (value === void 0 || value === null) continue;
2225
+ switch (key) {
2226
+ case "node":
2227
+ parts.push(this.where.node(variable, node, value));
2228
+ break;
2229
+ case "jwt":
2230
+ if (!isRecord2(value)) throw new GraphQLError3("Invalid authorization rule: jwt");
2231
+ parts.push(this.jwt(value));
2232
+ break;
2233
+ case "AND":
2234
+ case "OR": {
2235
+ const items = (Array.isArray(value) ? value : [value]).map((w) => {
2236
+ if (!isRecord2(w)) throw new GraphQLError3(`Invalid authorization rule: ${key}`);
2237
+ return this.ruleWhere(variable, node, w);
2238
+ });
2239
+ parts.push(key === "AND" ? and2(items) : or(items));
2240
+ break;
2241
+ }
2242
+ case "NOT": {
2243
+ if (!isRecord2(value)) throw new GraphQLError3("Invalid authorization rule: NOT");
2244
+ const inner = this.ruleWhere(variable, node, value);
2245
+ parts.push(inner === void 0 ? void 0 : `NOT (${inner})`);
2246
+ break;
2247
+ }
2248
+ default:
2249
+ throw new GraphQLError3(`Invalid authorization rule key ${key}`);
2250
+ }
2251
+ }
2252
+ return and2(parts);
2253
+ }
2254
+ /** `jwt: { roles: { includes: "admin" } }`: `($claim IS NOT NULL AND $value IN $claim)`. */
2255
+ jwt(where) {
2256
+ const parts = [];
2257
+ for (const [key, value] of Object.entries(where)) {
2258
+ if (value === void 0) continue;
2259
+ if (key === "AND" || key === "OR") {
2260
+ const items = (Array.isArray(value) ? value : [value]).map((w) => {
2261
+ if (!isRecord2(w)) throw new GraphQLError3(`Invalid JWT filter ${key}`);
2262
+ return this.jwt(w);
2263
+ });
2264
+ parts.push(key === "AND" ? and2(items) : or(items));
2265
+ continue;
2266
+ }
2267
+ if (key === "NOT") {
2268
+ if (!isRecord2(value)) throw new GraphQLError3("Invalid JWT filter NOT");
2269
+ const inner = this.jwt(value);
2270
+ parts.push(inner === void 0 ? void 0 : `NOT (${inner})`);
2271
+ continue;
2272
+ }
2273
+ const { field, operator } = parseJwtWhereKey(key);
2274
+ const claim = this.ctx.param(claimValue(this.auth, field) ?? null);
2275
+ const comparisons = [];
2276
+ if (operator) {
2277
+ comparisons.push(jwtComparison(operator, claim, this.ctx.param(this.unwrap(value))));
2278
+ } else {
2279
+ if (!isRecord2(value)) throw new GraphQLError3(`Invalid JWT filter ${key}`);
2280
+ for (const [op, v] of Object.entries(value)) {
2281
+ if (v === void 0) continue;
2282
+ const legacy = GENERIC_OPERATORS[op];
2283
+ if (!legacy)
2284
+ throw new GraphQLError3(`Invalid operator ${op} in an authorization JWT filter`);
2285
+ comparisons.push(jwtComparison(legacy, claim, this.ctx.param(this.unwrap(v))));
2286
+ }
2287
+ }
2288
+ const cmp = and2(comparisons);
2289
+ parts.push(cmp === void 0 ? void 0 : `(${claim} IS NOT NULL AND ${cmp})`);
2290
+ }
2291
+ return and2(parts);
2292
+ }
2293
+ unwrap(v) {
2294
+ return v instanceof AuthValue ? v.value ?? null : v ?? null;
2295
+ }
2296
+ /**
2297
+ * Copy of a rule `where` with `$jwt.<path>` / `$context.<path>` strings replaced by their values
2298
+ * for this request ({@link AuthValue}); like v7, strings inside lists are left as they are.
2299
+ */
2300
+ populate(value, key) {
2301
+ if (typeof value === "string") return this.reference(value);
2302
+ if (Array.isArray(value)) {
2303
+ return key === "AND" || key === "OR" ? value.map((v) => this.populate(v)) : value;
2304
+ }
2305
+ if (isRecord2(value)) {
2306
+ const out = {};
2307
+ for (const [k, v] of Object.entries(value)) out[k] = this.populate(v, k);
2308
+ return out;
2309
+ }
2310
+ return value;
2311
+ }
2312
+ reference(value) {
2313
+ if (value.startsWith("$jwt")) {
2314
+ const path = value.substring(5);
2315
+ const mapped = this.auth.claims?.get(path) ?? path;
2316
+ return new AuthValue(readPath(this.auth.jwt ?? {}, mapped.split(".")));
2317
+ }
2318
+ if (value.startsWith("$context")) {
2319
+ return new AuthValue(readPath(this.auth.context, value.substring(9).split(".")));
2320
+ }
2321
+ return value;
2322
+ }
2323
+ };
2324
+
2325
+ // src/v7/model.ts
2326
+ import {
2327
+ Kind as Kind3,
2328
+ parse as parse2,
2329
+ valueFromASTUntyped as valueFromASTUntyped2
2330
+ } from "graphql";
2331
+
2332
+ // src/v7/naming.ts
2333
+ import pluralizeLib from "pluralize";
2334
+ function upperFirst(s) {
2335
+ return s.charAt(0).toUpperCase() + s.slice(1);
2336
+ }
2337
+ function camelCase(input) {
2338
+ const s = input.replace(/^_+/, "");
2339
+ const words = s.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_\-.]+/).filter(Boolean);
2340
+ return words.map((w, i) => i === 0 ? w.toLowerCase() : upperFirst(w.toLowerCase())).join("");
2341
+ }
2342
+ function leadingUnderscores(name) {
2343
+ return /^_+/.exec(name)?.[0] ?? "";
2344
+ }
2345
+ function pluralize(word) {
2346
+ return pluralizeLib(word);
2347
+ }
2348
+ function entityPlural(name, pluralOverride) {
2349
+ if (pluralOverride !== void 0)
2350
+ return `${leadingUnderscores(pluralOverride)}${camelCase(pluralOverride)}`;
2351
+ return `${leadingUnderscores(name)}${pluralizeLib(camelCase(name))}`;
2352
+ }
2353
+
2354
+ // src/v7/model.ts
2355
+ var SUPPORTED_SCALARS = [
2356
+ "ID",
2357
+ "String",
2358
+ "Int",
2359
+ "Float",
2360
+ "Boolean",
2361
+ "BigInt",
2362
+ "Date",
2363
+ "DateTime"
2364
+ ];
2365
+ var UNSUPPORTED_SCALARS = /* @__PURE__ */ new Set([
2366
+ "LocalDateTime",
2367
+ "Time",
2368
+ "LocalTime",
2369
+ "Duration",
2370
+ "Point",
2371
+ "CartesianPoint"
2372
+ ]);
2373
+ var AUTH_OPERATIONS = [
2374
+ "READ",
2375
+ "AGGREGATE",
2376
+ "CREATE",
2377
+ "UPDATE",
2378
+ "DELETE",
2379
+ "CREATE_RELATIONSHIP",
2380
+ "DELETE_RELATIONSHIP",
2381
+ "SUBSCRIBE"
2382
+ ];
2383
+ var FILTER_OPERATIONS = [
2384
+ "READ",
2385
+ "AGGREGATE",
2386
+ "UPDATE",
2387
+ "DELETE",
2388
+ "CREATE_RELATIONSHIP",
2389
+ "DELETE_RELATIONSHIP"
2390
+ ];
2391
+ var VALIDATE_OPERATIONS = [
2392
+ "READ",
2393
+ "AGGREGATE",
2394
+ "CREATE",
2395
+ "UPDATE",
2396
+ "DELETE",
2397
+ "CREATE_RELATIONSHIP",
2398
+ "DELETE_RELATIONSHIP"
2399
+ ];
2400
+ var UnsupportedTypeDefsError = class extends Error {
2401
+ name = "UnsupportedTypeDefsError";
2402
+ };
2403
+ function directive2(dirs, name) {
2404
+ return dirs?.find((d) => d.name.value === name);
2405
+ }
2406
+ function arg2(d, name) {
2407
+ return d?.arguments?.find((a) => a.name.value === name)?.value;
2408
+ }
2409
+ function stringArg2(d, name) {
2410
+ const v = arg2(d, name);
2411
+ return v && (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) ? v.value : void 0;
2412
+ }
2413
+ function listArg(d, name) {
2414
+ const v = arg2(d, name);
2415
+ if (!v) return void 0;
2416
+ if (v.kind === Kind3.LIST) {
2417
+ return v.values.flatMap(
2418
+ (x) => x.kind === Kind3.STRING || x.kind === Kind3.ENUM ? [x.value] : []
2419
+ );
2420
+ }
2421
+ if (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) return [v.value];
2422
+ return void 0;
2423
+ }
2424
+ function typeRef(t) {
2425
+ let cur = t;
2426
+ let required = false;
2427
+ if (cur.kind === Kind3.NON_NULL_TYPE) {
2428
+ required = true;
2429
+ cur = cur.type;
2430
+ }
2431
+ if (cur.kind === Kind3.LIST_TYPE) {
2432
+ let inner = cur.type;
2433
+ let elementRequired = false;
2434
+ if (inner.kind === Kind3.NON_NULL_TYPE) {
2435
+ elementRequired = true;
2436
+ inner = inner.type;
2437
+ }
2438
+ if (inner.kind !== Kind3.NAMED_TYPE)
2439
+ throw new UnsupportedTypeDefsError("Nested lists are not supported.");
2440
+ return { name: inner.name.value, list: true, required, elementRequired };
2441
+ }
2442
+ return {
2443
+ name: cur.name.value,
2444
+ list: false,
2445
+ required,
2446
+ elementRequired: false
2447
+ };
2448
+ }
2449
+ var ACCEPTED_FIELD_DIRECTIVES = /* @__PURE__ */ new Set([
2450
+ "authentication",
2451
+ "authorization",
2452
+ "id",
2453
+ "default",
2454
+ "timestamp",
2455
+ "cypher",
2456
+ "relationship",
2457
+ "alias",
2458
+ "deprecated",
2459
+ "coalesce",
2460
+ "unique"
2461
+ ]);
2462
+ var ACCEPTED_TYPE_DIRECTIVES = /* @__PURE__ */ new Set([
2463
+ "node",
2464
+ "fulltext",
2465
+ "plural",
2466
+ "authentication",
2467
+ "authorization",
2468
+ "relationshipProperties",
2469
+ "jwt"
2470
+ ]);
2471
+ function deprecationReason(dirs) {
2472
+ const d = directive2(dirs, "deprecated");
2473
+ if (!d) return void 0;
2474
+ return stringArg2(d, "reason") ?? "No longer supported";
2475
+ }
2476
+ function readAttribute(owner, f, enums) {
2477
+ for (const d of f.directives ?? []) {
2478
+ if (!ACCEPTED_FIELD_DIRECTIVES.has(d.name.value)) {
2479
+ throw new UnsupportedTypeDefsError(
2480
+ `${owner}.${f.name.value}: @${d.name.value} is not supported by @cyphra/graphql yet.`
2481
+ );
2482
+ }
2483
+ }
2484
+ const cypher = readCypher(`${owner}.${f.name.value}`, directive2(f.directives, "cypher"));
2485
+ if (f.arguments?.length && !cypher) {
2486
+ throw new UnsupportedTypeDefsError(
2487
+ `${owner}.${f.name.value}: field arguments are only supported on @cypher fields.`
2488
+ );
2489
+ }
2490
+ const type = typeRef(f.type);
2491
+ const isEnum = enums.has(type.name);
2492
+ if (!isEnum && !SUPPORTED_SCALARS.includes(type.name)) {
2493
+ if (UNSUPPORTED_SCALARS.has(type.name)) {
2494
+ throw new UnsupportedTypeDefsError(
2495
+ `${owner}.${f.name.value}: ${type.name} is not supported by @cyphra/graphql yet.`
2496
+ );
2497
+ }
2498
+ throw new UnsupportedTypeDefsError(
2499
+ `${owner}.${f.name.value}: type ${type.name} is not a supported scalar or enum (fields returning objects need @relationship).`
2500
+ );
2501
+ }
2502
+ const dirs = f.directives;
2503
+ const def = directive2(dirs, "default");
2504
+ const defaultAst = arg2(def, "value");
2505
+ const ts = directive2(dirs, "timestamp");
2506
+ const alias = directive2(dirs, "alias");
2507
+ return {
2508
+ name: f.name.value,
2509
+ property: stringArg2(alias, "property") ?? f.name.value,
2510
+ type,
2511
+ kind: isEnum ? "enum" : "scalar",
2512
+ description: f.description?.value,
2513
+ id: !!directive2(dirs, "id"),
2514
+ defaultAst,
2515
+ defaultValue: defaultAst ? valueFromASTUntyped2(defaultAst) : void 0,
2516
+ timestamp: ts ? listArg(ts, "operations") ?? ["CREATE", "UPDATE"] : void 0,
2517
+ cypher,
2518
+ args: readArguments(`${owner}.${f.name.value}`, f, enums),
2519
+ deprecated: deprecationReason(dirs),
2520
+ auth: readAuthAnnotations(`${owner}.${f.name.value}`, dirs)
2521
+ };
2522
+ }
2523
+ function readCypher(where, d) {
2524
+ if (!d) return void 0;
2525
+ for (const a of d.arguments ?? []) {
2526
+ if (!["statement", "columnName"].includes(a.name.value)) {
2527
+ throw new UnsupportedTypeDefsError(`${where}: @cypher(${a.name.value}) is not supported.`);
2528
+ }
2529
+ }
2530
+ const statement = stringArg2(d, "statement");
2531
+ const columnName = stringArg2(d, "columnName");
2532
+ if (!statement || !columnName) {
2533
+ throw new UnsupportedTypeDefsError(`${where}: @cypher needs a statement and a columnName.`);
2534
+ }
2535
+ return { statement, columnName };
2536
+ }
2537
+ function readArguments(where, f, enums) {
2538
+ return (f.arguments ?? []).map((a) => {
2539
+ if (a.directives?.length) {
2540
+ throw new UnsupportedTypeDefsError(
2541
+ `${where}(${a.name.value}): directives on arguments are not supported.`
2542
+ );
2543
+ }
2544
+ const type = typeRef(a.type);
2545
+ const isEnum = enums.has(type.name);
2546
+ if (!isEnum && !SUPPORTED_SCALARS.includes(type.name)) {
2547
+ throw new UnsupportedTypeDefsError(
2548
+ `${where}(${a.name.value}): arguments of type ${type.name} are not supported by @cyphra/graphql yet (scalars and enums only).`
2549
+ );
2550
+ }
2551
+ return {
2552
+ name: a.name.value,
2553
+ type,
2554
+ kind: isEnum ? "enum" : "scalar",
2555
+ description: a.description?.value,
2556
+ defaultAst: a.defaultValue
2557
+ };
2558
+ });
2559
+ }
2560
+ function isRecord3(v) {
2561
+ return typeof v === "object" && v !== null && !Array.isArray(v);
2562
+ }
2563
+ function operationList(where, value, allowed) {
2564
+ if (value === void 0 || value === null) return void 0;
2565
+ const list2 = Array.isArray(value) ? value : [value];
2566
+ return list2.map((op) => {
2567
+ if (typeof op !== "string" || !allowed.includes(op)) {
2568
+ throw new UnsupportedTypeDefsError(`${where}: invalid operation ${String(op)}.`);
2569
+ }
2570
+ return op;
2571
+ });
2572
+ }
2573
+ var RULE_WHERE_KEYS = /* @__PURE__ */ new Set(["node", "jwt", "AND", "OR", "NOT"]);
2574
+ function checkRuleWhere(where, value) {
2575
+ if (!isRecord3(value))
2576
+ throw new UnsupportedTypeDefsError(`${where}: \`where\` must be an object.`);
2577
+ for (const [k, v] of Object.entries(value)) {
2578
+ if (!RULE_WHERE_KEYS.has(k)) {
2579
+ throw new UnsupportedTypeDefsError(`${where}: unknown key ${k} in \`where\`.`);
2580
+ }
2581
+ if (k === "AND" || k === "OR") {
2582
+ if (!Array.isArray(v)) throw new UnsupportedTypeDefsError(`${where}: ${k} must be a list.`);
2583
+ v.forEach((x) => checkRuleWhere(where, x));
2584
+ } else if (k === "NOT") {
2585
+ checkRuleWhere(where, v);
2586
+ } else if (!isRecord3(v)) {
2587
+ throw new UnsupportedTypeDefsError(`${where}: \`${k}\` must be an object.`);
2588
+ }
2589
+ }
2590
+ return value;
2591
+ }
2592
+ function readRules(where, value, allowed) {
2593
+ if (value === void 0 || value === null) return [];
2594
+ const list2 = Array.isArray(value) ? value : [value];
2595
+ return list2.map((rule, i) => {
2596
+ const at = `${where}[${i}]`;
2597
+ if (!isRecord3(rule)) throw new UnsupportedTypeDefsError(`${at}: a rule must be an object.`);
2598
+ for (const k of Object.keys(rule)) {
2599
+ if (!["operations", "requireAuthentication", "where", "when"].includes(k)) {
2600
+ throw new UnsupportedTypeDefsError(`${at}: unknown rule argument ${k}.`);
2601
+ }
2602
+ }
2603
+ if (rule.requireAuthentication !== void 0 && typeof rule.requireAuthentication !== "boolean") {
2604
+ throw new UnsupportedTypeDefsError(`${at}: requireAuthentication must be a Boolean.`);
2605
+ }
2606
+ return {
2607
+ operations: operationList(at, rule.operations, allowed) ?? [...allowed],
2608
+ requireAuthentication: rule.requireAuthentication !== false,
2609
+ where: checkRuleWhere(at, rule.where),
2610
+ raw: rule
2611
+ };
2612
+ });
2613
+ }
2614
+ function readAuthentication(where, d) {
2615
+ if (!d) return void 0;
2616
+ for (const a of d.arguments ?? []) {
2617
+ if (!["operations", "jwt"].includes(a.name.value)) {
2618
+ throw new UnsupportedTypeDefsError(
2619
+ `${where}: @authentication(${a.name.value}) is not supported.`
2620
+ );
2621
+ }
2622
+ }
2623
+ const opsArg = arg2(d, "operations");
2624
+ const jwtArg = arg2(d, "jwt");
2625
+ const jwt = jwtArg ? valueFromASTUntyped2(jwtArg) : void 0;
2626
+ if (jwt !== void 0 && jwt !== null && !isRecord3(jwt)) {
2627
+ throw new UnsupportedTypeDefsError(`${where}: @authentication(jwt) must be an object.`);
2628
+ }
2629
+ const operations = operationList(
2630
+ `${where} @authentication`,
2631
+ opsArg ? valueFromASTUntyped2(opsArg) : void 0,
2632
+ AUTH_OPERATIONS
2633
+ ) ?? AUTH_OPERATIONS;
2634
+ return { operations: new Set(operations), jwt: jwt ?? void 0 };
2635
+ }
2636
+ function readAuthorization(where, d) {
2637
+ if (!d) return void 0;
2638
+ for (const a of d.arguments ?? []) {
2639
+ if (!["filter", "validate"].includes(a.name.value)) {
2640
+ throw new UnsupportedTypeDefsError(
2641
+ `${where}: @authorization(${a.name.value}) is not supported.`
2642
+ );
2643
+ }
2644
+ }
2645
+ const filterArg = arg2(d, "filter");
2646
+ const validateArg = arg2(d, "validate");
2647
+ const filter = readRules(
2648
+ `${where} @authorization(filter)`,
2649
+ filterArg ? valueFromASTUntyped2(filterArg) : void 0,
2650
+ FILTER_OPERATIONS
2651
+ ).map((r) => {
2652
+ if (r.raw.when !== void 0) {
2653
+ throw new UnsupportedTypeDefsError(
2654
+ `${where} @authorization(filter): \`when\` only applies to validate rules.`
2655
+ );
2656
+ }
2657
+ return {
2658
+ operations: r.operations,
2659
+ requireAuthentication: r.requireAuthentication,
2660
+ where: r.where
2661
+ };
2662
+ });
2663
+ const validate = readRules(
2664
+ `${where} @authorization(validate)`,
2665
+ validateArg ? valueFromASTUntyped2(validateArg) : void 0,
2666
+ VALIDATE_OPERATIONS
2667
+ ).map((r) => {
2668
+ const when = r.raw.when === void 0 || r.raw.when === null ? ["BEFORE", "AFTER"] : r.raw.when;
2669
+ const list2 = Array.isArray(when) ? when : [when];
2670
+ for (const w of list2) {
2671
+ if (w !== "BEFORE" && w !== "AFTER") {
2672
+ throw new UnsupportedTypeDefsError(
2673
+ `${where} @authorization(validate): invalid when ${String(w)}.`
2674
+ );
2675
+ }
2676
+ }
2677
+ return {
2678
+ operations: r.operations,
2679
+ requireAuthentication: r.requireAuthentication,
2680
+ where: r.where,
2681
+ when: list2
2682
+ };
2683
+ });
2684
+ return { filter, validate };
2685
+ }
2686
+ function readAuthAnnotations(where, dirs) {
2687
+ const authentication = readAuthentication(where, directive2(dirs, "authentication"));
2688
+ const authorization = readAuthorization(where, directive2(dirs, "authorization"));
2689
+ return authentication || authorization ? { authentication, authorization } : void 0;
2690
+ }
2691
+ function readJwtClaims(o) {
2692
+ const claims = /* @__PURE__ */ new Map();
2693
+ for (const f of o.fields ?? []) {
2694
+ for (const d of f.directives ?? []) {
2695
+ if (d.name.value !== "jwtClaim") {
2696
+ throw new UnsupportedTypeDefsError(
2697
+ `${o.name.value}.${f.name.value}: @${d.name.value} is not supported on the @jwt type.`
2698
+ );
2699
+ }
2700
+ }
2701
+ const path = stringArg2(directive2(f.directives, "jwtClaim"), "path");
2702
+ if (path) claims.set(f.name.value, path);
2703
+ }
2704
+ return claims;
2705
+ }
2706
+ var CYPHER_FIELD_DIRECTIVES = /* @__PURE__ */ new Set(["cypher", "deprecated"]);
2707
+ function readCypherNodeField(owner, f, enums) {
2708
+ const where = `${owner}.${f.name.value}`;
2709
+ for (const d of f.directives ?? []) {
2710
+ if (!CYPHER_FIELD_DIRECTIVES.has(d.name.value)) {
2711
+ throw new UnsupportedTypeDefsError(
2712
+ `${where}: @${d.name.value} on a @cypher field returning nodes is not supported by @cyphra/graphql yet.`
2713
+ );
2714
+ }
2715
+ }
2716
+ const type = typeRef(f.type);
2717
+ return {
2718
+ name: f.name.value,
2719
+ target: type.name,
2720
+ type,
2721
+ cypher: readCypher(where, directive2(f.directives, "cypher")),
2722
+ args: readArguments(where, f, enums),
2723
+ description: f.description?.value,
2724
+ deprecated: deprecationReason(f.directives)
2725
+ };
2726
+ }
2727
+ function readRootType(o, enums, nodes) {
2728
+ if (!o) return { fields: [] };
2729
+ const type = o.name.value;
2730
+ let authentication;
2731
+ for (const d of o.directives ?? []) {
2732
+ if (d.name.value !== "authentication") {
2733
+ throw new UnsupportedTypeDefsError(
2734
+ `type ${type}: @${d.name.value} is not supported by @cyphra/graphql yet.`
2735
+ );
2736
+ }
2737
+ authentication = readAuthentication(`type ${type}`, d);
2738
+ }
2739
+ const fields = (o.fields ?? []).map((f) => {
2740
+ const where = `${type}.${f.name.value}`;
2741
+ for (const d of f.directives ?? []) {
2742
+ if (!["cypher", "deprecated", "authentication"].includes(d.name.value)) {
2743
+ throw new UnsupportedTypeDefsError(
2744
+ `${where}: @${d.name.value} is not supported on ${type} fields by @cyphra/graphql yet.`
2745
+ );
2746
+ }
2747
+ }
2748
+ const cypher = readCypher(where, directive2(f.directives, "cypher"));
2749
+ if (!cypher) {
2750
+ throw new UnsupportedTypeDefsError(
2751
+ `${where}: custom ${type} fields need @cypher (custom resolvers are not supported by @cyphra/graphql).`
2752
+ );
2753
+ }
2754
+ const t = typeRef(f.type);
2755
+ const kind = nodes.has(t.name) ? "node" : enums.has(t.name) ? "enum" : "scalar";
2756
+ if (kind === "scalar" && !SUPPORTED_SCALARS.includes(t.name)) {
2757
+ throw new UnsupportedTypeDefsError(
2758
+ `${where}: type ${t.name} is not supported by @cyphra/graphql yet (@node types, scalars and enums only).`
2759
+ );
2760
+ }
2761
+ return {
2762
+ name: f.name.value,
2763
+ type: t,
2764
+ kind,
2765
+ cypher,
2766
+ args: readArguments(where, f, enums),
2767
+ description: f.description?.value,
2768
+ deprecated: deprecationReason(f.directives),
2769
+ authentication: readAuthentication(where, directive2(f.directives, "authentication"))
2770
+ };
2771
+ });
2772
+ return { fields, authentication };
2773
+ }
2774
+ function readFulltext(owner, d, attributes) {
2775
+ if (!d) return [];
2776
+ const where = `type ${owner} @fulltext`;
2777
+ const value = arg2(d, "indexes");
2778
+ const indexes = value ? valueFromASTUntyped2(value) : void 0;
2779
+ if (!Array.isArray(indexes))
2780
+ throw new UnsupportedTypeDefsError(`${where}: indexes must be a list.`);
2781
+ return indexes.map((ix, i) => {
2782
+ if (!isRecord3(ix))
2783
+ throw new UnsupportedTypeDefsError(`${where}: indexes[${i}] must be an object.`);
2784
+ for (const k of Object.keys(ix)) {
2785
+ if (!["indexName", "queryName", "fields"].includes(k)) {
2786
+ throw new UnsupportedTypeDefsError(`${where}: unknown index argument ${k}.`);
2787
+ }
2788
+ }
2789
+ const { indexName, queryName, fields } = ix;
2790
+ if (typeof indexName !== "string" || typeof queryName !== "string" || !Array.isArray(fields)) {
2791
+ throw new UnsupportedTypeDefsError(
2792
+ `${where}: indexes[${i}] needs indexName, queryName and fields.`
2793
+ );
2794
+ }
2795
+ for (const field of fields) {
2796
+ const a = attributes.find((x) => x.name === field);
2797
+ if (!a || a.cypher || a.type.name !== "String" && a.type.name !== "ID") {
2798
+ throw new UnsupportedTypeDefsError(
2799
+ `${where}: field ${String(field)} must be a String or ID field of ${owner}.`
2800
+ );
2801
+ }
2802
+ }
2803
+ return { indexName, queryName, fields };
2804
+ });
2805
+ }
2806
+ function readTypeDefs(typeDefs) {
2807
+ const doc = parse2(typeDefs);
2808
+ const objects = [];
2809
+ const enums = /* @__PURE__ */ new Map();
2810
+ let schemaAuthentication;
2811
+ for (const def of doc.definitions) {
2812
+ switch (def.kind) {
2813
+ case Kind3.SCHEMA_EXTENSION:
2814
+ case Kind3.SCHEMA_DEFINITION: {
2815
+ if (def.operationTypes?.length) {
2816
+ throw new UnsupportedTypeDefsError(
2817
+ "schema: custom root operation types are not supported by @cyphra/graphql yet."
2818
+ );
2819
+ }
2820
+ for (const d of def.directives ?? []) {
2821
+ if (d.name.value !== "authentication") {
2822
+ throw new UnsupportedTypeDefsError(
2823
+ `schema: @${d.name.value} is not supported by @cyphra/graphql yet.`
2824
+ );
2825
+ }
2826
+ if (schemaAuthentication) {
2827
+ throw new UnsupportedTypeDefsError("schema: @authentication is set more than once.");
2828
+ }
2829
+ schemaAuthentication = readAuthentication("schema", d);
2830
+ }
2831
+ break;
2832
+ }
2833
+ case Kind3.OBJECT_TYPE_DEFINITION:
2834
+ objects.push(def);
2835
+ break;
2836
+ case Kind3.ENUM_TYPE_DEFINITION:
2837
+ enums.set(def.name.value, {
2838
+ name: def.name.value,
2839
+ description: def.description?.value,
2840
+ values: (def.values ?? []).map((v) => ({
2841
+ name: v.name.value,
2842
+ description: v.description?.value,
2843
+ deprecated: deprecationReason(v.directives)
2844
+ }))
2845
+ });
2846
+ break;
2847
+ case Kind3.SCALAR_TYPE_DEFINITION:
2848
+ if (!SUPPORTED_SCALARS.includes(def.name.value)) {
2849
+ throw new UnsupportedTypeDefsError(
2850
+ `scalar ${def.name.value}: custom scalars are not supported by @cyphra/graphql yet.`
2851
+ );
2852
+ }
2853
+ break;
2854
+ case Kind3.DIRECTIVE_DEFINITION:
2855
+ break;
2856
+ default:
2857
+ throw new UnsupportedTypeDefsError(
2858
+ `${def.kind}${"name" in def && def.name ? ` ${def.name.value}` : ""}: not supported by @cyphra/graphql yet (only object types, enums and relationship properties).`
2859
+ );
2860
+ }
2861
+ }
2862
+ const enumNames = new Set(enums.keys());
2863
+ const properties = /* @__PURE__ */ new Map();
2864
+ const nodeDefs = [];
2865
+ const rootDefs = /* @__PURE__ */ new Map();
2866
+ let jwtClaims;
2867
+ for (const o of objects) {
2868
+ const name = o.name.value;
2869
+ if (name === "Subscription") {
2870
+ throw new UnsupportedTypeDefsError(
2871
+ "type Subscription: subscriptions are not supported by @cyphra/graphql yet."
2872
+ );
2873
+ }
2874
+ if (name === "Query" || name === "Mutation") {
2875
+ if (rootDefs.has(name)) {
2876
+ throw new UnsupportedTypeDefsError(`type ${name}: defined more than once.`);
2877
+ }
2878
+ rootDefs.set(name, o);
2879
+ continue;
2880
+ }
2881
+ if (o.interfaces?.length) {
2882
+ throw new UnsupportedTypeDefsError(
2883
+ `type ${name}: interfaces are not supported by @cyphra/graphql yet.`
2884
+ );
2885
+ }
2886
+ for (const d of o.directives ?? []) {
2887
+ if (!ACCEPTED_TYPE_DIRECTIVES.has(d.name.value)) {
2888
+ throw new UnsupportedTypeDefsError(
2889
+ `type ${name}: @${d.name.value} is not supported by @cyphra/graphql yet.`
2890
+ );
2891
+ }
2892
+ }
2893
+ if (directive2(o.directives, "jwt")) {
2894
+ if (jwtClaims)
2895
+ throw new UnsupportedTypeDefsError(`type ${name}: only one @jwt type is allowed.`);
2896
+ jwtClaims = readJwtClaims(o);
2897
+ continue;
2898
+ }
2899
+ if (directive2(o.directives, "relationshipProperties")) {
2900
+ properties.set(name, {
2901
+ name,
2902
+ attributes: (o.fields ?? []).map((f) => {
2903
+ const a = readAttribute(name, f, enumNames);
2904
+ if (a.auth) {
2905
+ throw new UnsupportedTypeDefsError(
2906
+ `${name}.${f.name.value}: @authentication / @authorization on relationship properties are not supported.`
2907
+ );
2908
+ }
2909
+ return a;
2910
+ })
2911
+ });
2912
+ continue;
2913
+ }
2914
+ if (!directive2(o.directives, "node")) {
2915
+ throw new UnsupportedTypeDefsError(
2916
+ `type ${name}: object types without @node are not supported by @cyphra/graphql yet.`
2917
+ );
2918
+ }
2919
+ nodeDefs.push(o);
2920
+ }
2921
+ const nodeNames = new Set(nodeDefs.map((o) => o.name.value));
2922
+ const nodes = nodeDefs.map((o) => {
2923
+ const name = o.name.value;
2924
+ const attributes = [];
2925
+ const relationships = [];
2926
+ const cypherNodes = [];
2927
+ for (const f of o.fields ?? []) {
2928
+ const rel = directive2(f.directives, "relationship");
2929
+ const cypher = directive2(f.directives, "cypher");
2930
+ if (cypher && !rel && nodeNames.has(typeRef(f.type).name)) {
2931
+ cypherNodes.push(readCypherNodeField(name, f, enumNames));
2932
+ continue;
2933
+ }
2934
+ if (!rel) {
2935
+ attributes.push(readAttribute(name, f, enumNames));
2936
+ continue;
2937
+ }
2938
+ for (const d of f.directives ?? []) {
2939
+ if (d.name.value === "authentication" || d.name.value === "authorization") {
2940
+ throw new UnsupportedTypeDefsError(
2941
+ `${name}.${f.name.value}: @${d.name.value} on a relationship field is not supported (put the rules on the related type).`
2942
+ );
2943
+ }
2944
+ }
2945
+ const t = typeRef(f.type);
2946
+ if (!nodeNames.has(t.name)) {
2947
+ throw new UnsupportedTypeDefsError(
2948
+ `${name}.${f.name.value}: relationships to ${t.name} are not supported by @cyphra/graphql yet (target must be a @node type).`
2949
+ );
2950
+ }
2951
+ for (const a of rel.arguments ?? []) {
2952
+ if (!["type", "direction", "properties"].includes(a.name.value)) {
2953
+ throw new UnsupportedTypeDefsError(
2954
+ `${name}.${f.name.value}: @relationship(${a.name.value}) is not supported by @cyphra/graphql yet.`
2955
+ );
2956
+ }
2957
+ }
2958
+ const props = stringArg2(rel, "properties");
2959
+ if (props && !properties.has(props)) {
2960
+ throw new UnsupportedTypeDefsError(
2961
+ `${name}.${f.name.value}: properties type ${props} must be a @relationshipProperties type.`
2962
+ );
2963
+ }
2964
+ relationships.push({
2965
+ name: f.name.value,
2966
+ source: name,
2967
+ target: t.name,
2968
+ type: stringArg2(rel, "type") ?? "",
2969
+ direction: stringArg2(rel, "direction") === "IN" ? "IN" : "OUT",
2970
+ properties: props,
2971
+ list: t.list,
2972
+ required: t.required,
2973
+ elementRequired: t.elementRequired,
2974
+ description: f.description?.value,
2975
+ deprecated: deprecationReason(f.directives)
2976
+ });
2977
+ }
2978
+ const nodeDir = directive2(o.directives, "node");
2979
+ const labels2 = listArg(nodeDir, "labels") ?? [name];
2980
+ const pluralDir = directive2(o.directives, "plural");
2981
+ const plural = entityPlural(name, stringArg2(pluralDir, "value"));
2982
+ return {
2983
+ name,
2984
+ description: o.description?.value,
2985
+ labels: labels2,
2986
+ plural,
2987
+ pascalPlural: upperFirst(plural),
2988
+ attributes,
2989
+ relationships,
2990
+ cypherNodes,
2991
+ fulltext: readFulltext(name, directive2(o.directives, "fulltext"), attributes),
2992
+ auth: readAuthAnnotations(`type ${name}`, o.directives) ?? {}
2993
+ };
2994
+ });
2995
+ const byName0 = new Map(nodes.map((n) => [n.name, n]));
2996
+ const root = (type) => readRootType(rootDefs.get(type), enumNames, nodeNames);
2997
+ const query = root("Query");
2998
+ const mutation = root("Mutation");
2999
+ const generated = /* @__PURE__ */ new Set();
3000
+ for (const n of byName0.values()) {
3001
+ generated.add(n.plural);
3002
+ generated.add(`${n.plural}Connection`);
3003
+ for (const ft of n.fulltext) {
3004
+ if (generated.has(ft.queryName)) {
3005
+ throw new UnsupportedTypeDefsError(
3006
+ `type ${n.name} @fulltext: queryName ${ft.queryName} is already a Query field.`
3007
+ );
3008
+ }
3009
+ generated.add(ft.queryName);
3010
+ }
3011
+ }
3012
+ for (const f of query.fields) {
3013
+ if (generated.has(f.name)) {
3014
+ throw new UnsupportedTypeDefsError(
3015
+ `Query.${f.name}: conflicts with a generated Query field.`
3016
+ );
3017
+ }
3018
+ }
3019
+ const generatedMutations = new Set(
3020
+ [...byName0.values()].flatMap(
3021
+ (n) => ["create", "update", "delete"].map((k) => `${k}${n.pascalPlural}`)
3022
+ )
3023
+ );
3024
+ for (const f of mutation.fields) {
3025
+ if (generatedMutations.has(f.name)) {
3026
+ throw new UnsupportedTypeDefsError(
3027
+ `Mutation.${f.name}: conflicts with a generated Mutation field.`
3028
+ );
3029
+ }
3030
+ }
3031
+ const byName = new Map(nodes.map((n) => [n.name, n]));
3032
+ return {
3033
+ nodes,
3034
+ authentication: schemaAuthentication,
3035
+ jwtClaims: jwtClaims ?? /* @__PURE__ */ new Map(),
3036
+ properties,
3037
+ enums,
3038
+ query,
3039
+ mutation,
3040
+ node(name) {
3041
+ const n = byName.get(name);
3042
+ if (!n) throw new Error(`Unknown node type ${name}`);
3043
+ return n;
3044
+ }
3045
+ };
3046
+ }
3047
+
1894
3048
  // src/v7/cypher/select.ts
3049
+ var FORBIDDEN_KEY = "cyphra:forbidden";
3050
+ var FORBIDDEN_MARKER = `{ ${"`"}${FORBIDDEN_KEY}${"`"}: true }`;
3051
+ function containsForbidden(raw) {
3052
+ if (Array.isArray(raw)) return raw.some(containsForbidden);
3053
+ if (typeof raw !== "object" || raw === null) return false;
3054
+ const proto = Object.getPrototypeOf(raw);
3055
+ if (proto !== Object.prototype && proto !== null) return false;
3056
+ if (Object.prototype.hasOwnProperty.call(raw, FORBIDDEN_KEY)) return true;
3057
+ return Object.values(raw).some(containsForbidden);
3058
+ }
3059
+ function and3(parts) {
3060
+ const ps = parts.filter((p) => p !== void 0);
3061
+ if (ps.length === 0) return void 0;
3062
+ if (ps.length === 1) return ps[0];
3063
+ return ps.map((p) => `(${p})`).join(" AND ");
3064
+ }
3065
+ function rowGate(failure, expr, marker) {
3066
+ return failure === void 0 ? expr : `CASE WHEN ${failure} THEN ${marker} ELSE ${expr} END`;
3067
+ }
3068
+ function gate(match, predicate, failure, expr, marker) {
3069
+ if (failure === void 0) return expr;
3070
+ return `CASE WHEN EXISTS { MATCH ${match} WHERE ${and3([predicate, failure])} } THEN ${marker} ELSE ${expr} END`;
3071
+ }
3072
+ function sortScope() {
3073
+ return { clauses: [], vars: /* @__PURE__ */ new Map() };
3074
+ }
1895
3075
  var CURSOR_PREFIX = "arrayconnection:";
1896
3076
  function offsetToCursor(offset) {
1897
3077
  return Buffer.from(`${CURSOR_PREFIX}${offset}`, "utf8").toString("base64");
@@ -1950,12 +3130,15 @@ function attributeDecoder(a) {
1950
3130
  }
1951
3131
  return (v) => v ?? null;
1952
3132
  }
3133
+ function toFloat(v) {
3134
+ return isInt(v) ? v.toNumber() : Number(v);
3135
+ }
1953
3136
  function toNumber(v) {
1954
3137
  return isInt(v) ? v.toNumber() : Number(v);
1955
3138
  }
1956
3139
  function intParam(ctx, value) {
1957
3140
  if (typeof value !== "number") return void 0;
1958
- return ctx.param(neo4j2.int(Math.max(0, Math.trunc(value))));
3141
+ return ctx.param(neo4j3.int(Math.max(0, Math.trunc(value))));
1959
3142
  }
1960
3143
  function paging(ctx, offset, limit) {
1961
3144
  const parts = [];
@@ -1965,9 +3148,10 @@ function paging(ctx, offset, limit) {
1965
3148
  if (l) parts.push(`LIMIT ${l}`);
1966
3149
  return parts.join(" ");
1967
3150
  }
1968
- function withClause(vars, order, page) {
3151
+ function withClause(vars, order, page, sort) {
1969
3152
  if (!order && !page) return "";
1970
- return ["WITH", vars, order, page].filter(Boolean).join(" ");
3153
+ const all = [vars, ...sort ? sort.vars.values() : []].join(", ");
3154
+ return ["WITH", all, order, page].filter(Boolean).join(" ");
1971
3155
  }
1972
3156
  var AGGREGATE_FUNCTIONS = {
1973
3157
  min: "min",
@@ -1989,62 +3173,153 @@ function mapDecoder(decoders) {
1989
3173
  };
1990
3174
  }
1991
3175
  var SelectionCompiler = class {
1992
- constructor(model, info) {
3176
+ constructor(model, info, auth) {
1993
3177
  this.model = model;
1994
3178
  this.info = info;
1995
- this.where = new WhereCompiler(model, this.ctx, (n) => this.assertReadable(n));
3179
+ this.auth = auth;
3180
+ this.where = new WhereCompiler(model, this.ctx);
3181
+ this.rules = new AuthRules(model, this.ctx, auth);
3182
+ this.ctx.jwt = auth.jwt ?? {};
1996
3183
  }
1997
3184
  model;
1998
3185
  info;
3186
+ auth;
1999
3187
  ctx = new CypherContext();
2000
3188
  where;
2001
- assertReadable(node) {
2002
- if (readNeedsAuth(node)) {
2003
- throw notImplemented(
2004
- `reading ${node.name}, which has @authentication / @authorization rules`,
2005
- FOLLOW_UP.authorization
2006
- );
3189
+ rules;
3190
+ /**
3191
+ * `COLLECT { <body> RETURN ret }` / `COUNT { <body> }` / `EXISTS { <body> }` as an expression or,
3192
+ * when the subquery contains a `@cypher` statement, hoisted into `scope` as
3193
+ * `CALL (*) { <body> RETURN collect(ret) | count(*) AS v }` (the variable is the value).
3194
+ */
3195
+ subquery(scope, kind, body, ret) {
3196
+ const text = body.filter(Boolean).join(" ");
3197
+ if (!hasStatement(text, ret)) {
3198
+ if (kind === "collect") return `COLLECT { ${text} RETURN ${ret} }`;
3199
+ if (kind === "count") return `COUNT { ${text}${ret ? ` RETURN ${ret}` : ""} }`;
3200
+ return `EXISTS { ${text} }`;
2007
3201
  }
3202
+ const v = this.ctx.variable("sub");
3203
+ const agg = kind === "collect" ? `collect(${ret})` : kind === "count" ? "count(*)" : "count(*) > 0";
3204
+ scope.push(["CALL (*) {", text, `RETURN ${agg} AS ${v}`, "}"].join("\n"));
3205
+ return v;
3206
+ }
3207
+ /** {@link gate} with the existence check hoisted when it contains a statement. */
3208
+ gate(scope, match, predicate, failure, expr, marker) {
3209
+ if (failure === void 0) return expr;
3210
+ if (!hasStatement(predicate, failure)) return gate(match, predicate, failure, expr, marker);
3211
+ const denied = this.subquery(scope, "exists", [
3212
+ `MATCH ${match} WHERE ${and3([predicate, failure])}`
3213
+ ]);
3214
+ return `CASE WHEN ${denied} THEN ${marker} ELSE ${expr} END`;
3215
+ }
3216
+ /** {@link rowGate} with the check hoisted when it contains a statement. */
3217
+ rowGate(scope, failure, expr, marker) {
3218
+ if (failure === void 0 || !hasStatement(failure)) return rowGate(failure, expr, marker);
3219
+ const denied = this.subquery(scope, "exists", [`WITH * WHERE ${failure}`]);
3220
+ return `CASE WHEN ${denied} THEN ${marker} ELSE ${expr} END`;
3221
+ }
3222
+ /** `@authentication` for `operation` on the type (and on each of `fields`). */
3223
+ authenticate(node, operation, fields = []) {
3224
+ checkAuthentication(this.model, this.auth, node, [operation]);
3225
+ for (const f of fields) checkAuthentication(this.model, this.auth, node, [operation], f);
3226
+ }
3227
+ /** Attributes of `node` selected in `fieldNodes` (they bring their field-level rules). */
3228
+ selectedAttributes(node, fieldNodes) {
3229
+ const names = new Set(
3230
+ [...collectFields(this.info, subSelections(fieldNodes)).values()].map(
3231
+ (n) => n[0].name.value
3232
+ )
3233
+ );
3234
+ return node.attributes.filter((a) => names.has(a.name));
3235
+ }
3236
+ /**
3237
+ * READ rules of a node selection: the `filter` predicate and the `validate` failure (BEFORE) for
3238
+ * the type and the selected attributes.
3239
+ */
3240
+ readRules(variable, node, fieldNodes) {
3241
+ const attrs = this.selectedAttributes(node, fieldNodes);
3242
+ return {
3243
+ filter: this.rules.filter(variable, node, "READ", attrs),
3244
+ failure: this.rules.fails(variable, node, "READ", "BEFORE", attrs)
3245
+ };
3246
+ }
3247
+ /** `[marker]` for a list selection that is not allowed. */
3248
+ forbiddenList() {
3249
+ return `[${FORBIDDEN_MARKER}]`;
2008
3250
  }
2009
- sortItems(variable, attributes, sort, owner) {
3251
+ forbiddenMap() {
3252
+ return FORBIDDEN_MARKER;
3253
+ }
3254
+ sortItems(variable, attributes, sort, owner, pre) {
2010
3255
  const items = [];
2011
3256
  if (sort === null || typeof sort !== "object") return items;
2012
3257
  for (const [field, dir] of Object.entries(sort)) {
2013
3258
  if (dir !== "ASC" && dir !== "DESC") continue;
2014
3259
  const a = attributes.find((x) => x.name === field);
2015
3260
  if (!a) throw new Error(`Unknown sort field ${owner}.${field}`);
2016
- if (a.cypher)
2017
- throw notImplemented(`sorting on @cypher field ${owner}.${field}`, FOLLOW_UP.cypher);
3261
+ if (a.cypher) {
3262
+ items.push(`${this.sortValue(variable, a, pre)} ${dir}`);
3263
+ continue;
3264
+ }
2018
3265
  items.push(`${variable}.${q(a.property)} ${dir}`);
2019
3266
  }
2020
3267
  return items;
2021
3268
  }
2022
- nodeOrder(variable, node, sort) {
3269
+ /** The variable holding a `@cypher` sort value, computed once per field (v7). */
3270
+ sortValue(variable, a, pre) {
3271
+ const key = `${variable}.${a.name}`;
3272
+ let v = pre.vars.get(key);
3273
+ if (!v) {
3274
+ const c = scalarClause(this.ctx, variable, a.cypher, a.args, {}, a.type.list);
3275
+ pre.clauses.push(c.clause);
3276
+ pre.vars.set(key, c.variable);
3277
+ v = c.variable;
3278
+ }
3279
+ return v;
3280
+ }
3281
+ nodeOrder(variable, node, sort, pre) {
2023
3282
  const items = (Array.isArray(sort) ? sort : []).flatMap(
2024
- (s) => this.sortItems(variable, node.attributes, s, node.name)
3283
+ (s) => this.sortItems(variable, node.attributes, s, node.name, pre)
2025
3284
  );
2026
3285
  return items.length ? `ORDER BY ${items.join(", ")}` : "";
2027
3286
  }
2028
- connectionOrder(relVar, nodeVar, rel, sort) {
3287
+ connectionOrder(relVar, nodeVar, rel, sort, pre) {
2029
3288
  const target = this.model.node(rel.target);
2030
3289
  const props = this.props(rel);
2031
3290
  const items = [];
2032
3291
  for (const s of Array.isArray(sort) ? sort : []) {
2033
3292
  if (s === null || typeof s !== "object") continue;
2034
3293
  for (const [k, v] of Object.entries(s)) {
2035
- if (k === "node") items.push(...this.sortItems(nodeVar, target.attributes, v, target.name));
3294
+ if (k === "node")
3295
+ items.push(...this.sortItems(nodeVar, target.attributes, v, target.name, pre));
2036
3296
  else if (k === "edge" && props)
2037
- items.push(...this.sortItems(relVar, props.attributes, v, props.name));
3297
+ items.push(...this.sortItems(relVar, props.attributes, v, props.name, pre));
2038
3298
  }
2039
3299
  }
2040
3300
  return items.length ? `ORDER BY ${items.join(", ")}` : "";
2041
3301
  }
3302
+ /**
3303
+ * The value of a scalar `@cypher` field of `variable` for the response key: the sort value when
3304
+ * the field was sorted on (same field, no arguments), else a new `CALL` clause in `scope`.
3305
+ */
3306
+ cypherValue(scope, variable, attr, fieldNode, gqlType, pre) {
3307
+ const reused = attr.args.length ? void 0 : pre?.vars.get(`${variable}.${attr.name}`);
3308
+ if (reused) return reused;
3309
+ const values = attr.args.length ? fieldArgs(gqlType.getFields()[attr.name], fieldNode, this.info) : {};
3310
+ const c = scalarClause(this.ctx, variable, attr.cypher, attr.args, values, attr.type.list);
3311
+ scope.push(c.clause);
3312
+ return c.variable;
3313
+ }
2042
3314
  props(rel) {
2043
3315
  return rel.properties ? this.model.properties.get(rel.properties) : void 0;
2044
3316
  }
2045
3317
  /** `{ key: expr, … }` for a selection on a node variable, and its decoder. */
2046
- projectNode(variable, node, fieldNodes) {
2047
- this.assertReadable(node);
3318
+ projectNode(variable, node, fieldNodes, scope, pre) {
3319
+ const fields = [...collectFields(this.info, subSelections(fieldNodes)).values()].map(
3320
+ (n) => n[0].name.value
3321
+ );
3322
+ this.authenticate(node, "READ", fields);
2048
3323
  const type = objectType(this.info, node.name);
2049
3324
  const gqlFields = type.getFields();
2050
3325
  const entries = [];
@@ -2054,25 +3329,31 @@ var SelectionCompiler = class {
2054
3329
  if (name === "__typename") continue;
2055
3330
  const attr = node.attributes.find((a) => a.name === name);
2056
3331
  if (attr) {
2057
- if (attr.cypher)
2058
- throw notImplemented(`@cypher field ${node.name}.${name}`, FOLLOW_UP.cypher);
2059
- entries.push(`${q(key)}: ${variable}.${q(attr.property)}`);
3332
+ const value = attr.cypher ? this.cypherValue(scope, variable, attr, nodes[0], type, pre) : `${variable}.${q(attr.property)}`;
3333
+ entries.push(`${q(key)}: ${value}`);
2060
3334
  decoders.push([key, attributeDecoder(attr)]);
2061
3335
  continue;
2062
3336
  }
2063
3337
  const gqlField = gqlFields[name];
2064
3338
  if (!gqlField) throw new Error(`Unknown field ${node.name}.${name}`);
2065
3339
  const args = fieldArgs(gqlField, nodes[0], this.info);
3340
+ const cypherNode = node.cypherNodes.find((c) => c.name === name);
3341
+ if (cypherNode) {
3342
+ const p = this.cypherNodeField(scope, variable, cypherNode, args, nodes);
3343
+ entries.push(`${q(key)}: ${p.expr}`);
3344
+ decoders.push([key, p.decode]);
3345
+ continue;
3346
+ }
2066
3347
  const rel = node.relationships.find((r) => r.name === name);
2067
3348
  if (rel) {
2068
- const p = this.relationshipList(variable, rel, args, nodes);
3349
+ const p = this.relationshipList(scope, variable, rel, args, nodes);
2069
3350
  entries.push(`${q(key)}: ${p.expr}`);
2070
3351
  decoders.push([key, p.decode]);
2071
3352
  continue;
2072
3353
  }
2073
3354
  const connRel = name.endsWith("Connection") ? node.relationships.find((r) => `${r.name}Connection` === name) : void 0;
2074
3355
  if (connRel) {
2075
- const p = this.relationshipConnection(variable, connRel, args, nodes);
3356
+ const p = this.relationshipConnection(scope, variable, connRel, args, nodes);
2076
3357
  entries.push(`${q(key)}: ${p.expr}`);
2077
3358
  decoders.push([key, p.decode]);
2078
3359
  continue;
@@ -2089,15 +3370,17 @@ var SelectionCompiler = class {
2089
3370
  }
2090
3371
  };
2091
3372
  }
2092
- projectProperties(relVar, props, fieldNodes) {
3373
+ projectProperties(relVar, props, fieldNodes, scope, pre) {
2093
3374
  const entries = [];
2094
3375
  const decoders = [];
3376
+ const type = objectType(this.info, props.name);
2095
3377
  for (const [key, nodes] of collectFields(this.info, subSelections(fieldNodes))) {
2096
3378
  const name = nodes[0].name.value;
2097
3379
  if (name === "__typename") continue;
2098
3380
  const attr = props.attributes.find((a) => a.name === name);
2099
3381
  if (!attr) throw new Error(`Unknown field ${props.name}.${name}`);
2100
- entries.push(`${q(key)}: ${relVar}.${q(attr.property)}`);
3382
+ const value = attr.cypher ? this.cypherValue(scope, relVar, attr, nodes[0], type, pre) : `${relVar}.${q(attr.property)}`;
3383
+ entries.push(`${q(key)}: ${value}`);
2101
3384
  decoders.push([key, attributeDecoder(attr)]);
2102
3385
  }
2103
3386
  return {
@@ -2110,23 +3393,66 @@ var SelectionCompiler = class {
2110
3393
  }
2111
3394
  };
2112
3395
  }
2113
- relationshipList(variable, rel, args, fieldNodes) {
3396
+ relationshipList(scope, variable, rel, args, fieldNodes) {
2114
3397
  const target = this.model.node(rel.target);
2115
3398
  const m = this.ctx.variable("this");
2116
3399
  const pattern = relationshipPattern(this.model, variable, rel, m);
2117
- const pred = this.where.node(m, target, args.where);
2118
- const order = this.nodeOrder(m, target, args.sort);
3400
+ const auth = this.readRules(m, target, fieldNodes);
3401
+ const pred = and3([this.where.node(m, target, args.where), auth.filter]);
3402
+ const pre = sortScope();
3403
+ const order = this.nodeOrder(m, target, args.sort, pre);
2119
3404
  const page = paging(this.ctx, args.offset, args.limit);
2120
- const inner = this.projectNode(m, target, fieldNodes);
3405
+ const inner = [];
3406
+ const proj = this.projectNode(m, target, fieldNodes, inner, pre);
3407
+ const row = this.rowGate(inner, auth.failure, proj.expr, this.forbiddenMap());
2121
3408
  const body = [
2122
3409
  `MATCH ${pattern}`,
2123
3410
  pred ? `WHERE ${pred}` : "",
2124
- withClause(m, order, page),
2125
- `RETURN ${inner.expr}`
2126
- ].filter(Boolean).join(" ");
3411
+ ...pre.clauses,
3412
+ withClause(m, order, page, pre),
3413
+ ...inner
3414
+ ];
3415
+ const list2 = this.subquery(scope, "collect", body, row);
3416
+ return {
3417
+ expr: this.gate(scope, pattern, pred, auth.failure, list2, this.forbiddenList()),
3418
+ decode: (raw) => Array.isArray(raw) ? raw.map(proj.decode) : []
3419
+ };
3420
+ }
3421
+ /**
3422
+ * A `@cypher` field returning nodes: `CALL (v) { <statement> WITH col AS n WHERE n IS NOT NULL
3423
+ * AND <READ filter> … RETURN collect(<projection>) AS s }` (`head(…)` for one node). The READ rules
3424
+ * of the returned type apply (a node failing `validate` makes the field `Forbidden`), like v7.
3425
+ */
3426
+ cypherNodeField(scope, variable, field, args, fieldNodes) {
3427
+ const target = this.model.node(field.target);
3428
+ const call = statementCall(this.ctx, field.cypher, field.args, args, variable);
3429
+ const p = this.cypherNodes(call, field.cypher, target, fieldNodes);
3430
+ const s = this.ctx.variable("cypher");
3431
+ const value = field.type.list ? `collect(${p.row})` : `head(collect(${p.row}))`;
3432
+ scope.push([`CALL (${variable}) {`, ...p.clauses, `RETURN ${value} AS ${s}`, "}"].join("\n"));
3433
+ return {
3434
+ expr: s,
3435
+ decode: field.type.list ? (raw) => Array.isArray(raw) ? raw.map(p.decode) : [] : (raw) => raw === null || raw === void 0 ? null : p.decode(raw)
3436
+ };
3437
+ }
3438
+ /**
3439
+ * Clauses that run a statement returning nodes and keep the readable ones (`WHERE n IS NOT NULL
3440
+ * AND <READ filter>`), and the projection of one row (or the forbidden marker).
3441
+ */
3442
+ cypherNodes(call, cypher, target, fieldNodes) {
3443
+ const n = this.ctx.variable("this");
3444
+ const auth = this.readRules(n, target, fieldNodes);
3445
+ const inner = [];
3446
+ const proj = this.projectNode(n, target, fieldNodes, inner);
3447
+ const row = this.rowGate(inner, auth.failure, proj.expr, this.forbiddenMap());
2127
3448
  return {
2128
- expr: `COLLECT { ${body} }`,
2129
- decode: (raw) => Array.isArray(raw) ? raw.map(inner.decode) : []
3449
+ clauses: [
3450
+ call,
3451
+ `WITH ${column(cypher)} AS ${n} WHERE ${and3([`${n} IS NOT NULL`, auth.filter])}`,
3452
+ ...inner
3453
+ ],
3454
+ row,
3455
+ decode: proj.decode
2130
3456
  };
2131
3457
  }
2132
3458
  /**
@@ -2138,6 +3464,10 @@ var SelectionCompiler = class {
2138
3464
  const afterOffset = cursorToOffset(opts.args.after);
2139
3465
  const offset = afterOffset === void 0 ? 0 : afterOffset + 1;
2140
3466
  const conn = collectFields(this.info, subSelections(opts.fieldNodes));
3467
+ this.authenticate(opts.node, "READ");
3468
+ const edgeNodeFields = [...collectFields(this.info, subSelections(conn.get("edges") ?? []))].filter(([, n]) => n[0].name.value === "node").flatMap(([, n]) => n);
3469
+ const readAuth = this.readRules(opts.nodeVar, opts.node, edgeNodeFields);
3470
+ const readPredicate = and3([opts.predicate, readAuth.filter]);
2141
3471
  const edgeEntries = [];
2142
3472
  const edgeDecoders = [];
2143
3473
  const edgeFieldNodes = [];
@@ -2145,13 +3475,32 @@ var SelectionCompiler = class {
2145
3475
  const aggregateEntries = [];
2146
3476
  let needsTotal = false;
2147
3477
  let needsEdges = false;
2148
- const where = opts.predicate ? ` WHERE ${opts.predicate}` : "";
3478
+ const where = readPredicate ? ` WHERE ${readPredicate}` : "";
2149
3479
  for (const [key, nodes] of conn) {
2150
3480
  const name = nodes[0].name.value;
2151
3481
  if (name === "aggregate") {
3482
+ const aggNodeFields = [...collectFields(this.info, subSelections(nodes))].filter(([, n]) => n[0].name.value === "node").flatMap(([, n]) => n);
3483
+ const aggAttrs = this.selectedAttributes(opts.node, aggNodeFields);
3484
+ this.authenticate(
3485
+ opts.node,
3486
+ "AGGREGATE",
3487
+ aggAttrs.map((a) => a.name)
3488
+ );
3489
+ const aggPredicate = and3([
3490
+ opts.predicate,
3491
+ this.rules.filter(opts.nodeVar, opts.node, "AGGREGATE", aggAttrs)
3492
+ ]);
3493
+ const aggFailure = this.rules.fails(
3494
+ opts.nodeVar,
3495
+ opts.node,
3496
+ "AGGREGATE",
3497
+ "BEFORE",
3498
+ aggAttrs
3499
+ );
2152
3500
  const p = this.aggregate(
2153
3501
  {
2154
- base: `MATCH ${opts.match}${where}`,
3502
+ scope: opts.scope,
3503
+ base: `MATCH ${opts.match}${aggPredicate ? ` WHERE ${aggPredicate}` : ""}`,
2155
3504
  nodeVar: opts.nodeVar,
2156
3505
  relVar: opts.relVar,
2157
3506
  node: opts.node,
@@ -2160,39 +3509,59 @@ var SelectionCompiler = class {
2160
3509
  },
2161
3510
  nodes
2162
3511
  );
2163
- aggregateEntries.push(`${q(key)}: ${p.expr}`);
3512
+ aggregateEntries.push(
3513
+ `${q(key)}: ${this.gate(opts.scope, opts.match, aggPredicate, aggFailure, p.expr, this.forbiddenMap())}`
3514
+ );
2164
3515
  aggregates.push([key, p.decode]);
2165
3516
  }
2166
3517
  if (name === "edges") edgeFieldNodes.push(...nodes);
2167
3518
  if (name === "edges" || name === "pageInfo") needsEdges = true;
2168
3519
  if (name === "totalCount" || name === "pageInfo") needsTotal = true;
2169
3520
  }
3521
+ const edgeScope = [];
2170
3522
  for (const [key, nodes] of collectFields(this.info, subSelections(edgeFieldNodes))) {
2171
3523
  const name = nodes[0].name.value;
2172
3524
  if (name === "cursor") {
2173
3525
  edgeDecoders.push([key, (_raw, i) => offsetToCursor(offset + i)]);
2174
3526
  } else if (name === "node") {
2175
- const p = opts.projectNode(nodes);
3527
+ const p = opts.projectNode(nodes, edgeScope, opts.pre);
2176
3528
  edgeEntries.push(`${q(key)}: ${p.expr}`);
2177
3529
  edgeDecoders.push([key, (raw) => p.decode(raw[key])]);
2178
3530
  } else if (name === "properties" && opts.projectProperties) {
2179
- const p = opts.projectProperties(nodes);
3531
+ const p = opts.projectProperties(nodes, edgeScope, opts.pre);
2180
3532
  edgeEntries.push(`${q(key)}: ${p.expr}`);
2181
3533
  edgeDecoders.push([key, (raw) => p.decode(raw[key])]);
2182
3534
  }
2183
3535
  }
2184
3536
  const withVars = opts.relVar ? `${opts.relVar}, ${opts.nodeVar}` : opts.nodeVar;
2185
3537
  const page = paging(this.ctx, offset || void 0, opts.args.first);
3538
+ const edgeRow = this.rowGate(
3539
+ edgeScope,
3540
+ needsEdges ? readAuth.failure : void 0,
3541
+ `{ ${edgeEntries.join(", ")} }`,
3542
+ this.forbiddenMap()
3543
+ );
2186
3544
  const edgesBody = [
2187
3545
  `MATCH ${opts.match}${where}`,
2188
- withClause(withVars, opts.order, page),
2189
- `RETURN { ${edgeEntries.join(", ")} }`
2190
- ].filter(Boolean).join(" ");
3546
+ ...opts.pre.clauses,
3547
+ withClause(withVars, opts.order, page, opts.pre),
3548
+ ...edgeScope
3549
+ ];
2191
3550
  const parts = [];
2192
- if (needsTotal) parts.push(`total: COUNT { MATCH ${opts.match}${where} }`);
2193
- if (needsEdges) parts.push(`edges: COLLECT { ${edgesBody} }`);
3551
+ if (needsTotal)
3552
+ parts.push(`total: ${this.subquery(opts.scope, "count", [`MATCH ${opts.match}${where}`])}`);
3553
+ if (needsEdges)
3554
+ parts.push(`edges: ${this.subquery(opts.scope, "collect", edgesBody, edgeRow)}`);
2194
3555
  if (aggregateEntries.length) parts.push(`aggregate: { ${aggregateEntries.join(", ")} }`);
2195
- const expr = `{ ${parts.join(", ")} }`;
3556
+ const map = `{ ${parts.join(", ")} }`;
3557
+ const expr = needsTotal || needsEdges ? this.gate(
3558
+ opts.scope,
3559
+ opts.match,
3560
+ readPredicate,
3561
+ readAuth.failure,
3562
+ map,
3563
+ this.forbiddenMap()
3564
+ ) : map;
2196
3565
  return {
2197
3566
  expr,
2198
3567
  decode: (raw) => {
@@ -2255,7 +3624,9 @@ var SelectionCompiler = class {
2255
3624
  const what = cn[0].name.value;
2256
3625
  const v = what === "nodes" ? scope.nodeVar : what === "edges" ? scope.relVar : void 0;
2257
3626
  if (!v) continue;
2258
- counts.push(`${q(ck)}: COUNT { ${scope.base} WITH DISTINCT ${v} RETURN ${v} }`);
3627
+ counts.push(
3628
+ `${q(ck)}: ${this.subquery(scope.scope, "count", [scope.base, `WITH DISTINCT ${v}`], v)}`
3629
+ );
2259
3630
  keys.push(ck);
2260
3631
  }
2261
3632
  entries.push(`${q(key)}: { ${counts.join(", ")} }`);
@@ -2275,7 +3646,6 @@ var SelectionCompiler = class {
2275
3646
  const attributes = isEdge ? scope.props?.attributes : scope.node.attributes;
2276
3647
  if (!variable || !attributes)
2277
3648
  throw new Error(`Unknown field ${scope.owner}.aggregate.${name}`);
2278
- this.assertReadable(scope.node);
2279
3649
  const fieldEntries = [];
2280
3650
  const fieldDecoders = [];
2281
3651
  for (const [fk, fn] of collectFields(this.info, subSelections(nodes))) {
@@ -2283,7 +3653,7 @@ var SelectionCompiler = class {
2283
3653
  if (field === "__typename") continue;
2284
3654
  const attr = attributes.find((a) => a.name === field);
2285
3655
  if (!attr) throw new Error(`Unknown field ${scope.owner}.aggregate.${name}.${field}`);
2286
- const p = this.aggregateAttribute(scope.base, variable, attr, fn);
3656
+ const p = this.aggregateAttribute(scope.scope, scope.base, variable, attr, fn);
2287
3657
  fieldEntries.push(`${q(fk)}: ${p.expr}`);
2288
3658
  fieldDecoders.push([fk, p.decode]);
2289
3659
  }
@@ -2293,7 +3663,7 @@ var SelectionCompiler = class {
2293
3663
  return { expr: `{ ${entries.join(", ")} }`, decode: mapDecoder(decoders) };
2294
3664
  }
2295
3665
  /** `min` / `max` / `average` / `sum` / `shortest` / `longest` of one attribute, v7 semantics. */
2296
- aggregateAttribute(base, variable, attr, fieldNodes) {
3666
+ aggregateAttribute(scope, base, variable, attr, fieldNodes) {
2297
3667
  const prop = `${variable}.${q(attr.property)}`;
2298
3668
  const type = attr.type.name;
2299
3669
  const ops = [];
@@ -2306,7 +3676,12 @@ var SelectionCompiler = class {
2306
3676
  const l = this.ctx.variable("list");
2307
3677
  const values = `${base} WITH DISTINCT ${variable} WHERE ${prop} IS NOT NULL`;
2308
3678
  if (type === "String") {
2309
- const list3 = `COLLECT { ${values} WITH ${variable} ORDER BY size(${prop}) DESC RETURN ${prop} }`;
3679
+ const list3 = this.subquery(
3680
+ scope,
3681
+ "collect",
3682
+ [values, `WITH ${variable} ORDER BY size(${prop}) DESC`],
3683
+ prop
3684
+ );
2310
3685
  const items2 = ops.map(
2311
3686
  ([k, op]) => `${q(k)}: ${op === "longest" ? `head(${l})` : op === "shortest" ? `last(${l})` : "null"}`
2312
3687
  );
@@ -2315,7 +3690,7 @@ var SelectionCompiler = class {
2315
3690
  decode: mapDecoder(decoders)
2316
3691
  };
2317
3692
  }
2318
- const list2 = `COLLECT { ${values} RETURN ${prop} }`;
3693
+ const list2 = this.subquery(scope, "collect", [values], prop);
2319
3694
  const items = ops.map(([k, op]) => {
2320
3695
  const fn = AGGREGATE_FUNCTIONS[op];
2321
3696
  return `${q(k)}: ${fn ? listAggregate(fn, l) : "null"}`;
@@ -2325,20 +3700,22 @@ var SelectionCompiler = class {
2325
3700
  decode: mapDecoder(decoders)
2326
3701
  };
2327
3702
  }
2328
- relationshipConnection(variable, rel, args, fieldNodes) {
3703
+ relationshipConnection(scope, variable, rel, args, fieldNodes) {
2329
3704
  const target = this.model.node(rel.target);
2330
- this.assertReadable(target);
2331
3705
  const m = this.ctx.variable("this");
2332
3706
  const r = this.ctx.variable("edge");
2333
3707
  const props = this.props(rel);
3708
+ const pre = sortScope();
2334
3709
  return this.connection({
3710
+ scope,
2335
3711
  match: relationshipPattern(this.model, variable, rel, m, r),
2336
3712
  predicate: this.where.connection(r, m, rel, args.where),
2337
- order: this.connectionOrder(r, m, rel, args.sort),
3713
+ order: this.connectionOrder(r, m, rel, args.sort, pre),
3714
+ pre,
2338
3715
  nodeVar: m,
2339
3716
  relVar: r,
2340
- projectNode: (nodes) => this.projectNode(m, target, nodes),
2341
- projectProperties: props ? (nodes) => this.projectProperties(r, props, nodes) : void 0,
3717
+ projectNode: (nodes, sc, p) => this.projectNode(m, target, nodes, sc, p),
3718
+ projectProperties: props ? (nodes, sc, p) => this.projectProperties(r, props, nodes, sc, p) : void 0,
2342
3719
  node: target,
2343
3720
  props,
2344
3721
  args,
@@ -2348,45 +3725,194 @@ var SelectionCompiler = class {
2348
3725
  }
2349
3726
  /** `movies(where, sort, limit, offset)`. */
2350
3727
  rootList(node, args, fieldNodes) {
2351
- this.assertReadable(node);
2352
3728
  const v = this.ctx.variable("this");
2353
- const pred = this.where.node(v, node, args.where);
2354
- const order = this.nodeOrder(v, node, args.sort);
3729
+ const auth = this.readRules(v, node, fieldNodes);
3730
+ const pred = and3([this.where.node(v, node, args.where), auth.filter]);
3731
+ const pre = sortScope();
3732
+ const order = this.nodeOrder(v, node, args.sort, pre);
2355
3733
  const page = paging(this.ctx, args.offset, args.limit);
2356
- const proj = this.projectNode(v, node, fieldNodes);
2357
- const cypher = [
3734
+ const inner = [];
3735
+ const proj = this.projectNode(v, node, fieldNodes, inner, pre);
3736
+ const head = [
2358
3737
  `MATCH (${v}${labels(node.labels)})`,
2359
3738
  pred ? `WHERE ${pred}` : "",
2360
- withClause(v, order, page),
2361
- `RETURN ${proj.expr} AS this`
2362
- ].filter(Boolean).join("\n");
3739
+ ...pre.clauses,
3740
+ withClause(v, order, page, pre),
3741
+ ...inner
3742
+ ];
3743
+ if (auth.failure !== void 0) {
3744
+ const root = [];
3745
+ const row = this.rowGate(inner, auth.failure, proj.expr, this.forbiddenMap());
3746
+ const list2 = this.subquery(root, "collect", head, row);
3747
+ const match = `(${v}${labels(node.labels)})`;
3748
+ const value = this.gate(root, match, pred, auth.failure, list2, this.forbiddenList());
3749
+ return {
3750
+ cypher: [...root, `RETURN ${value} AS this`].join("\n"),
3751
+ params: this.ctx.params,
3752
+ decode: (rows) => Array.isArray(rows[0]) ? rows[0].map(proj.decode) : []
3753
+ };
3754
+ }
3755
+ const cypher = [...head, `RETURN ${proj.expr} AS this`].filter(Boolean).join("\n");
2363
3756
  return { cypher, params: this.ctx.params, decode: (rows) => rows.map(proj.decode) };
2364
3757
  }
2365
3758
  /** `moviesConnection(where, sort, first, after)`. */
2366
3759
  rootConnection(node, args, fieldNodes) {
2367
- this.assertReadable(node);
2368
3760
  const v = this.ctx.variable("this");
3761
+ const root = [];
3762
+ const pre = sortScope();
2369
3763
  const c = this.connection({
3764
+ scope: root,
2370
3765
  match: `(${v}${labels(node.labels)})`,
2371
3766
  predicate: this.where.node(v, node, args.where),
2372
- order: this.nodeOrder(v, node, args.sort),
3767
+ order: this.nodeOrder(v, node, args.sort, pre),
3768
+ pre,
2373
3769
  nodeVar: v,
2374
- projectNode: (nodes) => this.projectNode(v, node, nodes),
3770
+ projectNode: (nodes, sc, p) => this.projectNode(v, node, nodes, sc, p),
2375
3771
  node,
2376
3772
  args,
2377
3773
  fieldNodes,
2378
3774
  owner: `${node.plural}Connection`
2379
3775
  });
2380
3776
  return {
2381
- cypher: `RETURN ${c.expr} AS this`,
3777
+ cypher: [...root, `RETURN ${c.expr} AS this`].join("\n"),
2382
3778
  params: this.ctx.params,
2383
3779
  decode: (rows) => c.decode(rows[0])
2384
3780
  };
2385
3781
  }
3782
+ /**
3783
+ * A `Query` / `Mutation` `@cypher` field: `CALL () { <statement> }` then one row per returned
3784
+ * value (a scalar list column is flattened, like v7). A non-list field takes the first row.
3785
+ * Returned nodes get the READ rules of their type and the selection's projection.
3786
+ */
3787
+ rootCypher(field, args, fieldNodes) {
3788
+ const call = statementCall(this.ctx, field.cypher, field.args, args);
3789
+ const list2 = field.type.list;
3790
+ if (field.kind !== "node") {
3791
+ const decode = attributeDecoder({ kind: field.kind, type: field.type });
3792
+ const x = this.ctx.variable("value");
3793
+ const cypher = list2 ? [call, `UNWIND ${column(field.cypher)} AS ${x}`, `RETURN ${x} AS this`] : [call, `RETURN ${column(field.cypher)} AS this`];
3794
+ return {
3795
+ cypher: cypher.join("\n"),
3796
+ params: this.ctx.params,
3797
+ decode: list2 ? (rows) => rows.map((r) => decode(r)) : (rows) => rows.length ? decode(rows[0]) : null
3798
+ };
3799
+ }
3800
+ const target = this.model.node(field.type.name);
3801
+ this.authenticate(target, "READ");
3802
+ const p = this.cypherNodes(call, field.cypher, target, fieldNodes);
3803
+ return {
3804
+ cypher: [...p.clauses, `RETURN ${p.row} AS this`].join("\n"),
3805
+ params: this.ctx.params,
3806
+ decode: list2 ? (rows) => rows.map(p.decode) : (rows) => rows.length ? p.decode(rows[0]) : null
3807
+ };
3808
+ }
3809
+ /**
3810
+ * A `@fulltext` query (`moviesByTitle(phrase, where, sort, first, after)`), v7 7.6:
3811
+ * `db.index.fulltext.queryNodes(index, phrase)` keeps the nodes of the type that match `where`
3812
+ * (`score: { min, max }` and `node`) and its READ filter rules; `totalCount` counts them,
3813
+ * `edges` (`node`, `score`, offset cursors) are ordered by `sort` (no order: the index order,
3814
+ * best score first) and paginated by `first` / `after`. A matching node that fails READ
3815
+ * `validate` rules makes the query `Forbidden`.
3816
+ */
3817
+ rootFulltext(node, index, args, fieldNodes) {
3818
+ this.authenticate(node, "READ");
3819
+ const v = this.ctx.variable("this");
3820
+ const score = this.ctx.variable("score");
3821
+ const conn = collectFields(this.info, subSelections(fieldNodes));
3822
+ const edgeFields = [...conn].filter(([, n]) => n[0].name.value === "edges").flatMap(([, n]) => n);
3823
+ const nodeFields = [...collectFields(this.info, subSelections(edgeFields))].filter(([, n]) => n[0].name.value === "node").flatMap(([, n]) => n);
3824
+ const auth = this.readRules(v, node, nodeFields);
3825
+ const where = args.where ?? {};
3826
+ const scoreWhere = where.score ?? {};
3827
+ const pred = and3([
3828
+ `${v}${labels(node.labels)}`,
3829
+ typeof scoreWhere.min === "number" ? `${score} >= ${this.ctx.param(scoreWhere.min)}` : void 0,
3830
+ typeof scoreWhere.max === "number" ? `${score} <= ${this.ctx.param(scoreWhere.max)}` : void 0,
3831
+ this.where.node(v, node, where.node),
3832
+ auth.filter
3833
+ ]);
3834
+ const pre = sortScope();
3835
+ const items = [];
3836
+ for (const s of Array.isArray(args.sort) ? args.sort : []) {
3837
+ if (s === null || typeof s !== "object") continue;
3838
+ for (const [k, dir] of Object.entries(s)) {
3839
+ if (k === "score" && (dir === "ASC" || dir === "DESC")) items.push(`${score} ${dir}`);
3840
+ else if (k === "node")
3841
+ items.push(...this.sortItems(v, node.attributes, dir, node.name, pre));
3842
+ }
3843
+ }
3844
+ const afterOffset = cursorToOffset(args.after);
3845
+ const offset = afterOffset === void 0 ? 0 : afterOffset + 1;
3846
+ const page = paging(this.ctx, offset || void 0, args.first);
3847
+ const edges = this.ctx.variable("edges");
3848
+ const e = this.ctx.variable("edge");
3849
+ const inner = [];
3850
+ const entries = [`score: ${score}`];
3851
+ const decoders = [];
3852
+ for (const [key, nodes] of collectFields(this.info, subSelections(edgeFields))) {
3853
+ const name = nodes[0].name.value;
3854
+ if (name === "cursor") decoders.push([key, (_r, i) => offsetToCursor(offset + i)]);
3855
+ else if (name === "score") decoders.push([key, (r) => toFloat(r.score)]);
3856
+ else if (name === "node") {
3857
+ const p = this.projectNode(v, node, nodes, inner, pre);
3858
+ entries.push(`${q(key)}: ${p.expr}`);
3859
+ decoders.push([key, (r) => p.decode(r[key])]);
3860
+ }
3861
+ }
3862
+ const order = items.length ? `ORDER BY ${items.join(", ")}` : "";
3863
+ const denied = this.ctx.variable("denied");
3864
+ const pageVar = this.ctx.variable("page");
3865
+ const result = `{ edges: ${pageVar}, total: size(${edges}) }`;
3866
+ const cypher = [
3867
+ `CALL db.index.fulltext.queryNodes(${this.ctx.param(index.indexName)}, ${this.ctx.param(args.phrase ?? "")}) YIELD node AS ${v}, score AS ${score}`,
3868
+ `WHERE ${pred}`,
3869
+ `WITH collect({ node: ${v}, score: ${score} }) AS ${edges}${auth.failure ? `, sum(CASE WHEN ${auth.failure} THEN 1 ELSE 0 END) > 0 AS ${denied}` : ""}`,
3870
+ `CALL (${edges}) {`,
3871
+ `UNWIND ${edges} AS ${e}`,
3872
+ `WITH ${e}.node AS ${v}, ${e}.score AS ${score}`,
3873
+ ...pre.clauses,
3874
+ withClause(`${v}, ${score}`, order, page, pre),
3875
+ ...inner,
3876
+ `RETURN collect({ ${entries.join(", ")} }) AS ${pageVar}`,
3877
+ `}`,
3878
+ `RETURN ${auth.failure ? `CASE WHEN ${denied} THEN ${this.forbiddenMap()} ELSE ${result} END` : result} AS this`
3879
+ ].filter(Boolean).join("\n");
3880
+ return {
3881
+ cypher,
3882
+ params: this.ctx.params,
3883
+ decode: (rows) => {
3884
+ const r = rows[0] ?? {};
3885
+ const total = toNumber(r.total ?? 0);
3886
+ const rawEdges = Array.isArray(r.edges) ? r.edges : [];
3887
+ const out = {};
3888
+ const list2 = rawEdges.map(
3889
+ (raw, i) => Object.fromEntries(decoders.map(([k, dec]) => [k, dec(raw ?? {}, i)]))
3890
+ );
3891
+ for (const [key, nodes] of conn) {
3892
+ const name = nodes[0].name.value;
3893
+ if (name === "totalCount") out[key] = total;
3894
+ else if (name === "edges") out[key] = list2;
3895
+ else if (name === "pageInfo") {
3896
+ const info = {};
3897
+ for (const [pk, pn] of collectFields(this.info, subSelections(nodes))) {
3898
+ const n = pn[0].name.value;
3899
+ if (n === "hasNextPage") info[pk] = offset + list2.length < total;
3900
+ else if (n === "hasPreviousPage") info[pk] = offset > 0;
3901
+ else if (n === "startCursor") info[pk] = list2.length ? offsetToCursor(offset) : null;
3902
+ else if (n === "endCursor")
3903
+ info[pk] = list2.length ? offsetToCursor(offset + list2.length - 1) : null;
3904
+ }
3905
+ out[key] = info;
3906
+ }
3907
+ }
3908
+ return out;
3909
+ }
3910
+ };
3911
+ }
2386
3912
  };
2387
3913
 
2388
3914
  // src/v7/cypher/mutate.ts
2389
- import { GraphQLError as GraphQLError3 } from "graphql";
3915
+ import { GraphQLError as GraphQLError4 } from "graphql";
2390
3916
  import { isInt as isInt2 } from "neo4j-driver";
2391
3917
  var COUNTER_KEYS = {
2392
3918
  nodesCreated: "nc",
@@ -2471,25 +3997,49 @@ function decodeCounts(fields, counts) {
2471
3997
  );
2472
3998
  }
2473
3999
  var MutationCompiler = class {
2474
- constructor(model, info) {
4000
+ constructor(model, info, auth) {
2475
4001
  this.model = model;
2476
4002
  this.info = info;
2477
- this.select = new SelectionCompiler(model, info);
4003
+ this.auth = auth;
4004
+ this.select = new SelectionCompiler(model, info, auth);
2478
4005
  this.ctx = this.select.ctx;
2479
- this.where = new WhereCompiler(model, this.ctx, (n) => this.select.assertReadable(n));
4006
+ this.rules = this.select.rules;
4007
+ this.where = new WhereCompiler(model, this.ctx);
2480
4008
  }
2481
4009
  model;
2482
4010
  info;
4011
+ auth;
2483
4012
  select;
2484
4013
  where;
2485
4014
  ctx;
2486
- assertWritable(node) {
2487
- if (node.auth.authorization || node.auth.authentication?.length) {
2488
- throw notImplemented(
2489
- `writing ${node.name}, which has @authentication / @authorization rules`,
2490
- FOLLOW_UP.authorization
4015
+ rules;
4016
+ /** `@authentication` for `operation` on the type and on the written `fields`. */
4017
+ authenticate(node, operation, fields = []) {
4018
+ checkAuthentication(this.model, this.auth, node, [operation]);
4019
+ for (const f of fields) checkAuthentication(this.model, this.auth, node, [operation], f);
4020
+ }
4021
+ /** Attributes written by a create / update input (`title`, `title_SET`, …). */
4022
+ writtenAttributes(node, input) {
4023
+ if (!isPlainObject2(input)) return [];
4024
+ const out = /* @__PURE__ */ new Set();
4025
+ for (const [key, value] of Object.entries(input)) {
4026
+ if (value === void 0) continue;
4027
+ const attr = node.attributes.find((a) => a.name === key) ?? node.attributes.find(
4028
+ (a) => key.startsWith(`${a.name}_`) && key.slice(a.name.length + 1) in LEGACY_UPDATE_OPERATORS
2491
4029
  );
4030
+ if (attr) out.add(attr);
2492
4031
  }
4032
+ return [...out];
4033
+ }
4034
+ /**
4035
+ * Evaluates `check` (a `CASE WHEN … THEN 'Forbidden' END`) on the current rows and keeps its result
4036
+ * (`WITH *, … AS authN`), so a BEFORE check sees the graph as it was before the writes that follow.
4037
+ */
4038
+ capture(block, check) {
4039
+ if (check === void 0) return;
4040
+ const v = this.ctx.variable("auth");
4041
+ block.add(`WITH *, ${check} AS ${v}`);
4042
+ block.check([v]);
2493
4043
  }
2494
4044
  props(rel) {
2495
4045
  return rel.properties ? this.model.properties.get(rel.properties) : void 0;
@@ -2556,7 +4106,7 @@ ${indent(inner.clauses)}
2556
4106
  const sets = [];
2557
4107
  for (const [attr, { keys, ops }] of byAttribute) {
2558
4108
  if (keys.length > 1) {
2559
- throw new GraphQLError3(
4109
+ throw new GraphQLError4(
2560
4110
  `Conflicting modification of ${keys.map((k) => `[[${k}]]`).join(", ")} on type ${owner}`
2561
4111
  );
2562
4112
  }
@@ -2615,7 +4165,12 @@ ${indent(inner.clauses)}
2615
4165
  // ---------------------------------------------------------------------------------------------
2616
4166
  /** `CREATE (v:Label) SET …` and the nested writes of a `${Node}CreateInput`. */
2617
4167
  createNode(block, v, node, input, afterCreate) {
2618
- this.assertWritable(node);
4168
+ const written = this.writtenAttributes(node, input);
4169
+ this.authenticate(
4170
+ node,
4171
+ "CREATE",
4172
+ written.map((a) => a.name)
4173
+ );
2619
4174
  block.add(`CREATE (${v}${labels(node.labels)})`);
2620
4175
  const sets = [
2621
4176
  ...onCreateGenerated(v, node.attributes),
@@ -2624,13 +4179,16 @@ ${indent(inner.clauses)}
2624
4179
  if (sets.length) block.add(`SET ${sets.join(", ")}`);
2625
4180
  block.count("nc", "1");
2626
4181
  afterCreate?.();
2627
- if (!isPlainObject2(input)) return;
2628
- for (const rel of node.relationships) {
2629
- const field = input[rel.name];
2630
- if (!isPlainObject2(field)) continue;
2631
- for (const el of asList(field.create)) this.nestedCreate(block, v, rel, el);
2632
- for (const el of asList(field.connect)) this.connect(block, v, rel, el);
4182
+ if (isPlainObject2(input)) {
4183
+ for (const rel of node.relationships) {
4184
+ const field = input[rel.name];
4185
+ if (!isPlainObject2(field)) continue;
4186
+ for (const el of asList(field.create)) this.nestedCreate(block, v, rel, el);
4187
+ for (const el of asList(field.connect)) this.connect(block, v, rel, el);
4188
+ }
2633
4189
  }
4190
+ const after = this.rules.check(this.rules.fails(v, node, "CREATE", "AFTER", written));
4191
+ if (after) block.check([after]);
2634
4192
  }
2635
4193
  /** `{ node, edge }` of a relationship `create`: a new related node and the edge to it. */
2636
4194
  nestedCreate(block, from, rel, el) {
@@ -2657,12 +4215,21 @@ ${indent(inner.clauses)}
2657
4215
  connect(block, from, rel, el) {
2658
4216
  if (!isPlainObject2(el)) return;
2659
4217
  const target = this.model.node(rel.target);
2660
- this.assertWritable(target);
4218
+ const source = this.model.node(rel.source);
4219
+ this.authenticate(target, "CREATE_RELATIONSHIP");
4220
+ this.authenticate(source, "CREATE_RELATIONSHIP");
2661
4221
  const inner = new Block();
2662
4222
  const t = this.ctx.variable("this");
2663
4223
  const where = isPlainObject2(el.where) ? el.where.node : void 0;
2664
- const pred = this.where.node(t, target, where);
4224
+ const pred = and4([
4225
+ this.where.node(t, target, where),
4226
+ this.rules.filter(t, target, "CREATE_RELATIONSHIP")
4227
+ ]);
2665
4228
  inner.add(`MATCH (${t}${labels(target.labels)})${pred ? ` WHERE ${pred}` : ""}`);
4229
+ this.capture(
4230
+ inner,
4231
+ this.rules.check(this.rules.fails(t, target, "CREATE_RELATIONSHIP", "BEFORE"))
4232
+ );
2666
4233
  for (const nested of asList(el.connect)) {
2667
4234
  if (!isPlainObject2(nested)) continue;
2668
4235
  for (const [name, els] of Object.entries(nested)) {
@@ -2678,6 +4245,11 @@ ${indent(inner.clauses)}
2678
4245
  if (sets.length) inner.add(`SET ${sets.join(", ")}`);
2679
4246
  }
2680
4247
  inner.count("rc", "1");
4248
+ const after = [
4249
+ this.rules.check(this.rules.fails(t, target, "CREATE_RELATIONSHIP", "AFTER")),
4250
+ this.rules.check(this.rules.fails(from, source, "CREATE_RELATIONSHIP", "AFTER"))
4251
+ ].filter((c) => c !== void 0);
4252
+ if (after.length) inner.check(after);
2681
4253
  this.call(block, [from], inner);
2682
4254
  }
2683
4255
  // ---------------------------------------------------------------------------------------------
@@ -2719,15 +4291,25 @@ ${indent(inner.clauses)}
2719
4291
  nestedUpdate(block, from, rel, el) {
2720
4292
  if (!isPlainObject2(el)) return;
2721
4293
  const target = this.model.node(rel.target);
2722
- this.assertWritable(target);
4294
+ const written = this.writtenAttributes(target, el.node);
4295
+ this.authenticate(
4296
+ target,
4297
+ "UPDATE",
4298
+ written.map((a) => a.name)
4299
+ );
4300
+ const typeRules = written.length > 0 || this.hasNestedUpdate(target, el.node);
2723
4301
  const props = this.props(rel);
2724
4302
  const inner = new Block();
2725
4303
  const t = this.ctx.variable("this");
2726
4304
  const r = this.ctx.variable("edge");
2727
- const pred = this.where.connection(r, t, rel, el.where);
4305
+ const pred = and4([
4306
+ this.where.connection(r, t, rel, el.where),
4307
+ typeRules ? this.rules.filter(t, target, "UPDATE") : void 0
4308
+ ]);
2728
4309
  inner.add(
2729
4310
  `MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`
2730
4311
  );
4312
+ this.capture(inner, this.updateCheck(t, target, "BEFORE", written, typeRules));
2731
4313
  const checks = [];
2732
4314
  const sets = [
2733
4315
  ...onUpdateGenerated(t, target.attributes),
@@ -2745,20 +4327,66 @@ ${indent(inner.clauses)}
2745
4327
  if (sets.length) inner.add(`SET ${sets.join(", ")}`);
2746
4328
  inner.check(checks);
2747
4329
  this.updateRelationships(inner, t, target, el.node);
4330
+ const after = this.updateCheck(t, target, "AFTER", written, typeRules);
4331
+ if (after) inner.check([after]);
2748
4332
  if (!inner.hasCounts() && inner.clauses.length === 1) return;
2749
4333
  this.call(block, [from], inner);
2750
4334
  }
4335
+ /** Whether an update input has a nested `update` on one of its relationships. */
4336
+ hasNestedUpdate(node, input) {
4337
+ if (!isPlainObject2(input)) return false;
4338
+ return node.relationships.some(
4339
+ (rel) => asList(input[rel.name]).some(
4340
+ (el) => isPlainObject2(el) && el.update !== void 0 && el.update !== null
4341
+ )
4342
+ );
4343
+ }
4344
+ /** UPDATE `validate` check: the type's rules (when they apply) and the written attributes' rules. */
4345
+ updateCheck(v, node, when, written, typeRules) {
4346
+ const validations = [
4347
+ ...typeRules ? this.rules.validations(v, node, "UPDATE", when) : [],
4348
+ ...written.flatMap(
4349
+ (a) => this.rules.validations(v, { ...node, auth: {} }, "UPDATE", when, [a])
4350
+ )
4351
+ ];
4352
+ return this.rules.check(this.rules.failure(validations));
4353
+ }
2751
4354
  /** `{ where, disconnect }`: deletes the matching relationships (then nested disconnects). */
2752
4355
  disconnect(block, from, rel, el) {
2753
4356
  if (!isPlainObject2(el)) return;
2754
4357
  const target = this.model.node(rel.target);
2755
- this.assertWritable(target);
4358
+ const source = this.model.node(rel.source);
4359
+ this.authenticate(target, "DELETE_RELATIONSHIP");
4360
+ this.authenticate(source, "DELETE_RELATIONSHIP");
2756
4361
  const inner = new Block();
2757
4362
  const t = this.ctx.variable("this");
2758
4363
  const r = this.ctx.variable("edge");
2759
- const pred = this.where.connection(r, t, rel, el.where);
2760
- inner.add(
2761
- `MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`
4364
+ const pred = and4([
4365
+ this.where.connection(r, t, rel, el.where),
4366
+ this.rules.filter(t, target, "DELETE_RELATIONSHIP")
4367
+ ]);
4368
+ const pattern = relationshipPattern(this.model, from, rel, t, r);
4369
+ const sourceBefore = this.rules.fails(from, source, "DELETE_RELATIONSHIP", "BEFORE");
4370
+ const targetOnNull = this.onNull(
4371
+ t,
4372
+ (n) => this.rules.failure([
4373
+ ...this.rules.validations(n, target, "DELETE_RELATIONSHIP", "BEFORE"),
4374
+ ...this.rules.validations(n, target, "DELETE_RELATIONSHIP", "AFTER")
4375
+ ])
4376
+ );
4377
+ this.capture(
4378
+ block,
4379
+ this.rules.check(
4380
+ orParts([
4381
+ sourceBefore,
4382
+ targetOnNull ? `(NOT EXISTS { MATCH ${pattern}${pred ? ` WHERE ${pred}` : ""} } AND ${targetOnNull})` : void 0
4383
+ ])
4384
+ )
4385
+ );
4386
+ inner.add(`MATCH ${pattern}${pred ? ` WHERE ${pred}` : ""}`);
4387
+ this.capture(
4388
+ inner,
4389
+ this.rules.check(this.rules.fails(t, target, "DELETE_RELATIONSHIP", "BEFORE"))
2762
4390
  );
2763
4391
  if (isPlainObject2(el.disconnect)) {
2764
4392
  for (const [name, els] of Object.entries(el.disconnect)) {
@@ -2769,7 +4397,24 @@ ${indent(inner.clauses)}
2769
4397
  if (inner.clauses.length > 1) inner.add("WITH *");
2770
4398
  inner.add(`DELETE ${r}`);
2771
4399
  inner.count("rd", "1");
4400
+ const targetAfter = this.rules.check(
4401
+ this.rules.fails(t, target, "DELETE_RELATIONSHIP", "AFTER")
4402
+ );
4403
+ if (targetAfter) inner.check([targetAfter]);
2772
4404
  this.call(block, [from], inner);
4405
+ this.capture(
4406
+ block,
4407
+ this.rules.check(this.rules.fails(from, source, "DELETE_RELATIONSHIP", "AFTER"))
4408
+ );
4409
+ }
4410
+ /**
4411
+ * `failure(n)` evaluated with `n` bound to `null` (`[n IN [null] | …][0]`), or `undefined` when there
4412
+ * are no rules: what v7's OPTIONAL MATCH checks when no node matched.
4413
+ */
4414
+ onNull(name, failure) {
4415
+ const n = this.ctx.variable(`${name}_null`);
4416
+ const f = failure(n);
4417
+ return f === void 0 ? void 0 : `[${n} IN [null] | ${f}][0]`;
2773
4418
  }
2774
4419
  // ---------------------------------------------------------------------------------------------
2775
4420
  // Delete
@@ -2779,8 +4424,7 @@ ${indent(inner.clauses)}
2779
4424
  * matching `where` and, through nested `delete`, nodes related to them. `match` is the chain of
2780
4425
  * `MATCH … WHERE …` that binds `t`.
2781
4426
  */
2782
- deleteLists(match, t, node, del) {
2783
- this.assertWritable(node);
4427
+ deleteLists(match, t, node, del, failures) {
2784
4428
  const lists = [`COLLECT { ${match} RETURN DISTINCT ${t} }`];
2785
4429
  if (!isPlainObject2(del)) return lists;
2786
4430
  for (const [name, els] of Object.entries(del)) {
@@ -2788,15 +4432,34 @@ ${indent(inner.clauses)}
2788
4432
  const target = this.model.node(rel.target);
2789
4433
  for (const el of asList(els)) {
2790
4434
  if (!isPlainObject2(el)) continue;
2791
- const u = this.ctx.variable("this");
2792
- const r = this.ctx.variable("edge");
2793
- const pred = this.where.connection(r, u, rel, el.where);
2794
- const chain = `${match} MATCH ${relationshipPattern(this.model, t, rel, u, r)}${pred ? ` WHERE ${pred}` : ""}`;
2795
- lists.push(...this.deleteLists(chain, u, target, el.delete));
4435
+ const { chain, u } = this.nestedDeleteMatch(match, t, rel, target, el, failures);
4436
+ lists.push(...this.deleteLists(chain, u, target, el.delete, failures));
2796
4437
  }
2797
4438
  }
2798
4439
  return lists;
2799
4440
  }
4441
+ /**
4442
+ * `MATCH` of a nested `{ where, delete }` from `t` (after `parent`, the chain binding `t`), with the
4443
+ * target's DELETE filter; pushes to `failures` the list of failed DELETE validations of the matched
4444
+ * nodes (v7: OPTIONAL MATCH, so the rules are also evaluated on `null` when nothing matches).
4445
+ */
4446
+ nestedDeleteMatch(parent, t, rel, target, el, failures) {
4447
+ this.authenticate(target, "DELETE");
4448
+ const u = this.ctx.variable("this");
4449
+ const r = this.ctx.variable("edge");
4450
+ const pred = and4([
4451
+ this.where.connection(r, u, rel, el.where),
4452
+ this.rules.filter(u, target, "DELETE")
4453
+ ]);
4454
+ const step = `${relationshipPattern(this.model, t, rel, u, r)}${pred ? ` WHERE ${pred}` : ""}`;
4455
+ const failure = this.rules.fails(u, target, "DELETE", "BEFORE");
4456
+ if (failure) {
4457
+ failures.push(
4458
+ `COLLECT { ${parent ? `${parent} ` : ""}OPTIONAL MATCH ${step} WITH * WHERE ${failure} RETURN ${this.rules.forbiddenMessage()} }`
4459
+ );
4460
+ }
4461
+ return { chain: `${parent ? `${parent} ` : ""}MATCH ${step}`, u };
4462
+ }
2800
4463
  /**
2801
4464
  * Deletes the distinct nodes of `list` with their relationships, counting both
2802
4465
  * (`WITH … AS deleted, COUNT { … } AS …`, then `FOREACH … DETACH DELETE`).
@@ -2819,13 +4482,18 @@ ${indent(inner.clauses)}
2819
4482
  nestedDelete(block, from, rel, el) {
2820
4483
  if (!isPlainObject2(el)) return;
2821
4484
  const target = this.model.node(rel.target);
2822
- const t = this.ctx.variable("this");
2823
- const r = this.ctx.variable("edge");
2824
- const pred = this.where.connection(r, t, rel, el.where);
2825
- const match = `MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`;
2826
- const lists = this.deleteLists(match, t, target, el.delete);
4485
+ const failures = [];
4486
+ const { chain, u } = this.nestedDeleteMatch("", from, rel, target, el, failures);
4487
+ const lists = this.deleteLists(chain, u, target, el.delete, failures);
2827
4488
  const inner = new Block();
2828
- this.deleteNodes(inner, `(${lists.join(" + ")})`, []);
4489
+ const keep = [];
4490
+ if (failures.length) {
4491
+ const f = this.ctx.variable("authDelete");
4492
+ inner.add(`WITH ${failures.join(" + ")} AS ${f}`);
4493
+ inner.errors.push(f);
4494
+ keep.push(f);
4495
+ }
4496
+ this.deleteNodes(inner, `(${lists.join(" + ")})`, keep);
2829
4497
  this.call(block, [from], inner);
2830
4498
  }
2831
4499
  // ---------------------------------------------------------------------------------------------
@@ -2835,7 +4503,7 @@ ${indent(inner.clauses)}
2835
4503
  * `WITH <nodes> AS nodes, <info>`, the projections of the response's node list (one per response
2836
4504
  * key) and the decoder of the `{ info, <plural> }` response.
2837
4505
  */
2838
- response(block, nodes, info, node, fieldNodes) {
4506
+ response(block, nodes, info, node, fieldNodes, readRules2) {
2839
4507
  const list2 = this.ctx.variable("nodes");
2840
4508
  block.add(`WITH ${nodes} AS ${list2}, ${info} AS info`);
2841
4509
  const entries = [];
@@ -2856,11 +4524,18 @@ ${indent(inner.clauses)}
2856
4524
  } else if (name === node.plural) {
2857
4525
  const v = this.ctx.variable("this");
2858
4526
  const d = this.ctx.variable("data");
2859
- const proj = this.select.projectNode(v, node, nodesOfKey);
4527
+ const auth = readRules2 ? this.select.readRules(v, node, nodesOfKey) : {};
4528
+ const scope = [];
4529
+ const proj = this.select.projectNode(v, node, nodesOfKey, scope);
4530
+ const value = auth.failure ? `CASE WHEN ${auth.failure} THEN ${this.select.forbiddenMap()} ELSE ${proj.expr} END` : proj.expr;
4531
+ const filter = auth.filter ? `
4532
+ WITH ${v} WHERE ${auth.filter}` : "";
4533
+ const clauses = scope.map((c) => `
4534
+ ${indent([c])}`).join("");
2860
4535
  block.add(
2861
4536
  `CALL (${list2}) {
2862
- UNWIND ${list2} AS ${v}
2863
- RETURN collect(${proj.expr}) AS ${d}
4537
+ UNWIND ${list2} AS ${v}${filter}${clauses}
4538
+ RETURN collect(${value}) AS ${d}
2864
4539
  }`
2865
4540
  );
2866
4541
  entries.push(`${q(key)}: ${d}`);
@@ -2874,28 +4549,30 @@ ${indent(inner.clauses)}
2874
4549
  }
2875
4550
  }
2876
4551
  const data = entries.length ? `{ ${entries.join(", ")} }` : "{}";
2877
- block.add(`RETURN { info: info, data: ${data} } AS this`);
4552
+ const gated = block.errors.length ? `CASE WHEN size(info.errors) = 0 THEN ${data} ELSE {} END` : data;
4553
+ block.add(`RETURN { info: info, data: ${gated} } AS this`);
2878
4554
  return {
2879
4555
  cypher: block.clauses.join("\n"),
2880
4556
  params: this.ctx.params,
2881
4557
  decode: (rows) => {
2882
4558
  const raw = rows[0] ?? {};
2883
4559
  const errors = (raw.info ?? {}).errors;
2884
- if (Array.isArray(errors) && errors.length) throw new GraphQLError3(String(errors[0]));
4560
+ if (Array.isArray(errors) && errors.length) throw new GraphQLError4(String(errors[0]));
2885
4561
  return Object.fromEntries(decoders.map(([k, dec]) => [k, dec(raw)]));
2886
4562
  }
2887
4563
  };
2888
4564
  }
2889
4565
  /** `createMovies(input: [...])`. */
2890
4566
  rootCreate(node, args, fieldNodes) {
2891
- this.assertWritable(node);
4567
+ this.authenticate(node, "CREATE");
2892
4568
  const block = new Block();
2893
4569
  const groups = [];
2894
4570
  const inputs = asList(args.input);
4571
+ const checked2 = this.hasCreateChecks(node);
2895
4572
  let i = 0;
2896
4573
  while (i < inputs.length) {
2897
4574
  let j = i;
2898
- while (j < inputs.length && !this.hasRelationshipInput(node, inputs[j])) j++;
4575
+ while (j < inputs.length && !checked2 && !this.hasRelationshipInput(node, inputs[j])) j++;
2899
4576
  if (j > i) {
2900
4577
  groups.push(this.createFlat(block, node, inputs.slice(i, j)));
2901
4578
  i = j;
@@ -2922,7 +4599,15 @@ ${indent(inner.clauses)}
2922
4599
  groups.length ? groups.join(" + ") : "[]",
2923
4600
  block.aggregate(false),
2924
4601
  node,
2925
- fieldNodes
4602
+ fieldNodes,
4603
+ false
4604
+ );
4605
+ }
4606
+ /** Whether creating `node` has `validate` rules or field-level `@authentication` to check. */
4607
+ hasCreateChecks(node) {
4608
+ const rules = [node.auth, ...node.attributes.map((a) => a.auth)];
4609
+ return rules.some(
4610
+ (a) => a?.authorization?.validate.some((r) => r.operations.includes("CREATE")) || a !== node.auth && a?.authentication !== void 0
2926
4611
  );
2927
4612
  }
2928
4613
  hasRelationshipInput(node, input) {
@@ -2930,6 +4615,7 @@ ${indent(inner.clauses)}
2930
4615
  }
2931
4616
  /** `UNWIND $rows AS row CREATE (n:Label) SET n.p = row.p, …` for inputs without relationships. */
2932
4617
  createFlat(block, node, inputs) {
4618
+ this.authenticate(node, "CREATE");
2933
4619
  const keys = /* @__PURE__ */ new Set();
2934
4620
  for (const input of inputs) {
2935
4621
  if (!isPlainObject2(input)) continue;
@@ -2967,12 +4653,22 @@ ${indent(lines)}
2967
4653
  }
2968
4654
  /** `updateMovies(where, update)`; without `update` it only reads (and refreshes UPDATE timestamps). */
2969
4655
  rootUpdate(node, args, fieldNodes) {
2970
- this.assertWritable(node);
4656
+ const written = this.writtenAttributes(node, args.update);
4657
+ this.authenticate(
4658
+ node,
4659
+ "UPDATE",
4660
+ written.map((a) => a.name)
4661
+ );
4662
+ const typeRules = written.length > 0;
2971
4663
  const block = new Block();
2972
4664
  const v = this.ctx.variable("this");
2973
- const pred = this.where.node(v, node, args.where);
4665
+ const pred = and4([
4666
+ this.where.node(v, node, args.where),
4667
+ typeRules ? this.rules.filter(v, node, "UPDATE") : void 0
4668
+ ]);
2974
4669
  block.add(`MATCH (${v}${labels(node.labels)})${pred ? `
2975
4670
  WHERE ${pred}` : ""}`);
4671
+ this.capture(block, this.updateCheck(v, node, "BEFORE", written, typeRules));
2976
4672
  const checks = [];
2977
4673
  const sets = [
2978
4674
  ...onUpdateGenerated(v, node.attributes),
@@ -2988,42 +4684,57 @@ WHERE ${pred}` : ""}`);
2988
4684
  if (sets.length) block.add(`SET ${sets.join(", ")}`);
2989
4685
  block.check(checks);
2990
4686
  this.updateRelationships(block, v, node, args.update);
2991
- return this.response(block, `collect(${v})`, block.aggregate(), node, fieldNodes);
4687
+ const after = this.updateCheck(v, node, "AFTER", written, typeRules);
4688
+ if (after) block.check([after]);
4689
+ return this.response(block, `collect(${v})`, block.aggregate(), node, fieldNodes, true);
2992
4690
  }
2993
4691
  /** `deleteMovies(where, delete)`: one `DeleteInfo`. */
2994
4692
  rootDelete(node, args, fieldNodes) {
2995
- this.assertWritable(node);
4693
+ this.authenticate(node, "DELETE");
2996
4694
  const block = new Block();
2997
4695
  const v = this.ctx.variable("this");
2998
- const pred = this.where.node(v, node, args.where);
4696
+ const pred = and4([this.where.node(v, node, args.where), this.rules.filter(v, node, "DELETE")]);
2999
4697
  block.add(`MATCH (${v}${labels(node.labels)})${pred ? `
3000
4698
  WHERE ${pred}` : ""}`);
3001
4699
  const roots = this.ctx.variable("roots");
3002
4700
  const nested = [];
4701
+ const failures = [];
4702
+ const rootFailure = this.rules.check(this.rules.fails(v, node, "DELETE", "BEFORE"));
3003
4703
  if (isPlainObject2(args.delete)) {
3004
4704
  for (const [name, els] of Object.entries(args.delete)) {
3005
4705
  const rel = this.relationship(node, name);
3006
4706
  const target = this.model.node(rel.target);
3007
4707
  for (const el of asList(els)) {
3008
4708
  if (!isPlainObject2(el)) continue;
3009
- const t = this.ctx.variable("this");
3010
- const r = this.ctx.variable("edge");
3011
- const p = this.where.connection(r, t, rel, el.where);
3012
- const match = `MATCH ${relationshipPattern(this.model, v, rel, t, r)}${p ? ` WHERE ${p}` : ""}`;
3013
- nested.push(...this.deleteLists(match, t, target, el.delete));
4709
+ const { chain, u } = this.nestedDeleteMatch("", v, rel, target, el, failures);
4710
+ nested.push(...this.deleteLists(chain, u, target, el.delete, failures));
3014
4711
  }
3015
4712
  }
3016
4713
  }
4714
+ const errorParts = [
4715
+ ...rootFailure ? [`collect(${rootFailure})`] : [],
4716
+ ...failures.length ? [`reduce(acc = [], l IN collect(${failures.join(" + ")}) | acc + l)`] : []
4717
+ ];
4718
+ const keep = [];
4719
+ let errors;
4720
+ if (errorParts.length) {
4721
+ errors = this.ctx.variable("authErrors");
4722
+ keep.push(errors);
4723
+ }
4724
+ const errorsItem = errors ? `, ${errorParts.join(" + ")} AS ${errors}` : "";
3017
4725
  let list2;
3018
4726
  if (nested.length) {
3019
4727
  const related = this.ctx.variable("related");
3020
- block.add(`WITH collect(${v}) AS ${roots}, collect(${nested.join(" + ")}) AS ${related}`);
4728
+ block.add(
4729
+ `WITH collect(${v}) AS ${roots}, collect(${nested.join(" + ")}) AS ${related}${errorsItem}`
4730
+ );
3021
4731
  list2 = `(${roots} + reduce(acc = [], l IN ${related} | acc + l))`;
3022
4732
  } else {
3023
- block.add(`WITH collect(${v}) AS ${roots}`);
4733
+ block.add(`WITH collect(${v}) AS ${roots}${errorsItem}`);
3024
4734
  list2 = roots;
3025
4735
  }
3026
- this.deleteNodes(block, list2, []);
4736
+ this.deleteNodes(block, list2, keep);
4737
+ if (errors) block.errors.push(errors);
3027
4738
  const fields = [...collectFields(this.info, subSelections(fieldNodes))].map(
3028
4739
  ([k, n]) => [k, n[0].name.value]
3029
4740
  );
@@ -3033,21 +4744,36 @@ WHERE ${pred}` : ""}`);
3033
4744
  params: this.ctx.params,
3034
4745
  decode: (rows) => {
3035
4746
  const counts = rows[0] ?? {};
4747
+ const errors2 = counts.errors;
4748
+ if (Array.isArray(errors2) && errors2.length) throw new GraphQLError4(String(errors2[0]));
3036
4749
  return decodeCounts(fields, counts);
3037
4750
  }
3038
4751
  };
3039
4752
  }
3040
4753
  };
4754
+ function and4(parts) {
4755
+ const ps = parts.filter((p) => p !== void 0);
4756
+ if (ps.length === 0) return void 0;
4757
+ if (ps.length === 1) return ps[0];
4758
+ return ps.map((p) => `(${p})`).join(" AND ");
4759
+ }
4760
+ function orParts(parts) {
4761
+ const ps = parts.filter((p) => p !== void 0);
4762
+ if (ps.length === 0) return void 0;
4763
+ if (ps.length === 1) return ps[0];
4764
+ return ps.map((p) => `(${p})`).join(" OR ");
4765
+ }
3041
4766
  var intAttribute = {
3042
4767
  name: "pop",
3043
4768
  property: "pop",
3044
4769
  type: { name: "Int", list: false, required: true, elementRequired: false },
3045
4770
  kind: "scalar",
3046
- id: false
4771
+ id: false,
4772
+ args: []
3047
4773
  };
3048
4774
 
3049
4775
  // src/v7/execute.ts
3050
- import neo4j3 from "neo4j-driver";
4776
+ import neo4j4 from "neo4j-driver";
3051
4777
  function createExecutors(opts) {
3052
4778
  const log = (cypher, params) => {
3053
4779
  if (opts.debug)
@@ -3056,14 +4782,27 @@ function createExecutors(opts) {
3056
4782
  const rows = async (tx, cypher, params) => (await tx.run(cypher, params)).records.map((r) => r.get("this"));
3057
4783
  if (opts.client) {
3058
4784
  const client = opts.client;
4785
+ const clientRows = async (tx, cypher, params, op) => (await client.runCompiledTx(
4786
+ tx,
4787
+ { text: cypher, params },
4788
+ { operation: op, transaction: false }
4789
+ )).records.map((r) => r.get("this"));
3059
4790
  return {
3060
4791
  read: async (cypher, params) => {
3061
4792
  log(cypher, params);
3062
- return client.withReadTransaction((tx) => rows(tx, cypher, params));
4793
+ return client.instrumentation.operation(
4794
+ { operation: "graphql.read" },
4795
+ () => client.withReadTransaction((tx) => clientRows(tx, cypher, params, "graphql.read"))
4796
+ );
3063
4797
  },
3064
4798
  write: async (cypher, params, consume) => {
3065
4799
  log(cypher, params);
3066
- return client.withWriteTransaction(async (tx) => consume(await rows(tx, cypher, params)));
4800
+ return client.instrumentation.operation(
4801
+ { operation: "graphql.write" },
4802
+ () => client.withWriteTransaction(
4803
+ async (tx) => consume(await clientRows(tx, cypher, params, "graphql.write"))
4804
+ )
4805
+ );
3067
4806
  }
3068
4807
  };
3069
4808
  }
@@ -3072,7 +4811,7 @@ function createExecutors(opts) {
3072
4811
  const withSession = async (mode, fn) => {
3073
4812
  const session = driver.session({
3074
4813
  database: opts.database,
3075
- defaultAccessMode: neo4j3.session[mode]
4814
+ defaultAccessMode: neo4j4.session[mode]
3076
4815
  });
3077
4816
  try {
3078
4817
  return await fn(session);
@@ -3114,8 +4853,8 @@ import {
3114
4853
  } from "graphql";
3115
4854
 
3116
4855
  // src/v7/scalars.ts
3117
- import { GraphQLError as GraphQLError4, GraphQLScalarType, Kind as Kind5 } from "graphql";
3118
- import neo4j4, { isDate, isDateTime, isInt as isInt3 } from "neo4j-driver";
4856
+ import { GraphQLError as GraphQLError5, GraphQLScalarType, Kind as Kind5 } from "graphql";
4857
+ import neo4j5, { isDate, isDateTime, isInt as isInt3 } from "neo4j-driver";
3119
4858
  var GraphQLBigInt = new GraphQLScalarType({
3120
4859
  name: "BigInt",
3121
4860
  description: "A BigInt value up to 64 bits in size, which can be a number or a string if used inline, or a string only if used as a variable. Always returned as a string.",
@@ -3123,18 +4862,18 @@ var GraphQLBigInt = new GraphQLScalarType({
3123
4862
  if (isInt3(value)) return value.toString(10);
3124
4863
  if (typeof value === "string") return value;
3125
4864
  if (typeof value === "number" || typeof value === "bigint") return value.toString(10);
3126
- throw new GraphQLError4(`BigInt cannot represent value: ${String(value)}`);
4865
+ throw new GraphQLError5(`BigInt cannot represent value: ${String(value)}`);
3127
4866
  },
3128
4867
  parseValue(value) {
3129
4868
  if (typeof value !== "string") {
3130
- throw new GraphQLError4(
4869
+ throw new GraphQLError5(
3131
4870
  "BigInt values are not JSON serializable. Please pass as a string in variables, or inline in the GraphQL query."
3132
4871
  );
3133
4872
  }
3134
4873
  try {
3135
- return neo4j4.int(value, { strictStringValidation: true });
4874
+ return neo4j5.int(value, { strictStringValidation: true });
3136
4875
  } catch {
3137
- throw new GraphQLError4(
4876
+ throw new GraphQLError5(
3138
4877
  "Value must be either a BigInt, or a string representing a BigInt value."
3139
4878
  );
3140
4879
  }
@@ -3142,11 +4881,11 @@ var GraphQLBigInt = new GraphQLScalarType({
3142
4881
  parseLiteral(ast) {
3143
4882
  if (ast.kind === Kind5.INT || ast.kind === Kind5.STRING) {
3144
4883
  try {
3145
- return neo4j4.int(ast.value, { strictStringValidation: true });
4884
+ return neo4j5.int(ast.value, { strictStringValidation: true });
3146
4885
  } catch {
3147
4886
  }
3148
4887
  }
3149
- throw new GraphQLError4(
4888
+ throw new GraphQLError5(
3150
4889
  "Value must be either a BigInt, or a string representing a BigInt value."
3151
4890
  );
3152
4891
  }
@@ -3158,22 +4897,22 @@ var GraphQLDate = new GraphQLScalarType({
3158
4897
  serialize(value) {
3159
4898
  if (typeof value === "string") return formatDate(value);
3160
4899
  if (isDate(value)) return formatDate(String(value));
3161
- throw new GraphQLError4(`Date cannot represent value: ${String(value)}`);
4900
+ throw new GraphQLError5(`Date cannot represent value: ${String(value)}`);
3162
4901
  },
3163
4902
  parseValue(value) {
3164
4903
  if (typeof value === "string") {
3165
4904
  const d = new Date(value);
3166
4905
  if (Number.isNaN(d.getTime())) {
3167
- throw new GraphQLError4(`Date cannot represent non temporal value: ${value}`);
4906
+ throw new GraphQLError5(`Date cannot represent non temporal value: ${value}`);
3168
4907
  }
3169
- return neo4j4.types.Date.fromStandardDate(d);
4908
+ return neo4j5.types.Date.fromStandardDate(d);
3170
4909
  }
3171
4910
  if (isDate(value)) return value;
3172
- throw new GraphQLError4(`Date cannot represent non string value: ${String(value)}`);
4911
+ throw new GraphQLError5(`Date cannot represent non string value: ${String(value)}`);
3173
4912
  },
3174
4913
  parseLiteral(ast) {
3175
- if (ast.kind !== Kind5.STRING) throw new GraphQLError4("Date cannot represent non string value.");
3176
- return neo4j4.types.Date.fromStandardDate(new Date(ast.value));
4914
+ if (ast.kind !== Kind5.STRING) throw new GraphQLError5("Date cannot represent non string value.");
4915
+ return neo4j5.types.Date.fromStandardDate(new Date(ast.value));
3177
4916
  }
3178
4917
  });
3179
4918
  var GraphQLDateTime = new GraphQLScalarType({
@@ -3183,20 +4922,20 @@ var GraphQLDateTime = new GraphQLScalarType({
3183
4922
  if (typeof value === "string") return new Date(value).toISOString();
3184
4923
  if (isDateTime(value)) return new Date(String(value)).toISOString();
3185
4924
  if (value instanceof Date) return value.toISOString();
3186
- throw new GraphQLError4(`DateTime cannot represent value: ${String(value)}`);
4925
+ throw new GraphQLError5(`DateTime cannot represent value: ${String(value)}`);
3187
4926
  },
3188
4927
  parseValue(value) {
3189
4928
  if (typeof value === "string") {
3190
4929
  if (Number.isNaN(new Date(value).getTime())) {
3191
- throw new GraphQLError4(`DateTime cannot represent non temporal value: ${value}`);
4930
+ throw new GraphQLError5(`DateTime cannot represent non temporal value: ${value}`);
3192
4931
  }
3193
4932
  return value;
3194
4933
  }
3195
- throw new GraphQLError4(`DateTime cannot represent non string value: ${String(value)}`);
4934
+ throw new GraphQLError5(`DateTime cannot represent non string value: ${String(value)}`);
3196
4935
  },
3197
4936
  parseLiteral(ast) {
3198
4937
  if (ast.kind !== Kind5.STRING)
3199
- throw new GraphQLError4("DateTime cannot represent non string value.");
4938
+ throw new GraphQLError5("DateTime cannot represent non string value.");
3200
4939
  return ast.value;
3201
4940
  }
3202
4941
  });
@@ -3562,7 +5301,7 @@ var TypeRegistry = class {
3562
5301
  attributeWhereFields(attributes) {
3563
5302
  const out = {};
3564
5303
  for (const a of attributes) {
3565
- if (a.cypher && a.type.list) continue;
5304
+ if (a.args.length) continue;
3566
5305
  out[a.name] = { type: this.scalarFilters(a), deprecationReason: a.deprecated };
3567
5306
  const named = this.namedType(a.type.name);
3568
5307
  const dep = (op) => a.deprecated ?? `Please use the relevant generic filter ${a.name}: { ${op}: ... }`;
@@ -3706,7 +5445,9 @@ ${users.join("\n")}`
3706
5445
  propertiesSort(p) {
3707
5446
  return this.input(
3708
5447
  `${p.name}Sort`,
3709
- () => Object.fromEntries(p.attributes.map((a) => [a.name, { type: this.sortDirection() }]))
5448
+ () => Object.fromEntries(
5449
+ p.attributes.filter((a) => !a.args.length).map((a) => [a.name, { type: this.sortDirection() }])
5450
+ )
3710
5451
  );
3711
5452
  }
3712
5453
  propertiesCreate(p) {
@@ -3738,6 +5479,14 @@ ${users.join("\n")}`
3738
5479
  n.name,
3739
5480
  () => {
3740
5481
  const fields = attributeOutputFields(this, n.attributes);
5482
+ for (const c of n.cypherNodes) {
5483
+ fields[c.name] = {
5484
+ type: this.nodeRefType(c.type, c.target),
5485
+ description: c.description,
5486
+ deprecationReason: c.deprecated,
5487
+ args: argumentConfigs(this, c.args)
5488
+ };
5489
+ }
3741
5490
  for (const r of n.relationships) {
3742
5491
  const target = this.model.node(r.target);
3743
5492
  fields[r.name] = {
@@ -3771,7 +5520,7 @@ ${users.join("\n")}`
3771
5520
  return this.input(
3772
5521
  `${n.name}Sort`,
3773
5522
  () => Object.fromEntries(
3774
- n.attributes.filter((a) => !a.type.list).map((a) => [a.name, { type: this.sortDirection() }])
5523
+ n.attributes.filter((a) => !a.type.list && !a.args.length).map((a) => [a.name, { type: this.sortDirection() }])
3775
5524
  ),
3776
5525
  `Fields to sort ${n.pascalPlural} by. The order in which sorts are applied is not guaranteed when specifying many fields in one ${n.name}Sort object.`
3777
5526
  );
@@ -3785,6 +5534,17 @@ ${users.join("\n")}`
3785
5534
  OR: { type: list(nn(self)) },
3786
5535
  ...this.attributeWhereFields(n.attributes)
3787
5536
  };
5537
+ for (const c of n.cypherNodes) {
5538
+ if (c.args.length) continue;
5539
+ const target = this.model.node(c.target);
5540
+ if (!c.type.list) {
5541
+ out[c.name] = { type: this.nodeWhere(target) };
5542
+ continue;
5543
+ }
5544
+ out[c.name] = { type: this.relationshipFilters(target) };
5545
+ for (const q2 of QUANTIFIERS)
5546
+ out[`${c.name}_${q2.toUpperCase()}`] = { type: this.nodeWhere(target) };
5547
+ }
3788
5548
  const sourcePlural = pluralize(n.name);
3789
5549
  for (const r of n.relationships) {
3790
5550
  const target = this.model.node(r.target);
@@ -3828,6 +5588,67 @@ ${users.join("\n")}`
3828
5588
  );
3829
5589
  });
3830
5590
  }
5591
+ /** `Movie`, `[Movie!]!`, … for a field returning nodes. */
5592
+ nodeRefType(t, target) {
5593
+ const named = this.node(this.model.node(target));
5594
+ if (t.list) {
5595
+ const inner = list(t.elementRequired ? nn(named) : named);
5596
+ return t.required ? nn(inner) : inner;
5597
+ }
5598
+ return t.required ? nn(named) : named;
5599
+ }
5600
+ /** The type of a `Query` / `Mutation` `@cypher` field. */
5601
+ rootFieldType(f) {
5602
+ return f.kind === "node" ? this.nodeRefType(f.type, f.type.name) : this.attributeType(f.type);
5603
+ }
5604
+ floatWhere() {
5605
+ return this.input(
5606
+ "FloatWhere",
5607
+ () => ({ max: { type: GraphQLFloat }, min: { type: GraphQLFloat } }),
5608
+ "The input for filtering a float"
5609
+ );
5610
+ }
5611
+ fulltextEdge(n) {
5612
+ return this.object(`${n.name}IndexEdge`, () => ({
5613
+ cursor: { type: nn(GraphQLString) },
5614
+ node: { type: nn(this.node(n)) },
5615
+ score: { type: nn(GraphQLFloat) }
5616
+ }));
5617
+ }
5618
+ fulltextConnection(n) {
5619
+ return this.object(`${n.pascalPlural}IndexConnection`, () => ({
5620
+ edges: { type: nn(list(nn(this.fulltextEdge(n)))) },
5621
+ pageInfo: { type: nn(this.pageInfo()) },
5622
+ totalCount: { type: nn(GraphQLInt) }
5623
+ }));
5624
+ }
5625
+ fulltextSort(n) {
5626
+ return this.input(
5627
+ `${n.name}IndexSort`,
5628
+ () => ({ node: { type: this.nodeSort(n) }, score: { type: this.sortDirection() } }),
5629
+ `The input for sorting a Fulltext query on an index of ${n.name}`
5630
+ );
5631
+ }
5632
+ fulltextWhere(n) {
5633
+ return this.input(
5634
+ `${n.name}IndexWhere`,
5635
+ () => ({ node: { type: this.nodeWhere(n) }, score: { type: this.floatWhere() } }),
5636
+ `The input for filtering a full-text query on an index of ${n.name}`
5637
+ );
5638
+ }
5639
+ /** `moviesByTitle(phrase, where, sort, first, after)`. */
5640
+ fulltextField(n) {
5641
+ return {
5642
+ type: nn(this.fulltextConnection(n)),
5643
+ args: {
5644
+ after: { type: GraphQLString },
5645
+ first: { type: GraphQLInt },
5646
+ phrase: { type: nn(GraphQLString) },
5647
+ sort: { type: list(nn(this.fulltextSort(n))) },
5648
+ where: { type: this.fulltextWhere(n) }
5649
+ }
5650
+ };
5651
+ }
3831
5652
  nodeAggregate(n) {
3832
5653
  return this.object(`${n.name}Aggregate`, () => {
3833
5654
  const fields = { count: { type: nn(this.count()) } };
@@ -4130,18 +5951,40 @@ function relationshipType(reg, r) {
4130
5951
  }
4131
5952
  return r.required ? nn(target) : target;
4132
5953
  }
5954
+ function argumentConfigs(reg, args) {
5955
+ if (!args.length) return void 0;
5956
+ const out = {};
5957
+ for (const a of args) {
5958
+ const type = reg.attributeType(a.type);
5959
+ out[a.name] = {
5960
+ type,
5961
+ description: a.description,
5962
+ defaultValue: a.defaultAst ? valueFromAST(a.defaultAst, type) : void 0
5963
+ };
5964
+ }
5965
+ return out;
5966
+ }
4133
5967
  function attributeOutputFields(reg, attributes) {
4134
5968
  const out = {};
4135
5969
  for (const a of attributes) {
4136
5970
  const field = {
4137
5971
  type: reg.attributeType(a.type),
4138
5972
  description: a.description,
4139
- deprecationReason: a.deprecated
5973
+ deprecationReason: a.deprecated,
5974
+ args: argumentConfigs(reg, a.args)
4140
5975
  };
4141
5976
  out[a.name] = field;
4142
5977
  }
4143
5978
  return out;
4144
5979
  }
5980
+ function rootField(reg, f) {
5981
+ return {
5982
+ type: reg.rootFieldType(f),
5983
+ description: f.description,
5984
+ deprecationReason: f.deprecated,
5985
+ args: argumentConfigs(reg, f.args)
5986
+ };
5987
+ }
4145
5988
  function aggregateSelectionFields(reg, attributes) {
4146
5989
  return Object.fromEntries(
4147
5990
  attributes.filter(isAggregable).map((a) => [a.name, { type: nn(reg.aggregateSelection(a.type.name)) }])
@@ -4179,7 +6022,9 @@ function buildV7Schema(model) {
4179
6022
  where: { type: reg.nodeWhere(n) }
4180
6023
  }
4181
6024
  };
6025
+ for (const ft of n.fulltext) fields[ft.queryName] = reg.fulltextField(n);
4182
6026
  }
6027
+ for (const f of model.query.fields) fields[f.name] = rootField(reg, f);
4183
6028
  return fields;
4184
6029
  }
4185
6030
  });
@@ -4208,32 +6053,177 @@ function buildV7Schema(model) {
4208
6053
  }
4209
6054
  };
4210
6055
  }
6056
+ for (const f of model.mutation.fields) fields[f.name] = rootField(reg, f);
4211
6057
  return fields;
4212
6058
  }
4213
6059
  });
4214
6060
  return new GraphQLSchema({ query, mutation });
4215
6061
  }
4216
6062
 
6063
+ // src/v7/auth/jwt.ts
6064
+ import {
6065
+ createRemoteJWKSet,
6066
+ decodeJwt,
6067
+ jwtVerify
6068
+ } from "jose";
6069
+ var MAX_REMOTE_SETS = 64;
6070
+ function parseBearerToken(value) {
6071
+ if (!value.startsWith("Bearer ")) return value || void 0;
6072
+ return value.split("Bearer ")[1] || void 0;
6073
+ }
6074
+ var JwtDecoder = class {
6075
+ constructor(feature) {
6076
+ this.feature = feature;
6077
+ if (typeof feature.key !== "function") this.staticKey = this.resolve(feature.key);
6078
+ }
6079
+ feature;
6080
+ staticKey;
6081
+ remoteSets = /* @__PURE__ */ new Map();
6082
+ resolve(key) {
6083
+ if (typeof key === "string") return new TextEncoder().encode(key);
6084
+ if (!key || typeof key.url !== "string") {
6085
+ throw new TypeError(
6086
+ "@cyphra/graphql: features.authorization.key must be a string or { url }."
6087
+ );
6088
+ }
6089
+ let set = this.remoteSets.get(key.url);
6090
+ if (!set) {
6091
+ set = createRemoteJWKSet(new URL(key.url), key.options);
6092
+ if (this.remoteSets.size >= MAX_REMOTE_SETS) {
6093
+ this.remoteSets.delete(this.remoteSets.keys().next().value);
6094
+ }
6095
+ this.remoteSets.set(key.url, set);
6096
+ }
6097
+ return set;
6098
+ }
6099
+ /** The payload, or `undefined` when there is no token or it is not valid. */
6100
+ async decode(context) {
6101
+ const raw = context.token;
6102
+ if (typeof raw !== "string" || !raw) return void 0;
6103
+ const token = parseBearerToken(raw);
6104
+ if (!token) return void 0;
6105
+ try {
6106
+ if (this.feature.verify === false) return decodeJwt(token);
6107
+ const key = this.staticKey ?? this.resolve(this.feature.key(context));
6108
+ const { payload } = key instanceof Uint8Array ? await jwtVerify(token, key, this.feature.verifyOptions) : await jwtVerify(token, key, this.feature.verifyOptions);
6109
+ return payload;
6110
+ } catch {
6111
+ return void 0;
6112
+ }
6113
+ }
6114
+ };
6115
+
4217
6116
  // src/v7/index.ts
4218
6117
  var byResponseKey = (source, _args, _ctx, info) => source && typeof source === "object" ? source[info.path.key] : void 0;
4219
- function rootReadResolver(model, execute, nodeName, kind) {
4220
- return async (_source, args, _ctx, info) => {
6118
+ function withCypherParams(params, ctx) {
6119
+ const extra = ctx && typeof ctx === "object" ? ctx.cypherParams : void 0;
6120
+ if (extra === void 0 || extra === null) return params;
6121
+ if (typeof extra !== "object" || Array.isArray(extra)) {
6122
+ throw new GraphQLError6("context.cypherParams must be an object.");
6123
+ }
6124
+ const clash = Object.keys(extra).filter((k) => Object.prototype.hasOwnProperty.call(params, k));
6125
+ if (clash.length) {
6126
+ throw new GraphQLError6(
6127
+ `Duplicate parameter keys between context.cypherParams and generated parameters: [${clash.join(", ")}]`
6128
+ );
6129
+ }
6130
+ return { ...extra, ...params };
6131
+ }
6132
+ function checked(decode) {
6133
+ return (rows) => {
6134
+ if (containsForbidden(rows)) throw forbidden();
6135
+ return decode(rows);
6136
+ };
6137
+ }
6138
+ function rootReadResolver({ model, decoder }, execute, nodeName, kind) {
6139
+ return async (_source, args, ctx, info) => {
4221
6140
  const node = model.node(nodeName);
4222
- const compiler = new SelectionCompiler(model, info);
6141
+ const auth = await authContextFor(ctx, model, decoder);
6142
+ const compiler = new SelectionCompiler(model, info, auth);
4223
6143
  const compiled = kind === "list" ? compiler.rootList(node, args, info.fieldNodes) : compiler.rootConnection(node, args, info.fieldNodes);
4224
- return compiled.decode(await execute(compiled.cypher, compiled.params));
6144
+ return checked(compiled.decode)(
6145
+ await execute(compiled.cypher, withCypherParams(compiled.params, ctx))
6146
+ );
6147
+ };
6148
+ }
6149
+ function fulltextResolver({ model, decoder }, execute, nodeName, queryName) {
6150
+ return async (_source, args, ctx, info) => {
6151
+ const node = model.node(nodeName);
6152
+ const index = node.fulltext.find((f) => f.queryName === queryName);
6153
+ const auth = await authContextFor(ctx, model, decoder);
6154
+ const compiled = new SelectionCompiler(model, info, auth).rootFulltext(
6155
+ node,
6156
+ index,
6157
+ args,
6158
+ info.fieldNodes
6159
+ );
6160
+ return checked(compiled.decode)(
6161
+ await execute(compiled.cypher, withCypherParams(compiled.params, ctx))
6162
+ );
6163
+ };
6164
+ }
6165
+ function rootCypherResolver({ model, decoder }, executors, type, fieldName) {
6166
+ return async (_source, args, ctx, info) => {
6167
+ const field = (type === "Query" ? model.query : model.mutation).fields.find(
6168
+ (f) => f.name === fieldName
6169
+ );
6170
+ const auth = await authContextFor(ctx, model, decoder);
6171
+ checkRootAuthentication(model, auth, type, field);
6172
+ const compiled = new SelectionCompiler(model, info, auth).rootCypher(
6173
+ field,
6174
+ args,
6175
+ info.fieldNodes
6176
+ );
6177
+ const params = withCypherParams(compiled.params, ctx);
6178
+ if (type === "Query")
6179
+ return checked(compiled.decode)(await executors.read(compiled.cypher, params));
6180
+ return executors.write(compiled.cypher, params, checked(compiled.decode));
4225
6181
  };
4226
6182
  }
4227
- function rootMutationResolver(model, execute, nodeName, kind) {
4228
- return async (_source, args, _ctx, info) => {
6183
+ function rootMutationResolver({ model, decoder }, execute, nodeName, kind) {
6184
+ return async (_source, args, ctx, info) => {
4229
6185
  const node = model.node(nodeName);
4230
- const compiler = new MutationCompiler(model, info);
6186
+ const auth = await authContextFor(ctx, model, decoder);
6187
+ const compiler = new MutationCompiler(model, info, auth);
4231
6188
  const a = args;
4232
6189
  const compiled = kind === "create" ? compiler.rootCreate(node, a, info.fieldNodes) : kind === "update" ? compiler.rootUpdate(node, a, info.fieldNodes) : compiler.rootDelete(node, a, info.fieldNodes);
4233
- return execute(compiled.cypher, compiled.params, compiled.decode);
6190
+ return execute(
6191
+ compiled.cypher,
6192
+ withCypherParams(compiled.params, ctx),
6193
+ checked(compiled.decode)
6194
+ );
6195
+ };
6196
+ }
6197
+ function checkRules(model) {
6198
+ const auth = {
6199
+ isAuthenticated: false,
6200
+ jwt: void 0,
6201
+ claims: void 0,
6202
+ context: {}
4234
6203
  };
6204
+ for (const node of model.nodes) {
6205
+ for (const attr of [void 0, ...node.attributes]) {
6206
+ const annotation = attr ? attr.auth : node.auth;
6207
+ if (!annotation?.authorization) continue;
6208
+ const target = attr ? { ...node, auth: {} } : node;
6209
+ const attrs = attr ? [attr] : [];
6210
+ try {
6211
+ const rules = new AuthRules(model, new CypherContext(), auth);
6212
+ for (const op of AUTH_OPERATIONS) {
6213
+ rules.filter("this", target, op, attrs);
6214
+ rules.validations("this", target, op, "BEFORE", attrs);
6215
+ rules.validations("this", target, op, "AFTER", attrs);
6216
+ }
6217
+ } catch (e) {
6218
+ throw new UnsupportedTypeDefsError(
6219
+ `${node.name}${attr ? `.${attr.name}` : ""}: invalid @authorization rule: ${e.message}`
6220
+ );
6221
+ }
6222
+ }
6223
+ }
4235
6224
  }
4236
- function attachResolvers(schema, model, executors) {
6225
+ function attachResolvers(schema, auth, executors) {
6226
+ const model = auth.model;
4237
6227
  const execute = executors.read;
4238
6228
  for (const type of Object.values(schema.getTypeMap())) {
4239
6229
  if (!isObjectType(type) || type.name.startsWith("__")) continue;
@@ -4242,19 +6232,28 @@ function attachResolvers(schema, model, executors) {
4242
6232
  }
4243
6233
  const query = schema.getQueryType().getFields();
4244
6234
  for (const node of model.nodes) {
4245
- query[node.plural].resolve = rootReadResolver(model, execute, node.name, "list");
6235
+ query[node.plural].resolve = rootReadResolver(auth, execute, node.name, "list");
4246
6236
  query[`${node.plural}Connection`].resolve = rootReadResolver(
4247
- model,
6237
+ auth,
4248
6238
  execute,
4249
6239
  node.name,
4250
6240
  "connection"
4251
6241
  );
6242
+ for (const ft of node.fulltext) {
6243
+ query[ft.queryName].resolve = fulltextResolver(auth, execute, node.name, ft.queryName);
6244
+ }
6245
+ }
6246
+ for (const f of model.query.fields) {
6247
+ query[f.name].resolve = rootCypherResolver(auth, executors, "Query", f.name);
4252
6248
  }
4253
6249
  const mutation = schema.getMutationType().getFields();
6250
+ for (const f of model.mutation.fields) {
6251
+ mutation[f.name].resolve = rootCypherResolver(auth, executors, "Mutation", f.name);
6252
+ }
4254
6253
  for (const node of model.nodes) {
4255
6254
  for (const kind of ["create", "update", "delete"]) {
4256
6255
  mutation[`${kind}${node.pascalPlural}`].resolve = rootMutationResolver(
4257
- model,
6256
+ auth,
4258
6257
  executors.write,
4259
6258
  node.name,
4260
6259
  kind
@@ -4264,12 +6263,15 @@ function attachResolvers(schema, model, executors) {
4264
6263
  }
4265
6264
  function makeSchema(options) {
4266
6265
  const model = readTypeDefs(options.typeDefs);
6266
+ checkRules(model);
4267
6267
  const schema = buildV7Schema(model);
4268
- attachResolvers(schema, model, createExecutors(options));
6268
+ const feature = options.features?.authorization;
6269
+ const decoder = feature ? new JwtDecoder(feature) : void 0;
6270
+ attachResolvers(schema, { model, decoder }, createExecutors(options));
4269
6271
  return schema;
4270
6272
  }
4271
6273
  function contextFor(opts = {}) {
4272
- return opts.jwt ? { jwt: opts.jwt } : {};
6274
+ return Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== void 0));
4273
6275
  }
4274
6276
  function cyphraSchema(typeDefs) {
4275
6277
  const { document, issues } = convertGraphQLTypeDefs([