@cyphra/graphql 0.6.0 → 0.8.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/README.md +26 -2
- package/dist/index.d.ts +159 -15
- package/dist/index.js +2572 -597
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
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,7 +31,7 @@ import {
|
|
|
30
31
|
} from "graphql";
|
|
31
32
|
|
|
32
33
|
// src/import/mappings.ts
|
|
33
|
-
import { Kind } from "graphql";
|
|
34
|
+
import { Kind, valueFromASTUntyped } from "graphql";
|
|
34
35
|
var NOT_YET = "is not supported by Cyphra yet";
|
|
35
36
|
var SCALARS = {
|
|
36
37
|
ID: { type: "String" },
|
|
@@ -40,7 +41,7 @@ var SCALARS = {
|
|
|
40
41
|
Boolean: { type: "Boolean" },
|
|
41
42
|
DateTime: { type: "DateTime" },
|
|
42
43
|
Date: { type: "Date" },
|
|
43
|
-
BigInt: {
|
|
44
|
+
BigInt: { type: "BigInt" },
|
|
44
45
|
Time: { unsupported: `Time ${NOT_YET}` },
|
|
45
46
|
LocalTime: { unsupported: `LocalTime ${NOT_YET}` },
|
|
46
47
|
LocalDateTime: { unsupported: `LocalDateTime ${NOT_YET}` },
|
|
@@ -48,9 +49,12 @@ var SCALARS = {
|
|
|
48
49
|
Point: { unsupported: `Point ${NOT_YET}` },
|
|
49
50
|
CartesianPoint: { unsupported: `CartesianPoint ${NOT_YET}` }
|
|
50
51
|
};
|
|
51
|
-
|
|
52
|
+
function enumField(name) {
|
|
53
|
+
return { type: "Enum", enum: name };
|
|
54
|
+
}
|
|
55
|
+
var ENUM_AS_STRING = {
|
|
52
56
|
type: "String",
|
|
53
|
-
note: "
|
|
57
|
+
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
58
|
};
|
|
55
59
|
var CUSTOM_SCALAR_FIELD = {
|
|
56
60
|
unsupported: "custom scalars are not supported by Cyphra"
|
|
@@ -60,6 +64,14 @@ var UNIQUE = { name: "unique", args: [] };
|
|
|
60
64
|
function defaultFn(fn) {
|
|
61
65
|
return { name: "default", args: [{ key: "fn", value: { kind: "identifier", value: fn } }] };
|
|
62
66
|
}
|
|
67
|
+
function defaultEnum(value) {
|
|
68
|
+
return { name: "default", args: [{ key: "value", value: { kind: "identifier", value } }] };
|
|
69
|
+
}
|
|
70
|
+
function defaultBigInt(digits) {
|
|
71
|
+
const value = Number(digits);
|
|
72
|
+
const v = Number.isSafeInteger(value) ? { kind: "number", value } : { kind: "number", value, raw: digits };
|
|
73
|
+
return { name: "default", args: [{ key: "value", value: v }] };
|
|
74
|
+
}
|
|
63
75
|
function defaultLiteral(value) {
|
|
64
76
|
const v = typeof value === "string" ? { kind: "string", value } : typeof value === "number" ? { kind: "number", value } : { kind: "boolean", value };
|
|
65
77
|
return { name: "default", args: [{ key: "value", value: v }] };
|
|
@@ -78,13 +90,21 @@ function enumListArg(d, name) {
|
|
|
78
90
|
return items.flatMap((i) => i.kind === Kind.ENUM || i.kind === Kind.STRING ? [i.value] : []);
|
|
79
91
|
}
|
|
80
92
|
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
|
|
93
|
+
var AUTH = "authorization rules are not part of a Cyphra schema: compat.v7 still applies them; enforce them yourself around the typed client";
|
|
82
94
|
function issue(severity, feature, message) {
|
|
83
95
|
return { severity, feature, message };
|
|
84
96
|
}
|
|
85
97
|
function defaultFromValue(v, ctx) {
|
|
86
98
|
if (ctx.list) return { error: "Cyphra has no defaults for list fields" };
|
|
87
99
|
switch (ctx.type) {
|
|
100
|
+
case "Enum":
|
|
101
|
+
if (v.kind === Kind.ENUM) return defaultEnum(v.value);
|
|
102
|
+
break;
|
|
103
|
+
case "BigInt":
|
|
104
|
+
if ((v.kind === Kind.INT || v.kind === Kind.STRING) && /^-?[0-9]+$/.test(v.value)) {
|
|
105
|
+
return defaultBigInt(v.value);
|
|
106
|
+
}
|
|
107
|
+
break;
|
|
88
108
|
case "String":
|
|
89
109
|
if (v.kind === Kind.STRING) return v.value;
|
|
90
110
|
if (ctx.isEnum && v.kind === Kind.ENUM) return v.value;
|
|
@@ -191,10 +211,10 @@ var FIELD_DIRECTIVES = {
|
|
|
191
211
|
apply: (d, ctx) => {
|
|
192
212
|
const v = arg(d, "value");
|
|
193
213
|
const value = v ? defaultFromValue(v, ctx) : { error: "missing value" };
|
|
194
|
-
if (typeof value === "object") {
|
|
214
|
+
if (typeof value === "object" && "error" in value) {
|
|
195
215
|
return { issues: [issue("unsupported", "@default", `${value.error}; not converted`)] };
|
|
196
216
|
}
|
|
197
|
-
return { decorators: [defaultLiteral(value)] };
|
|
217
|
+
return { decorators: [typeof value === "object" ? value : defaultLiteral(value)] };
|
|
198
218
|
}
|
|
199
219
|
},
|
|
200
220
|
unique: {
|
|
@@ -248,7 +268,7 @@ var FIELD_DIRECTIVES = {
|
|
|
248
268
|
},
|
|
249
269
|
cypher: {
|
|
250
270
|
kind: "drop",
|
|
251
|
-
message: "@cypher fields are computed by a Cypher query: not converted, write it as a query"
|
|
271
|
+
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
272
|
},
|
|
253
273
|
customResolver: {
|
|
254
274
|
kind: "drop",
|
|
@@ -316,11 +336,47 @@ var TYPE_DIRECTIVES = {
|
|
|
316
336
|
}
|
|
317
337
|
return rename ? { rename, issues } : { issues };
|
|
318
338
|
},
|
|
319
|
-
fulltext:
|
|
339
|
+
fulltext: (d) => {
|
|
340
|
+
const raw = arg(d, "indexes");
|
|
341
|
+
const indexes = raw ? valueFromASTUntyped(raw) : void 0;
|
|
342
|
+
const list2 = Array.isArray(indexes) ? indexes : indexes === void 0 ? [] : [indexes];
|
|
343
|
+
const fulltext = [];
|
|
344
|
+
const issues = [];
|
|
345
|
+
for (const ix of list2) {
|
|
346
|
+
const { indexName, queryName, fields } = ix ?? {};
|
|
347
|
+
if (typeof indexName !== "string" || !Array.isArray(fields) || fields.length === 0 || !fields.every((f) => typeof f === "string")) {
|
|
348
|
+
issues.push(
|
|
349
|
+
issue("unsupported", "@fulltext", "an index needs indexName and fields: not converted")
|
|
350
|
+
);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(indexName)) {
|
|
354
|
+
issues.push(
|
|
355
|
+
issue(
|
|
356
|
+
"unsupported",
|
|
357
|
+
"@fulltext",
|
|
358
|
+
`index name "${indexName}" is not letters, digits and underscores: not converted`
|
|
359
|
+
)
|
|
360
|
+
);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
fulltext.push({ name: indexName, fields });
|
|
364
|
+
if (typeof queryName === "string") {
|
|
365
|
+
issues.push(
|
|
366
|
+
issue(
|
|
367
|
+
"ignored",
|
|
368
|
+
"@fulltext(queryName)",
|
|
369
|
+
`query field "${queryName}" is part of the GraphQL API (compat.v7 still serves it)`
|
|
370
|
+
)
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return { fulltext, issues };
|
|
375
|
+
},
|
|
376
|
+
vector: reportType(
|
|
320
377
|
"unsupported",
|
|
321
|
-
"
|
|
378
|
+
"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
379
|
),
|
|
323
|
-
vector: reportType("unsupported", "vector indexes are not supported: create them in a migration"),
|
|
324
380
|
authentication: reportType("unsupported", AUTH),
|
|
325
381
|
authorization: reportType("unsupported", AUTH),
|
|
326
382
|
subscriptionsAuthorization: reportType("unsupported", AUTH),
|
|
@@ -426,6 +482,11 @@ function collectTypes(sources) {
|
|
|
426
482
|
fields: [
|
|
427
483
|
...(def.kind === Kind2.OBJECT_TYPE_DEFINITION || def.kind === Kind2.INTERFACE_TYPE_DEFINITION ? def.fields : void 0) ?? []
|
|
428
484
|
],
|
|
485
|
+
values: [
|
|
486
|
+
...((def.kind === Kind2.ENUM_TYPE_DEFINITION ? def.values : void 0) ?? []).map(
|
|
487
|
+
(v) => v.name.value
|
|
488
|
+
)
|
|
489
|
+
],
|
|
429
490
|
source: src.name
|
|
430
491
|
});
|
|
431
492
|
}
|
|
@@ -440,6 +501,9 @@ function collectTypes(sources) {
|
|
|
440
501
|
if ((def.kind === Kind2.OBJECT_TYPE_EXTENSION || def.kind === Kind2.INTERFACE_TYPE_EXTENSION) && def.fields) {
|
|
441
502
|
base.fields.push(...def.fields);
|
|
442
503
|
}
|
|
504
|
+
if (def.kind === Kind2.ENUM_TYPE_EXTENSION && def.values) {
|
|
505
|
+
base.values.push(...def.values.map((v) => v.name.value));
|
|
506
|
+
}
|
|
443
507
|
}
|
|
444
508
|
return types;
|
|
445
509
|
}
|
|
@@ -482,15 +546,6 @@ function convertGraphQLTypeDefs(input) {
|
|
|
482
546
|
}
|
|
483
547
|
switch (t.kind) {
|
|
484
548
|
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
549
|
break;
|
|
495
550
|
case "interface":
|
|
496
551
|
report(t.name, {
|
|
@@ -525,7 +580,7 @@ function convertGraphQLTypeDefs(input) {
|
|
|
525
580
|
report(t.name, {
|
|
526
581
|
severity: "unsupported",
|
|
527
582
|
feature: t.name,
|
|
528
|
-
message: `custom ${t.name} fields (@cypher, resolvers) are not converted
|
|
583
|
+
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
584
|
});
|
|
530
585
|
} else if (directive(t.directives, "jwt")) {
|
|
531
586
|
report(t.name, {
|
|
@@ -544,6 +599,7 @@ function convertGraphQLTypeDefs(input) {
|
|
|
544
599
|
}
|
|
545
600
|
}
|
|
546
601
|
const usedNames = new Set(types.keys());
|
|
602
|
+
const fulltextOf = /* @__PURE__ */ new Map();
|
|
547
603
|
for (const t of nodeTypes) {
|
|
548
604
|
let name = t.name;
|
|
549
605
|
for (const d of t.directives) {
|
|
@@ -567,6 +623,9 @@ function convertGraphQLTypeDefs(input) {
|
|
|
567
623
|
}
|
|
568
624
|
const effect = rule(d, t.name);
|
|
569
625
|
for (const i of effect.issues ?? []) report(t.name, i);
|
|
626
|
+
if (effect.fulltext?.length) {
|
|
627
|
+
fulltextOf.set(t.name, [...fulltextOf.get(t.name) ?? [], ...effect.fulltext]);
|
|
628
|
+
}
|
|
570
629
|
if (effect.rename && effect.rename !== name) {
|
|
571
630
|
if (usedNames.has(effect.rename) || [...nodeName.values()].includes(effect.rename)) {
|
|
572
631
|
report(t.name, {
|
|
@@ -581,11 +640,19 @@ function convertGraphQLTypeDefs(input) {
|
|
|
581
640
|
}
|
|
582
641
|
nodeName.set(t.name, name);
|
|
583
642
|
}
|
|
643
|
+
const enumMap = enumMappings(types, new Set(nodeName.values()), report);
|
|
644
|
+
const usedEnums = /* @__PURE__ */ new Set();
|
|
645
|
+
const mapScalar = (named) => {
|
|
646
|
+
const m = scalarMapping(named, types, enumMap);
|
|
647
|
+
if ("enum" in m && m.enum) usedEnums.add(m.enum);
|
|
648
|
+
return m;
|
|
649
|
+
};
|
|
584
650
|
const usages = [];
|
|
585
651
|
const declarations = [];
|
|
586
652
|
for (const t of nodeTypes) {
|
|
587
653
|
const declName = nodeName.get(t.name);
|
|
588
654
|
const fields = [];
|
|
655
|
+
const scalarOf = /* @__PURE__ */ new Map();
|
|
589
656
|
let hasId = false;
|
|
590
657
|
for (const f of t.fields) {
|
|
591
658
|
const at = `${t.name}.${f.name.value}`;
|
|
@@ -606,18 +673,30 @@ function convertGraphQLTypeDefs(input) {
|
|
|
606
673
|
if (rel.usage) usages.push(rel.usage);
|
|
607
674
|
continue;
|
|
608
675
|
}
|
|
609
|
-
const scalar = convertScalar(f, u, at, "node", hasId,
|
|
676
|
+
const scalar = convertScalar(f, u, at, "node", hasId, mapScalar, report);
|
|
610
677
|
if (!scalar) {
|
|
611
678
|
note(declName, skippedLine(f, "type not supported"));
|
|
612
679
|
continue;
|
|
613
680
|
}
|
|
614
681
|
if (scalar.takesId) hasId = true;
|
|
615
682
|
fields.push(scalar.field);
|
|
683
|
+
scalarOf.set(f.name.value, scalar.field);
|
|
616
684
|
}
|
|
685
|
+
const kept = dedupeNames(fields, t.name, report);
|
|
686
|
+
const attributes = fulltextAttributes(
|
|
687
|
+
t.name,
|
|
688
|
+
fulltextOf.get(t.name) ?? [],
|
|
689
|
+
(name) => {
|
|
690
|
+
const f = scalarOf.get(name);
|
|
691
|
+
return f && kept.includes(f) ? f : void 0;
|
|
692
|
+
},
|
|
693
|
+
report
|
|
694
|
+
);
|
|
617
695
|
declarations.push({
|
|
618
696
|
kind: "Node",
|
|
619
697
|
name: declName,
|
|
620
|
-
fields:
|
|
698
|
+
fields: kept,
|
|
699
|
+
...attributes.length ? { attributes } : {}
|
|
621
700
|
});
|
|
622
701
|
}
|
|
623
702
|
const relationships = [];
|
|
@@ -668,7 +747,7 @@ function convertGraphQLTypeDefs(input) {
|
|
|
668
747
|
propNotes.push(skippedLine(f, "not a scalar"));
|
|
669
748
|
continue;
|
|
670
749
|
}
|
|
671
|
-
const scalar = convertScalar(f, u, at, "relationship", false,
|
|
750
|
+
const scalar = convertScalar(f, u, at, "relationship", false, mapScalar, report);
|
|
672
751
|
if (!scalar) {
|
|
673
752
|
propNotes.push(skippedLine(f, "type not supported"));
|
|
674
753
|
continue;
|
|
@@ -701,12 +780,56 @@ function convertGraphQLTypeDefs(input) {
|
|
|
701
780
|
if (propNotes.length) notes.set(name, [...propNotes]);
|
|
702
781
|
}
|
|
703
782
|
}
|
|
783
|
+
const enums = [...types.values()].filter((t) => usedEnums.has(t.name)).map((t) => ({ kind: "Enum", name: t.name, values: [...t.values] }));
|
|
704
784
|
return {
|
|
705
|
-
document: {
|
|
785
|
+
document: {
|
|
786
|
+
kind: "Document",
|
|
787
|
+
declarations: [...enums, ...declarations, ...relationships]
|
|
788
|
+
},
|
|
706
789
|
issues,
|
|
707
790
|
notes
|
|
708
791
|
};
|
|
709
792
|
}
|
|
793
|
+
function fulltextAttributes(typeName, drafts, fieldOf, report) {
|
|
794
|
+
const out = [];
|
|
795
|
+
const names = /* @__PURE__ */ new Set();
|
|
796
|
+
for (const ix of drafts) {
|
|
797
|
+
if (names.has(ix.name)) {
|
|
798
|
+
report(typeName, {
|
|
799
|
+
severity: "unsupported",
|
|
800
|
+
feature: "@fulltext",
|
|
801
|
+
message: `index "${ix.name}" is declared twice: kept the first`
|
|
802
|
+
});
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
const fields = [];
|
|
806
|
+
let problem;
|
|
807
|
+
for (const name of ix.fields) {
|
|
808
|
+
const f = fieldOf(name);
|
|
809
|
+
if (!f) problem = `field "${name}" was not converted`;
|
|
810
|
+
else if (f.type.name !== "String") problem = `field "${name}" is not a String or ID field`;
|
|
811
|
+
else if (fields.includes(f.name)) problem = `field "${name}" is listed twice`;
|
|
812
|
+
else fields.push(f.name);
|
|
813
|
+
if (problem) break;
|
|
814
|
+
}
|
|
815
|
+
if (problem) {
|
|
816
|
+
report(typeName, {
|
|
817
|
+
severity: "unsupported",
|
|
818
|
+
feature: "@fulltext",
|
|
819
|
+
message: `index "${ix.name}": ${problem}; not converted`
|
|
820
|
+
});
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
names.add(ix.name);
|
|
824
|
+
out.push({
|
|
825
|
+
kind: "ModelAttribute",
|
|
826
|
+
name: "fulltext",
|
|
827
|
+
fields,
|
|
828
|
+
args: [{ key: "name", value: { kind: "string", value: ix.name } }]
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
return out;
|
|
832
|
+
}
|
|
710
833
|
function skippedLine(f, why) {
|
|
711
834
|
return `${f.name.value}: ${print(f.type)} (not converted: ${why})`;
|
|
712
835
|
}
|
|
@@ -737,15 +860,41 @@ function dedupeNames(fields, typeName, report) {
|
|
|
737
860
|
}
|
|
738
861
|
return out;
|
|
739
862
|
}
|
|
740
|
-
|
|
863
|
+
var CYPHRA_TYPE_NAMES = /* @__PURE__ */ new Set([
|
|
864
|
+
"String",
|
|
865
|
+
"Int",
|
|
866
|
+
"Float",
|
|
867
|
+
"Boolean",
|
|
868
|
+
"DateTime",
|
|
869
|
+
"Date",
|
|
870
|
+
"BigInt",
|
|
871
|
+
"Json",
|
|
872
|
+
"Vector"
|
|
873
|
+
]);
|
|
874
|
+
function enumMappings(types, nodeNames, report) {
|
|
875
|
+
const out = /* @__PURE__ */ new Map();
|
|
876
|
+
for (const t of types.values()) {
|
|
877
|
+
if (t.kind !== "enum") continue;
|
|
878
|
+
if (CYPHRA_TYPE_NAMES.has(t.name) || nodeNames.has(t.name) || t.values.length === 0) {
|
|
879
|
+
out.set(t.name, ENUM_AS_STRING);
|
|
880
|
+
if ("note" in ENUM_AS_STRING && ENUM_AS_STRING.note) {
|
|
881
|
+
report(t.name, { severity: "changed", feature: "enum", message: ENUM_AS_STRING.note });
|
|
882
|
+
}
|
|
883
|
+
continue;
|
|
884
|
+
}
|
|
885
|
+
out.set(t.name, enumField(t.name));
|
|
886
|
+
}
|
|
887
|
+
return out;
|
|
888
|
+
}
|
|
889
|
+
function scalarMapping(named, types, enums) {
|
|
741
890
|
const builtin = SCALARS[named];
|
|
742
891
|
if (builtin) return builtin;
|
|
743
892
|
const t = types.get(named);
|
|
744
|
-
if (t?.kind === "enum") return { ...
|
|
893
|
+
if (t?.kind === "enum") return { ...enums.get(named) ?? ENUM_AS_STRING, isEnum: true };
|
|
745
894
|
return CUSTOM_SCALAR_FIELD;
|
|
746
895
|
}
|
|
747
896
|
var DECORATOR_ORDER = ["id", "unique", "index", "default"];
|
|
748
|
-
function convertScalar(f, u, at, owner, nodeHasId,
|
|
897
|
+
function convertScalar(f, u, at, owner, nodeHasId, mapScalar, report) {
|
|
749
898
|
if (u.nested) {
|
|
750
899
|
report(at, {
|
|
751
900
|
severity: "unsupported",
|
|
@@ -754,7 +903,7 @@ function convertScalar(f, u, at, owner, nodeHasId, types, report) {
|
|
|
754
903
|
});
|
|
755
904
|
return void 0;
|
|
756
905
|
}
|
|
757
|
-
const mapping =
|
|
906
|
+
const mapping = mapScalar(u.named);
|
|
758
907
|
if ("unsupported" in mapping) {
|
|
759
908
|
report(at, {
|
|
760
909
|
severity: "unsupported",
|
|
@@ -813,7 +962,12 @@ function convertScalar(f, u, at, owner, nodeHasId, types, report) {
|
|
|
813
962
|
field: {
|
|
814
963
|
kind: "Scalar",
|
|
815
964
|
name,
|
|
816
|
-
type:
|
|
965
|
+
type: {
|
|
966
|
+
name: mapping.type,
|
|
967
|
+
optional: u.list ? false : optional,
|
|
968
|
+
...u.list ? { list: true } : {},
|
|
969
|
+
...mapping.enum ? { enum: mapping.enum } : {}
|
|
970
|
+
},
|
|
817
971
|
decorators
|
|
818
972
|
},
|
|
819
973
|
takesId
|
|
@@ -923,6 +1077,7 @@ function convertRelation(f, u, at, ownerType, types, nodeName, report) {
|
|
|
923
1077
|
|
|
924
1078
|
// src/import/print.ts
|
|
925
1079
|
import {
|
|
1080
|
+
formatModelAttribute,
|
|
926
1081
|
parseSchema,
|
|
927
1082
|
printSchemaDocument,
|
|
928
1083
|
resolveSchema
|
|
@@ -932,7 +1087,9 @@ function printDeclaration(decl, notes) {
|
|
|
932
1087
|
const text = printSchemaDocument({ kind: "Document", declarations: [decl] }).trimEnd();
|
|
933
1088
|
if (!notes?.length) return text;
|
|
934
1089
|
const lines = text.split("\n");
|
|
935
|
-
|
|
1090
|
+
const attributes = decl.kind === "Enum" ? void 0 : decl.attributes;
|
|
1091
|
+
const attrs = attributes?.length ? attributes.length + 1 : 0;
|
|
1092
|
+
lines.splice(lines.length - 1 - attrs, 0, ...notes.map((n) => ` // ${n}`));
|
|
936
1093
|
return lines.join("\n");
|
|
937
1094
|
}
|
|
938
1095
|
function printDeclarations(result, decls) {
|
|
@@ -1010,8 +1167,7 @@ function mergeImportedSchema(existing, result) {
|
|
|
1010
1167
|
}
|
|
1011
1168
|
if (decl.kind !== "Node" || current.kind !== "Node") {
|
|
1012
1169
|
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}`);
|
|
1170
|
+
if (!same) kept(decl.name, `${current.kind.toLowerCase()} ${decl.name}`);
|
|
1015
1171
|
continue;
|
|
1016
1172
|
}
|
|
1017
1173
|
const missing = [];
|
|
@@ -1021,13 +1177,23 @@ function mergeImportedSchema(existing, result) {
|
|
|
1021
1177
|
else if (formatField(mine) !== formatField(f))
|
|
1022
1178
|
kept(`${decl.name}.${f.name}`, `field ${f.name}`);
|
|
1023
1179
|
}
|
|
1180
|
+
const nameOf = (a) => a.args.find((x) => x.key === "name")?.value.value;
|
|
1181
|
+
const attrs = [];
|
|
1182
|
+
for (const a of decl.attributes ?? []) {
|
|
1183
|
+
const mine = current.attributes?.find(
|
|
1184
|
+
(x) => x.name === a.name && nameOf(x) === nameOf(a)
|
|
1185
|
+
);
|
|
1186
|
+
if (!mine) attrs.push(formatModelAttribute(a));
|
|
1187
|
+
else if (formatModelAttribute(mine) !== formatModelAttribute(a))
|
|
1188
|
+
kept(decl.name, `@@${a.name} ${String(nameOf(a))}`);
|
|
1189
|
+
}
|
|
1024
1190
|
const notes = (result.notes.get(decl.name) ?? []).filter((n) => !out.includes(`// ${n}`));
|
|
1025
|
-
if (missing.length === 0 && notes.length === 0) continue;
|
|
1191
|
+
if (missing.length === 0 && notes.length === 0 && attrs.length === 0) continue;
|
|
1026
1192
|
const close = nodeCloseBrace(out, decl.name);
|
|
1027
1193
|
if (close < 0) throw new Error(`Could not find the block of node "${decl.name}".`);
|
|
1028
1194
|
const lineStart = out.lastIndexOf("\n", close - 1) + 1;
|
|
1029
1195
|
const onOwnLine = out.slice(lineStart, close).trim() === "";
|
|
1030
|
-
const added = [...missing.map(formatField), ...notes.map((n) => `// ${n}`)].map((l) => ` ${l}
|
|
1196
|
+
const added = [...missing.map(formatField), ...attrs, ...notes.map((n) => `// ${n}`)].map((l) => ` ${l}
|
|
1031
1197
|
`).join("");
|
|
1032
1198
|
out = onOwnLine ? out.slice(0, lineStart) + added + out.slice(lineStart) : `${out.slice(0, close).trimEnd()}
|
|
1033
1199
|
${added}${out.slice(close)}`;
|
|
@@ -1079,368 +1245,201 @@ import {
|
|
|
1079
1245
|
getArgumentValues,
|
|
1080
1246
|
getDirectiveValues
|
|
1081
1247
|
} from "graphql";
|
|
1082
|
-
import
|
|
1248
|
+
import neo4j3, { isInt } from "neo4j-driver";
|
|
1083
1249
|
|
|
1084
|
-
// src/v7/
|
|
1250
|
+
// src/v7/auth/context.ts
|
|
1085
1251
|
import { GraphQLError as GraphQLError2 } from "graphql";
|
|
1086
|
-
var
|
|
1087
|
-
|
|
1088
|
-
|
|
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
|
-
});
|
|
1252
|
+
var UNAUTHENTICATED = "Unauthenticated";
|
|
1253
|
+
var FORBIDDEN = "Forbidden";
|
|
1254
|
+
function unauthenticated() {
|
|
1255
|
+
return new GraphQLError2(UNAUTHENTICATED);
|
|
1094
1256
|
}
|
|
1095
|
-
|
|
1096
|
-
|
|
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);
|
|
1257
|
+
function forbidden() {
|
|
1258
|
+
return new GraphQLError2(FORBIDDEN);
|
|
1107
1259
|
}
|
|
1108
|
-
function
|
|
1109
|
-
|
|
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("");
|
|
1260
|
+
function isRecord(v) {
|
|
1261
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1112
1262
|
}
|
|
1113
|
-
|
|
1114
|
-
|
|
1263
|
+
var DISALLOWED_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
1264
|
+
function readPath(value, segments) {
|
|
1265
|
+
let cur = value;
|
|
1266
|
+
for (const s of segments) {
|
|
1267
|
+
if (DISALLOWED_KEYS.has(s)) return void 0;
|
|
1268
|
+
if (typeof cur !== "object" || cur === null) return void 0;
|
|
1269
|
+
if (!Object.prototype.hasOwnProperty.call(cur, s)) return void 0;
|
|
1270
|
+
cur = cur[s];
|
|
1271
|
+
}
|
|
1272
|
+
return cur;
|
|
1115
1273
|
}
|
|
1116
|
-
function
|
|
1117
|
-
return
|
|
1274
|
+
function splitClaimPath(path) {
|
|
1275
|
+
return path.split(/(?<!\\)\./).map((p) => p.replaceAll("\\.", "."));
|
|
1118
1276
|
}
|
|
1119
|
-
function
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1277
|
+
async function authContextFor(contextValue, model, decoder) {
|
|
1278
|
+
const context = isRecord(contextValue) ? contextValue : {};
|
|
1279
|
+
const trusted = context.jwt;
|
|
1280
|
+
if (trusted !== void 0 && trusted !== null && trusted !== false && trusted !== "") {
|
|
1281
|
+
if (!isRecord(trusted)) {
|
|
1282
|
+
throw new GraphQLError2("context.jwt must be the decoded JWT payload (an object).");
|
|
1283
|
+
}
|
|
1284
|
+
return { isAuthenticated: true, jwt: trusted, claims: void 0, context };
|
|
1285
|
+
}
|
|
1286
|
+
if (decoder && typeof context.token === "string") {
|
|
1287
|
+
const payload = await decoder.decode(context);
|
|
1288
|
+
if (payload) {
|
|
1289
|
+
return {
|
|
1290
|
+
isAuthenticated: true,
|
|
1291
|
+
jwt: payload,
|
|
1292
|
+
claims: model.jwtClaims,
|
|
1293
|
+
context
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
return { isAuthenticated: false, jwt: void 0, claims: void 0, context };
|
|
1123
1298
|
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
"
|
|
1131
|
-
"
|
|
1132
|
-
"
|
|
1133
|
-
"
|
|
1134
|
-
"
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
"
|
|
1138
|
-
"
|
|
1139
|
-
"
|
|
1140
|
-
"
|
|
1141
|
-
"Point",
|
|
1142
|
-
"CartesianPoint"
|
|
1143
|
-
]);
|
|
1144
|
-
var UnsupportedTypeDefsError = class extends Error {
|
|
1145
|
-
name = "UnsupportedTypeDefsError";
|
|
1299
|
+
function claimValue(auth, field) {
|
|
1300
|
+
const mapped = auth.claims?.get(field);
|
|
1301
|
+
return readPath(auth.jwt ?? {}, mapped ? splitClaimPath(mapped) : [field]);
|
|
1302
|
+
}
|
|
1303
|
+
var JWT_WHERE_KEY = /^(?<fieldName>[_A-Za-z]\w*?)(?:_(?<operator>IN|INCLUDES|MATCHES|CONTAINS|STARTS_WITH|ENDS_WITH|EQ|LT|LTE|GT|GTE))?$/;
|
|
1304
|
+
var GENERIC_OPERATORS = {
|
|
1305
|
+
eq: "EQ",
|
|
1306
|
+
in: "IN",
|
|
1307
|
+
includes: "INCLUDES",
|
|
1308
|
+
contains: "CONTAINS",
|
|
1309
|
+
startsWith: "STARTS_WITH",
|
|
1310
|
+
endsWith: "ENDS_WITH",
|
|
1311
|
+
matches: "MATCHES",
|
|
1312
|
+
lt: "LT",
|
|
1313
|
+
lte: "LTE",
|
|
1314
|
+
gt: "GT",
|
|
1315
|
+
gte: "GTE"
|
|
1146
1316
|
};
|
|
1147
|
-
function
|
|
1148
|
-
|
|
1317
|
+
function parseJwtWhereKey(key) {
|
|
1318
|
+
const m = JWT_WHERE_KEY.exec(key);
|
|
1319
|
+
if (!m?.groups) throw new GraphQLError2(`Invalid JWT filter ${key}`);
|
|
1320
|
+
return { field: m.groups.fieldName, operator: m.groups.operator };
|
|
1149
1321
|
}
|
|
1150
|
-
function
|
|
1151
|
-
return
|
|
1322
|
+
function isPrimitive(v) {
|
|
1323
|
+
return ["string", "number", "boolean", "bigint"].includes(typeof v);
|
|
1152
1324
|
}
|
|
1153
|
-
function
|
|
1154
|
-
|
|
1155
|
-
return v && (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) ? v.value : void 0;
|
|
1325
|
+
function ordered(received) {
|
|
1326
|
+
return typeof received === "string" ? BigInt(received) : received;
|
|
1156
1327
|
}
|
|
1157
|
-
function
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1328
|
+
function compareInJs(operator, received, value) {
|
|
1329
|
+
try {
|
|
1330
|
+
switch (operator) {
|
|
1331
|
+
case "EQ":
|
|
1332
|
+
return isPrimitive(received) && isPrimitive(value) && received == value;
|
|
1333
|
+
case "LT":
|
|
1334
|
+
return ordered(received) < value;
|
|
1335
|
+
case "LTE":
|
|
1336
|
+
return ordered(received) <= value;
|
|
1337
|
+
case "GT":
|
|
1338
|
+
return ordered(received) > value;
|
|
1339
|
+
case "GTE":
|
|
1340
|
+
return ordered(received) >= value;
|
|
1341
|
+
case "STARTS_WITH":
|
|
1342
|
+
return typeof received === "string" && typeof value === "string" && received.startsWith(value);
|
|
1343
|
+
case "ENDS_WITH":
|
|
1344
|
+
return typeof received === "string" && typeof value === "string" && received.endsWith(value);
|
|
1345
|
+
case "CONTAINS":
|
|
1346
|
+
return typeof received === "string" && typeof value === "string" && received.includes(value);
|
|
1347
|
+
case "INCLUDES":
|
|
1348
|
+
return Array.isArray(received) && received.some((v) => v === value);
|
|
1349
|
+
case "IN":
|
|
1350
|
+
return Array.isArray(value) && value.some((v) => v === received);
|
|
1351
|
+
}
|
|
1352
|
+
} catch {
|
|
1353
|
+
return false;
|
|
1164
1354
|
}
|
|
1165
|
-
|
|
1166
|
-
return void 0;
|
|
1355
|
+
throw new GraphQLError2(`Operator ${operator} is not supported in @authentication(jwt)`);
|
|
1167
1356
|
}
|
|
1168
|
-
function
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1357
|
+
function jwtMatches(where, auth) {
|
|
1358
|
+
for (const [key, value] of Object.entries(where)) {
|
|
1359
|
+
if (key === "AND" || key === "OR") {
|
|
1360
|
+
const results = (Array.isArray(value) ? value : [value]).map(
|
|
1361
|
+
(w) => isRecord(w) ? jwtMatches(w, auth) : false
|
|
1362
|
+
);
|
|
1363
|
+
if (key === "AND" ? !results.every(Boolean) : !results.some(Boolean)) return false;
|
|
1364
|
+
continue;
|
|
1365
|
+
}
|
|
1366
|
+
if (key === "NOT") {
|
|
1367
|
+
if (!isRecord(value) || jwtMatches(value, auth)) return false;
|
|
1368
|
+
continue;
|
|
1369
|
+
}
|
|
1370
|
+
const { field, operator } = parseJwtWhereKey(key);
|
|
1371
|
+
const received = claimValue(auth, field);
|
|
1372
|
+
if (!received) return false;
|
|
1373
|
+
if (operator) {
|
|
1374
|
+
if (!compareInJs(operator, received, value)) return false;
|
|
1375
|
+
continue;
|
|
1376
|
+
}
|
|
1377
|
+
if (!isRecord(value)) return false;
|
|
1378
|
+
for (const [op, v] of Object.entries(value)) {
|
|
1379
|
+
const legacy = GENERIC_OPERATORS[op];
|
|
1380
|
+
if (!legacy)
|
|
1381
|
+
throw new GraphQLError2(`Operator ${op} is not supported in @authentication(jwt)`);
|
|
1382
|
+
if (!compareInJs(legacy, received, v)) return false;
|
|
1181
1383
|
}
|
|
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
1384
|
}
|
|
1186
|
-
return
|
|
1187
|
-
name: cur.name.value,
|
|
1188
|
-
list: false,
|
|
1189
|
-
required,
|
|
1190
|
-
elementRequired: false
|
|
1191
|
-
};
|
|
1385
|
+
return true;
|
|
1192
1386
|
}
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
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";
|
|
1387
|
+
function applyAuthentication(annotation, operations, auth) {
|
|
1388
|
+
if (!annotation || !operations.some((op) => annotation.operations.has(op))) return;
|
|
1389
|
+
if (!auth.isAuthenticated) throw unauthenticated();
|
|
1390
|
+
if (annotation.jwt && (!auth.jwt || !jwtMatches(annotation.jwt, auth))) throw unauthenticated();
|
|
1216
1391
|
}
|
|
1217
|
-
function
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1392
|
+
function checkAuthentication(model, auth, node, operations, field) {
|
|
1393
|
+
applyAuthentication(model.authentication, operations, auth);
|
|
1394
|
+
if (field === void 0) {
|
|
1395
|
+
applyAuthentication(node.auth.authentication, operations, auth);
|
|
1396
|
+
} else {
|
|
1397
|
+
const attr = node.attributes.find((a) => a.name === field);
|
|
1398
|
+
applyAuthentication(attr?.auth?.authentication, operations, auth);
|
|
1224
1399
|
}
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1400
|
+
}
|
|
1401
|
+
function checkRootAuthentication(model, auth, type, field) {
|
|
1402
|
+
const operations = type === "Query" ? ["READ"] : ["CREATE", "UPDATE", "DELETE"];
|
|
1403
|
+
applyAuthentication(model.authentication, operations, auth);
|
|
1404
|
+
applyAuthentication(
|
|
1405
|
+
(type === "Query" ? model.query : model.mutation).authentication,
|
|
1406
|
+
operations,
|
|
1407
|
+
auth
|
|
1408
|
+
);
|
|
1409
|
+
applyAuthentication(field.authentication, operations, auth);
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
// src/v7/auth/rules.ts
|
|
1413
|
+
import { GraphQLError as GraphQLError3 } from "graphql";
|
|
1414
|
+
|
|
1415
|
+
// src/v7/cypher/where.ts
|
|
1416
|
+
import neo4j2 from "neo4j-driver";
|
|
1417
|
+
|
|
1418
|
+
// src/v7/cypher/context.ts
|
|
1419
|
+
var CypherContext = class {
|
|
1420
|
+
params = {};
|
|
1421
|
+
paramCount = 0;
|
|
1422
|
+
varCount = 0;
|
|
1423
|
+
/** `$jwt` of `@cypher` statements: the decoded JWT, `{}` when not authenticated (v7). */
|
|
1424
|
+
jwt = {};
|
|
1425
|
+
/** Bind a value and return its `$placeholder`. */
|
|
1426
|
+
param(value) {
|
|
1427
|
+
const key = `p${this.paramCount++}`;
|
|
1428
|
+
this.params[key] = value;
|
|
1429
|
+
return `$${key}`;
|
|
1229
1430
|
}
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
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
|
-
);
|
|
1431
|
+
/** Bind a value under a fixed name (`$jwt` of `@cypher` statements). */
|
|
1432
|
+
namedParam(name, value) {
|
|
1433
|
+
this.params[name] = value;
|
|
1434
|
+
return `$${name}`;
|
|
1241
1435
|
}
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
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}`;
|
|
1436
|
-
}
|
|
1437
|
-
/** Fresh variable name, e.g. `this0`. */
|
|
1438
|
-
variable(prefix2 = "this") {
|
|
1439
|
-
return `${prefix2}${this.varCount++}`;
|
|
1440
|
-
}
|
|
1441
|
-
};
|
|
1442
|
-
function q(id) {
|
|
1443
|
-
return "`" + id.replace(/`/g, "``") + "`";
|
|
1436
|
+
/** Fresh variable name, e.g. `this0`. */
|
|
1437
|
+
variable(prefix2 = "this") {
|
|
1438
|
+
return `${prefix2}${this.varCount++}`;
|
|
1439
|
+
}
|
|
1440
|
+
};
|
|
1441
|
+
function q(id) {
|
|
1442
|
+
return "`" + id.replace(/`/g, "``") + "`";
|
|
1444
1443
|
}
|
|
1445
1444
|
function labels(ls) {
|
|
1446
1445
|
return ls.map((l) => `:${q(l)}`).join("");
|
|
@@ -1462,8 +1461,105 @@ function withList(list2, l, body) {
|
|
|
1462
1461
|
return `[${l} IN [${list2}] | ${body(l)}][0]`;
|
|
1463
1462
|
}
|
|
1464
1463
|
|
|
1465
|
-
// src/v7/cypher/
|
|
1464
|
+
// src/v7/cypher/custom.ts
|
|
1466
1465
|
import neo4j from "neo4j-driver";
|
|
1466
|
+
var STATEMENT_MARK = "/* @cypher */";
|
|
1467
|
+
function hasStatement(...texts) {
|
|
1468
|
+
return texts.some((t) => t !== void 0 && t.includes(STATEMENT_MARK));
|
|
1469
|
+
}
|
|
1470
|
+
function argumentValue(arg3, value) {
|
|
1471
|
+
if (value === null || value === void 0) return null;
|
|
1472
|
+
if (Array.isArray(value)) return value.map((v) => argumentValue(arg3, v));
|
|
1473
|
+
if (arg3.kind === "scalar" && arg3.type.name === "Int" && typeof value === "number") {
|
|
1474
|
+
return neo4j.int(value);
|
|
1475
|
+
}
|
|
1476
|
+
return value;
|
|
1477
|
+
}
|
|
1478
|
+
function bindArguments(ctx, statement, args, values) {
|
|
1479
|
+
if (args.length === 0) return statement;
|
|
1480
|
+
const names = args.map((a) => a.name.replace(/[^_A-Za-z0-9]/g, ""));
|
|
1481
|
+
const re = new RegExp(`\\$(${names.join("|")})\\b`, "g");
|
|
1482
|
+
const bound = /* @__PURE__ */ new Map();
|
|
1483
|
+
return statement.replace(re, (_m, name) => {
|
|
1484
|
+
const value = values[name];
|
|
1485
|
+
if (value === void 0 || value === null) return "NULL";
|
|
1486
|
+
let p = bound.get(name);
|
|
1487
|
+
if (!p) {
|
|
1488
|
+
p = ctx.param(
|
|
1489
|
+
argumentValue(
|
|
1490
|
+
args.find((a) => a.name === name),
|
|
1491
|
+
value
|
|
1492
|
+
)
|
|
1493
|
+
);
|
|
1494
|
+
bound.set(name, p);
|
|
1495
|
+
}
|
|
1496
|
+
return p;
|
|
1497
|
+
});
|
|
1498
|
+
}
|
|
1499
|
+
function statementCall(ctx, cypher, args, values, variable) {
|
|
1500
|
+
const statement = bindArguments(ctx, cypher.statement, args, values);
|
|
1501
|
+
if (/\$jwt\b/.test(statement)) ctx.namedParam("jwt", ctx.jwt);
|
|
1502
|
+
if (variable === void 0) return `CALL () {
|
|
1503
|
+
${STATEMENT_MARK}
|
|
1504
|
+
${statement}
|
|
1505
|
+
}`;
|
|
1506
|
+
return `CALL (${variable}) {
|
|
1507
|
+
WITH ${variable} AS this
|
|
1508
|
+
${STATEMENT_MARK}
|
|
1509
|
+
${statement}
|
|
1510
|
+
}`;
|
|
1511
|
+
}
|
|
1512
|
+
function column(cypher) {
|
|
1513
|
+
return q(cypher.columnName);
|
|
1514
|
+
}
|
|
1515
|
+
function scalarClause(ctx, variable, cypher, args, values, list2) {
|
|
1516
|
+
const s = ctx.variable("cypher");
|
|
1517
|
+
const call = statementCall(ctx, cypher, args, values, variable);
|
|
1518
|
+
if (!list2) {
|
|
1519
|
+
return {
|
|
1520
|
+
clause: `CALL (${variable}) {
|
|
1521
|
+
${call}
|
|
1522
|
+
RETURN ${column(cypher)} AS ${s}
|
|
1523
|
+
}`,
|
|
1524
|
+
variable: s
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
const x = ctx.variable("value");
|
|
1528
|
+
return {
|
|
1529
|
+
clause: `CALL (${variable}) {
|
|
1530
|
+
${call}
|
|
1531
|
+
UNWIND ${column(cypher)} AS ${x}
|
|
1532
|
+
RETURN collect(${x}) AS ${s}
|
|
1533
|
+
}`,
|
|
1534
|
+
variable: s
|
|
1535
|
+
};
|
|
1536
|
+
}
|
|
1537
|
+
function scalarExpr(ctx, variable, cypher, list2) {
|
|
1538
|
+
const call = statementCall(ctx, cypher, [], {}, variable);
|
|
1539
|
+
if (!list2) return `head(COLLECT {
|
|
1540
|
+
${call}
|
|
1541
|
+
RETURN ${column(cypher)}
|
|
1542
|
+
})`;
|
|
1543
|
+
const x = ctx.variable("value");
|
|
1544
|
+
return `COLLECT {
|
|
1545
|
+
${call}
|
|
1546
|
+
UNWIND ${column(cypher)} AS ${x}
|
|
1547
|
+
RETURN ${x}
|
|
1548
|
+
}`;
|
|
1549
|
+
}
|
|
1550
|
+
function nodeRows(ctx, variable, cypher, x) {
|
|
1551
|
+
const call = statementCall(ctx, cypher, [], {}, variable);
|
|
1552
|
+
return `${call}
|
|
1553
|
+
WITH ${column(cypher)} AS ${x} WHERE ${x} IS NOT NULL`;
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
// src/v7/cypher/where.ts
|
|
1557
|
+
var AuthValue = class {
|
|
1558
|
+
constructor(value) {
|
|
1559
|
+
this.value = value;
|
|
1560
|
+
}
|
|
1561
|
+
value;
|
|
1562
|
+
};
|
|
1467
1563
|
var LEGACY_OPERATORS = {
|
|
1468
1564
|
EQ: "eq",
|
|
1469
1565
|
IN: "in",
|
|
@@ -1483,7 +1579,9 @@ var QUANTIFIER_KEYS = {
|
|
|
1483
1579
|
SOME: "some"
|
|
1484
1580
|
};
|
|
1485
1581
|
function isPlainObject(v) {
|
|
1486
|
-
|
|
1582
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
|
|
1583
|
+
const proto = Object.getPrototypeOf(v);
|
|
1584
|
+
return proto === Object.prototype || proto === null;
|
|
1487
1585
|
}
|
|
1488
1586
|
function and(parts) {
|
|
1489
1587
|
const ps = parts.filter((p) => p !== void 0);
|
|
@@ -1491,11 +1589,19 @@ function and(parts) {
|
|
|
1491
1589
|
if (ps.length === 1) return ps[0];
|
|
1492
1590
|
return ps.map((p) => `(${p})`).join(" AND ");
|
|
1493
1591
|
}
|
|
1592
|
+
function objectOrNothing(where, what) {
|
|
1593
|
+
return isFilterObject(where, what) ? where : void 0;
|
|
1594
|
+
}
|
|
1595
|
+
function isFilterObject(where, what) {
|
|
1596
|
+
if (where === null || where === void 0) return false;
|
|
1597
|
+
if (!isPlainObject(where)) throw new Error(`Invalid ${what}: expected an object`);
|
|
1598
|
+
return true;
|
|
1599
|
+
}
|
|
1494
1600
|
function encodeValue(attr, value) {
|
|
1495
1601
|
if (value === null || value === void 0) return null;
|
|
1496
1602
|
if (Array.isArray(value)) return value.map((v) => encodeValue(attr, v));
|
|
1497
1603
|
if (attr.kind === "scalar" && attr.type.name === "Int" && typeof value === "number") {
|
|
1498
|
-
return
|
|
1604
|
+
return neo4j2.int(value);
|
|
1499
1605
|
}
|
|
1500
1606
|
return value;
|
|
1501
1607
|
}
|
|
@@ -1510,48 +1616,62 @@ function valueExpr(ctx, attr, value, isList) {
|
|
|
1510
1616
|
}
|
|
1511
1617
|
function attributePredicate(ctx, expr, attr, op, value) {
|
|
1512
1618
|
if (value === void 0) return void 0;
|
|
1619
|
+
if (value instanceof AuthValue) {
|
|
1620
|
+
const p = ctx.param(value.value ?? null);
|
|
1621
|
+
const pred = attributeComparison(expr, attr, op, (isList) => castValue(attr, p, isList));
|
|
1622
|
+
return `(${p} IS NOT NULL AND ${pred})`;
|
|
1623
|
+
}
|
|
1513
1624
|
if (op === "eq" && value === null) return `${expr} IS NULL`;
|
|
1514
1625
|
if (value === null) return void 0;
|
|
1626
|
+
return attributeComparison(expr, attr, op, (isList) => valueExpr(ctx, attr, value, isList));
|
|
1627
|
+
}
|
|
1628
|
+
function attributeComparison(expr, attr, op, v) {
|
|
1515
1629
|
if (attr.type.list) {
|
|
1516
1630
|
switch (op) {
|
|
1517
1631
|
case "eq":
|
|
1518
|
-
return `${expr} = ${
|
|
1632
|
+
return `${expr} = ${v(true)}`;
|
|
1519
1633
|
case "includes":
|
|
1520
|
-
return `${
|
|
1634
|
+
return `${v(false)} IN ${expr}`;
|
|
1521
1635
|
}
|
|
1522
1636
|
throw new Error(`Unsupported list filter operator ${op}`);
|
|
1523
1637
|
}
|
|
1524
1638
|
switch (op) {
|
|
1525
1639
|
case "eq":
|
|
1526
|
-
return `${expr} = ${
|
|
1640
|
+
return `${expr} = ${v(false)}`;
|
|
1527
1641
|
case "in":
|
|
1528
|
-
return `${expr} IN ${
|
|
1642
|
+
return `${expr} IN ${v(true)}`;
|
|
1529
1643
|
case "contains":
|
|
1530
|
-
return `${expr} CONTAINS ${
|
|
1644
|
+
return `${expr} CONTAINS ${v(false)}`;
|
|
1531
1645
|
case "startsWith":
|
|
1532
|
-
return `${expr} STARTS WITH ${
|
|
1646
|
+
return `${expr} STARTS WITH ${v(false)}`;
|
|
1533
1647
|
case "endsWith":
|
|
1534
|
-
return `${expr} ENDS WITH ${
|
|
1648
|
+
return `${expr} ENDS WITH ${v(false)}`;
|
|
1535
1649
|
case "lt":
|
|
1536
|
-
return `${expr} < ${
|
|
1650
|
+
return `${expr} < ${v(false)}`;
|
|
1537
1651
|
case "lte":
|
|
1538
|
-
return `${expr} <= ${
|
|
1652
|
+
return `${expr} <= ${v(false)}`;
|
|
1539
1653
|
case "gt":
|
|
1540
|
-
return `${expr} > ${
|
|
1654
|
+
return `${expr} > ${v(false)}`;
|
|
1541
1655
|
case "gte":
|
|
1542
|
-
return `${expr} >= ${
|
|
1656
|
+
return `${expr} >= ${v(false)}`;
|
|
1543
1657
|
}
|
|
1544
1658
|
throw new Error(`Unsupported filter operator ${op}`);
|
|
1545
1659
|
}
|
|
1660
|
+
function attributeExpr(ctx, variable, attr) {
|
|
1661
|
+
if (!attr.cypher) return `${variable}.${q(attr.property)}`;
|
|
1662
|
+
if (attr.args.length)
|
|
1663
|
+
throw new Error(`Cannot filter on @cypher field ${attr.name} with arguments`);
|
|
1664
|
+
return scalarExpr(ctx, variable, attr.cypher, attr.type.list);
|
|
1665
|
+
}
|
|
1546
1666
|
function attributeFilter(ctx, variable, attributes, key, value) {
|
|
1547
1667
|
const direct = attributes.find((a) => a.name === key);
|
|
1548
1668
|
if (direct) {
|
|
1549
1669
|
if (value === null || value === void 0) return { handled: true };
|
|
1550
|
-
if (
|
|
1551
|
-
const
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
);
|
|
1670
|
+
if (!isPlainObject(value)) throw new Error(`Invalid filter on ${key}`);
|
|
1671
|
+
const ops = Object.entries(value).filter(([, v]) => v !== void 0);
|
|
1672
|
+
if (ops.length === 0) return { handled: true };
|
|
1673
|
+
const expr = attributeExpr(ctx, variable, direct);
|
|
1674
|
+
const preds = ops.map(([op, v]) => attributePredicate(ctx, expr, direct, op, v));
|
|
1555
1675
|
return { handled: true, predicate: and(preds) };
|
|
1556
1676
|
}
|
|
1557
1677
|
const m = /^(.+)_([A-Z_]+)$/.exec(key);
|
|
@@ -1559,11 +1679,11 @@ function attributeFilter(ctx, variable, attributes, key, value) {
|
|
|
1559
1679
|
const attr = attributes.find((a) => a.name === m[1]);
|
|
1560
1680
|
const op = LEGACY_OPERATORS[m[2]];
|
|
1561
1681
|
if (attr && op) {
|
|
1562
|
-
if (
|
|
1563
|
-
|
|
1682
|
+
if (value === void 0) return { handled: true };
|
|
1683
|
+
if (value === null && op !== "eq") return { handled: true };
|
|
1564
1684
|
return {
|
|
1565
1685
|
handled: true,
|
|
1566
|
-
predicate: attributePredicate(ctx,
|
|
1686
|
+
predicate: attributePredicate(ctx, attributeExpr(ctx, variable, attr), attr, op, value)
|
|
1567
1687
|
};
|
|
1568
1688
|
}
|
|
1569
1689
|
}
|
|
@@ -1572,8 +1692,8 @@ function attributeFilter(ctx, variable, attributes, key, value) {
|
|
|
1572
1692
|
function logical(where, key, compile) {
|
|
1573
1693
|
const value = where[key];
|
|
1574
1694
|
if (key === "AND" || key === "OR") {
|
|
1575
|
-
if (
|
|
1576
|
-
const parts = value.filter(
|
|
1695
|
+
if (value === null || value === void 0) return { handled: true };
|
|
1696
|
+
const parts = (Array.isArray(value) ? value : [value]).filter((w) => w !== null && w !== void 0).map((w) => compile(objectOrNothing(w, key)));
|
|
1577
1697
|
if (key === "AND") return { handled: true, predicate: and(parts) };
|
|
1578
1698
|
if (parts.length === 0) return { handled: true };
|
|
1579
1699
|
if (parts.some((p) => p === void 0)) return { handled: true, predicate: "true" };
|
|
@@ -1583,8 +1703,9 @@ function logical(where, key, compile) {
|
|
|
1583
1703
|
};
|
|
1584
1704
|
}
|
|
1585
1705
|
if (key === "NOT") {
|
|
1586
|
-
|
|
1587
|
-
|
|
1706
|
+
const o = objectOrNothing(value, key);
|
|
1707
|
+
if (o === void 0) return { handled: true };
|
|
1708
|
+
const inner = compile(o);
|
|
1588
1709
|
return { handled: true, predicate: inner === void 0 ? void 0 : `NOT (${inner})` };
|
|
1589
1710
|
}
|
|
1590
1711
|
return { handled: false };
|
|
@@ -1607,6 +1728,7 @@ function quantified(pattern, quantifier, predicate) {
|
|
|
1607
1728
|
case "all":
|
|
1608
1729
|
return `EXISTS { MATCH ${pattern} } AND NOT EXISTS { MATCH ${pattern} WHERE NOT (${predicate}) }`;
|
|
1609
1730
|
}
|
|
1731
|
+
throw new Error(`Unknown relationship filter ${String(quantifier)}`);
|
|
1610
1732
|
}
|
|
1611
1733
|
var AGGREGATION_COMPARISON = {
|
|
1612
1734
|
EQ: "eq",
|
|
@@ -1646,23 +1768,22 @@ function comparison(ctx, expr, op, value, attr) {
|
|
|
1646
1768
|
if (value === void 0 || value === null) return void 0;
|
|
1647
1769
|
const cmp = COMPARISON_OPERATORS[op];
|
|
1648
1770
|
if (!cmp) throw new Error(`Invalid aggregation filter operator ${op}`);
|
|
1649
|
-
const
|
|
1771
|
+
const ref = value instanceof AuthValue;
|
|
1772
|
+
const p = ctx.param(ref ? value.value ?? null : value);
|
|
1650
1773
|
const isDateTime2 = attr?.kind === "scalar" && attr.type.name === "DateTime";
|
|
1651
|
-
|
|
1774
|
+
const pred = `${expr} ${cmp} ${isDateTime2 ? `datetime(${p})` : p}`;
|
|
1775
|
+
return ref ? `(${p} IS NOT NULL AND ${pred})` : pred;
|
|
1652
1776
|
}
|
|
1653
1777
|
var WhereCompiler = class {
|
|
1654
|
-
constructor(model, ctx
|
|
1655
|
-
}) {
|
|
1778
|
+
constructor(model, ctx) {
|
|
1656
1779
|
this.model = model;
|
|
1657
1780
|
this.ctx = ctx;
|
|
1658
|
-
this.onTraverse = onTraverse;
|
|
1659
1781
|
}
|
|
1660
1782
|
model;
|
|
1661
1783
|
ctx;
|
|
1662
|
-
onTraverse;
|
|
1663
1784
|
/** Predicate for a `${Node}Where` input on `variable`, or `undefined` when it filters nothing. */
|
|
1664
1785
|
node(variable, node, where) {
|
|
1665
|
-
if (!
|
|
1786
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1666
1787
|
const parts = [];
|
|
1667
1788
|
for (const [key, value] of Object.entries(where)) {
|
|
1668
1789
|
if (value === void 0) continue;
|
|
@@ -1676,21 +1797,99 @@ var WhereCompiler = class {
|
|
|
1676
1797
|
parts.push(a.predicate);
|
|
1677
1798
|
continue;
|
|
1678
1799
|
}
|
|
1800
|
+
const c = this.cypherNodeFilter(variable, node, key, value);
|
|
1801
|
+
if (c.handled) {
|
|
1802
|
+
parts.push(c.predicate);
|
|
1803
|
+
continue;
|
|
1804
|
+
}
|
|
1679
1805
|
parts.push(this.relationshipFilter(variable, node, key, value));
|
|
1680
1806
|
}
|
|
1681
1807
|
return and(parts);
|
|
1682
1808
|
}
|
|
1809
|
+
/**
|
|
1810
|
+
* Filters on `@cypher` fields returning nodes (v7 7.6): for a list, `actors: { some | all | none |
|
|
1811
|
+
* single }` (and `actors_SOME`, …) test the returned nodes with `any` / `all` / `none` / `single`
|
|
1812
|
+
* (so `all` holds when the statement returns nothing); for one node, `topActor: { … }` tests the
|
|
1813
|
+
* first returned node and `topActor: null` matches when there is none.
|
|
1814
|
+
*/
|
|
1815
|
+
cypherNodeFilter(variable, node, key, value) {
|
|
1816
|
+
const legacy = /^(.+)_(ALL|NONE|SINGLE|SOME)$/.exec(key);
|
|
1817
|
+
const name = node.cypherNodes.some((c) => c.name === key) ? key : legacy?.[1];
|
|
1818
|
+
const field = node.cypherNodes.find((c) => c.name === name);
|
|
1819
|
+
if (!field) return { handled: false };
|
|
1820
|
+
if (field.args.length)
|
|
1821
|
+
throw new Error(`Cannot filter on @cypher field ${field.name} with arguments`);
|
|
1822
|
+
const target = this.model.node(field.target);
|
|
1823
|
+
if (!field.type.list) {
|
|
1824
|
+
if (value === void 0) return { handled: true };
|
|
1825
|
+
const x = this.ctx.variable("n");
|
|
1826
|
+
const rows = nodeRows(this.ctx, variable, field.cypher, x);
|
|
1827
|
+
if (value === null) return { handled: true, predicate: `NOT EXISTS {
|
|
1828
|
+
${rows}
|
|
1829
|
+
}` };
|
|
1830
|
+
const pred = this.node(x, target, value);
|
|
1831
|
+
if (pred === void 0) return { handled: true };
|
|
1832
|
+
return {
|
|
1833
|
+
handled: true,
|
|
1834
|
+
predicate: `EXISTS {
|
|
1835
|
+
${rows}
|
|
1836
|
+
WITH ${x} LIMIT 1
|
|
1837
|
+
WITH ${x} WHERE ${pred}
|
|
1838
|
+
}`
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
const quantifiers = key === field.name ? isFilterObject(value, key) ? Object.entries(value).map(([k, w]) => [k, w]) : [] : [[QUANTIFIER_KEYS[legacy[2]], value]];
|
|
1842
|
+
return {
|
|
1843
|
+
handled: true,
|
|
1844
|
+
predicate: and(
|
|
1845
|
+
quantifiers.map(
|
|
1846
|
+
([quantifier, w]) => this.cypherNodes(variable, field, target, quantifier, w)
|
|
1847
|
+
)
|
|
1848
|
+
)
|
|
1849
|
+
};
|
|
1850
|
+
}
|
|
1851
|
+
/** `any` / `all` / `none` / `single` of the nodes returned by the statement (v7 semantics). */
|
|
1852
|
+
cypherNodes(variable, field, target, quantifier, where) {
|
|
1853
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1854
|
+
const x = this.ctx.variable("n");
|
|
1855
|
+
const pred = this.node(x, target, where);
|
|
1856
|
+
if (pred === void 0) return void 0;
|
|
1857
|
+
const rows = () => nodeRows(this.ctx, variable, field.cypher, x);
|
|
1858
|
+
const matching = () => `COUNT {
|
|
1859
|
+
${rows()}
|
|
1860
|
+
WITH ${x} WHERE ${pred}
|
|
1861
|
+
}`;
|
|
1862
|
+
switch (quantifier) {
|
|
1863
|
+
case "some":
|
|
1864
|
+
return `EXISTS {
|
|
1865
|
+
${rows()}
|
|
1866
|
+
WITH ${x} WHERE ${pred}
|
|
1867
|
+
}`;
|
|
1868
|
+
case "none":
|
|
1869
|
+
return `NOT EXISTS {
|
|
1870
|
+
${rows()}
|
|
1871
|
+
WITH ${x} WHERE ${pred}
|
|
1872
|
+
}`;
|
|
1873
|
+
case "single":
|
|
1874
|
+
return `${matching()} = 1`;
|
|
1875
|
+
case "all":
|
|
1876
|
+
return `${matching()} = COUNT {
|
|
1877
|
+
${rows()}
|
|
1878
|
+
}`;
|
|
1879
|
+
}
|
|
1880
|
+
throw new Error(`Unknown relationship filter ${String(quantifier)}`);
|
|
1881
|
+
}
|
|
1683
1882
|
relationshipFilter(variable, node, key, value) {
|
|
1684
1883
|
const find = (name) => node.relationships.find((r) => r.name === name);
|
|
1685
1884
|
let rel = find(key);
|
|
1686
1885
|
if (rel) {
|
|
1687
|
-
if (!
|
|
1886
|
+
if (!isFilterObject(value, key)) return void 0;
|
|
1688
1887
|
return and(
|
|
1689
1888
|
Object.entries(value).map(([q2, w]) => this.related(variable, rel, q2, w))
|
|
1690
1889
|
);
|
|
1691
1890
|
}
|
|
1692
1891
|
if (key.endsWith("Connection") && (rel = find(key.slice(0, -"Connection".length)))) {
|
|
1693
|
-
if (!
|
|
1892
|
+
if (!isFilterObject(value, key)) return void 0;
|
|
1694
1893
|
return and(
|
|
1695
1894
|
Object.entries(value).map(([q2, w]) => {
|
|
1696
1895
|
if (q2 === "aggregate") return this.aggregate(variable, rel, w, false);
|
|
@@ -1712,10 +1911,9 @@ var WhereCompiler = class {
|
|
|
1712
1911
|
throw new Error(`Unknown filter ${node.name}Where.${key}`);
|
|
1713
1912
|
}
|
|
1714
1913
|
related(variable, rel, quantifier, where) {
|
|
1715
|
-
if (!
|
|
1914
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1716
1915
|
const m = this.ctx.variable("n");
|
|
1717
1916
|
const target = this.model.node(rel.target);
|
|
1718
|
-
this.onTraverse(target);
|
|
1719
1917
|
return quantified(
|
|
1720
1918
|
relationshipPattern(this.model, variable, rel, m),
|
|
1721
1919
|
quantifier,
|
|
@@ -1723,10 +1921,9 @@ var WhereCompiler = class {
|
|
|
1723
1921
|
);
|
|
1724
1922
|
}
|
|
1725
1923
|
relatedConnection(variable, rel, quantifier, where) {
|
|
1726
|
-
if (!
|
|
1924
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1727
1925
|
const m = this.ctx.variable("n");
|
|
1728
1926
|
const r = this.ctx.variable("r");
|
|
1729
|
-
this.onTraverse(this.model.node(rel.target));
|
|
1730
1927
|
return quantified(
|
|
1731
1928
|
relationshipPattern(this.model, variable, rel, m, r),
|
|
1732
1929
|
quantifier,
|
|
@@ -1738,9 +1935,8 @@ var WhereCompiler = class {
|
|
|
1738
1935
|
* the `actorsAggregate` form): `count`, `node`, `edge`, combined with AND / OR / NOT.
|
|
1739
1936
|
*/
|
|
1740
1937
|
aggregate(variable, rel, where, deprecated) {
|
|
1741
|
-
if (!
|
|
1938
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1742
1939
|
const target = this.model.node(rel.target);
|
|
1743
|
-
this.onTraverse(target);
|
|
1744
1940
|
const m = this.ctx.variable("n");
|
|
1745
1941
|
const r = this.ctx.variable("r");
|
|
1746
1942
|
const pattern = relationshipPattern(this.model, variable, rel, m, r);
|
|
@@ -1755,13 +1951,13 @@ var WhereCompiler = class {
|
|
|
1755
1951
|
continue;
|
|
1756
1952
|
}
|
|
1757
1953
|
if (key === "count") {
|
|
1758
|
-
if (!
|
|
1954
|
+
if (!isFilterObject(value, key)) continue;
|
|
1759
1955
|
if (deprecated) {
|
|
1760
1956
|
parts.push(this.countFilter(scope, false, value));
|
|
1761
1957
|
continue;
|
|
1762
1958
|
}
|
|
1763
1959
|
for (const [what, filters] of Object.entries(value)) {
|
|
1764
|
-
if (!
|
|
1960
|
+
if (!isFilterObject(filters, what)) continue;
|
|
1765
1961
|
if (what === "nodes") parts.push(this.countFilter(scope, true, filters));
|
|
1766
1962
|
else if (what === "edges") parts.push(this.countFilter(scope, false, filters));
|
|
1767
1963
|
else throw new Error(`Unknown aggregation count filter ${what}`);
|
|
@@ -1802,7 +1998,7 @@ var WhereCompiler = class {
|
|
|
1802
1998
|
}
|
|
1803
1999
|
/** `${…}NodeAggregationWhereInput` / `${Properties}AggregationWhereInput`. */
|
|
1804
2000
|
aggregationWhere(scope, attributes, on, distinct, where) {
|
|
1805
|
-
if (!
|
|
2001
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1806
2002
|
const parts = [];
|
|
1807
2003
|
for (const [key, value] of Object.entries(where)) {
|
|
1808
2004
|
if (value === void 0 || value === null) continue;
|
|
@@ -1817,9 +2013,9 @@ var WhereCompiler = class {
|
|
|
1817
2013
|
}
|
|
1818
2014
|
const direct = attributes.find((a) => a.name === key);
|
|
1819
2015
|
if (direct) {
|
|
1820
|
-
if (!
|
|
2016
|
+
if (!isFilterObject(value, key)) continue;
|
|
1821
2017
|
for (const [aggOp, filters] of Object.entries(value)) {
|
|
1822
|
-
if (!
|
|
2018
|
+
if (!isFilterObject(filters, aggOp)) continue;
|
|
1823
2019
|
const fn = GENERIC_AGGREGATES[aggOp];
|
|
1824
2020
|
if (!fn) throw new Error(`Invalid aggregation operator ${aggOp}`);
|
|
1825
2021
|
const agg2 = this.aggregated(scope, direct, on, distinct, fn);
|
|
@@ -1850,7 +2046,7 @@ var WhereCompiler = class {
|
|
|
1850
2046
|
}
|
|
1851
2047
|
/** Predicate for a `${Source}${Rel}ConnectionWhere` input (`node` / `edge`, AND / OR / NOT). */
|
|
1852
2048
|
connection(relVar, nodeVar, rel, where) {
|
|
1853
|
-
if (!
|
|
2049
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1854
2050
|
const parts = [];
|
|
1855
2051
|
for (const [key, value] of Object.entries(where)) {
|
|
1856
2052
|
if (value === void 0) continue;
|
|
@@ -1874,7 +2070,7 @@ var WhereCompiler = class {
|
|
|
1874
2070
|
}
|
|
1875
2071
|
/** Predicate for a `${Properties}Where` input on a relationship variable. */
|
|
1876
2072
|
edge(relVar, props, where) {
|
|
1877
|
-
if (!
|
|
2073
|
+
if (!isFilterObject(where, "filter")) return void 0;
|
|
1878
2074
|
const parts = [];
|
|
1879
2075
|
for (const [key, value] of Object.entries(where)) {
|
|
1880
2076
|
if (value === void 0) continue;
|
|
@@ -1887,11 +2083,981 @@ var WhereCompiler = class {
|
|
|
1887
2083
|
if (!a.handled) throw new Error(`Unknown filter ${props.name}Where.${key}`);
|
|
1888
2084
|
parts.push(a.predicate);
|
|
1889
2085
|
}
|
|
1890
|
-
return and(parts);
|
|
1891
|
-
}
|
|
1892
|
-
};
|
|
2086
|
+
return and(parts);
|
|
2087
|
+
}
|
|
2088
|
+
};
|
|
2089
|
+
|
|
2090
|
+
// src/v7/auth/rules.ts
|
|
2091
|
+
function isRecord2(v) {
|
|
2092
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
|
|
2093
|
+
const proto = Object.getPrototypeOf(v);
|
|
2094
|
+
return proto === Object.prototype || proto === null;
|
|
2095
|
+
}
|
|
2096
|
+
function and2(parts) {
|
|
2097
|
+
const ps = parts.filter((p) => p !== void 0);
|
|
2098
|
+
if (ps.length === 0) return void 0;
|
|
2099
|
+
if (ps.length === 1) return ps[0];
|
|
2100
|
+
return ps.map((p) => `(${p})`).join(" AND ");
|
|
2101
|
+
}
|
|
2102
|
+
function or(parts) {
|
|
2103
|
+
const ps = parts.filter((p) => p !== void 0);
|
|
2104
|
+
if (ps.length === 0) return void 0;
|
|
2105
|
+
if (ps.length === 1) return ps[0];
|
|
2106
|
+
return ps.map((p) => `(${p})`).join(" OR ");
|
|
2107
|
+
}
|
|
2108
|
+
function jwtComparison(operator, claim, value) {
|
|
2109
|
+
switch (operator) {
|
|
2110
|
+
case "EQ":
|
|
2111
|
+
return `${claim} = ${value}`;
|
|
2112
|
+
case "IN":
|
|
2113
|
+
return `${claim} IN ${value}`;
|
|
2114
|
+
case "INCLUDES":
|
|
2115
|
+
return `${value} IN ${claim}`;
|
|
2116
|
+
case "CONTAINS":
|
|
2117
|
+
return `${claim} CONTAINS ${value}`;
|
|
2118
|
+
case "STARTS_WITH":
|
|
2119
|
+
return `${claim} STARTS WITH ${value}`;
|
|
2120
|
+
case "ENDS_WITH":
|
|
2121
|
+
return `${claim} ENDS WITH ${value}`;
|
|
2122
|
+
case "MATCHES":
|
|
2123
|
+
return `${claim} =~ ${value}`;
|
|
2124
|
+
case "LT":
|
|
2125
|
+
return `${claim} < ${value}`;
|
|
2126
|
+
case "LTE":
|
|
2127
|
+
return `${claim} <= ${value}`;
|
|
2128
|
+
case "GT":
|
|
2129
|
+
return `${claim} > ${value}`;
|
|
2130
|
+
case "GTE":
|
|
2131
|
+
return `${claim} >= ${value}`;
|
|
2132
|
+
}
|
|
2133
|
+
throw new GraphQLError3(`Invalid operator ${operator} in an authorization JWT filter`);
|
|
2134
|
+
}
|
|
2135
|
+
function annotations(node, attributes) {
|
|
2136
|
+
return [node.auth, ...attributes.map((a) => a.auth)];
|
|
2137
|
+
}
|
|
2138
|
+
var AuthRules = class {
|
|
2139
|
+
constructor(model, ctx, auth) {
|
|
2140
|
+
this.ctx = ctx;
|
|
2141
|
+
this.auth = auth;
|
|
2142
|
+
this.where = new WhereCompiler(model, ctx);
|
|
2143
|
+
}
|
|
2144
|
+
ctx;
|
|
2145
|
+
auth;
|
|
2146
|
+
where;
|
|
2147
|
+
isAuthenticatedParam;
|
|
2148
|
+
forbiddenParam;
|
|
2149
|
+
/** `$pN` holding the "Forbidden" message (one parameter per statement). */
|
|
2150
|
+
forbiddenMessage() {
|
|
2151
|
+
this.forbiddenParam ??= this.ctx.param("Forbidden");
|
|
2152
|
+
return this.forbiddenParam;
|
|
2153
|
+
}
|
|
2154
|
+
isAuthenticated() {
|
|
2155
|
+
this.isAuthenticatedParam ??= this.ctx.param(this.auth.isAuthenticated);
|
|
2156
|
+
return this.isAuthenticatedParam;
|
|
2157
|
+
}
|
|
2158
|
+
/**
|
|
2159
|
+
* Filter of the `filter` rules for `operation` on `variable` (type rules AND the rules of each of
|
|
2160
|
+
* `attributes`), or `undefined` when no rule applies.
|
|
2161
|
+
*/
|
|
2162
|
+
filter(variable, node, operation, attributes = []) {
|
|
2163
|
+
return and2(
|
|
2164
|
+
annotations(node, attributes).map(
|
|
2165
|
+
(a) => or(
|
|
2166
|
+
(a?.authorization?.filter ?? []).filter((r) => r.operations.includes(operation)).map((r) => this.rule(variable, node, r))
|
|
2167
|
+
)
|
|
2168
|
+
)
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
/**
|
|
2172
|
+
* Predicates of the `validate` rules for `operation` / `when`, one per annotation (type, then each
|
|
2173
|
+
* of `attributes`); each must hold.
|
|
2174
|
+
*/
|
|
2175
|
+
validations(variable, node, operation, when, attributes = []) {
|
|
2176
|
+
const out = [];
|
|
2177
|
+
for (const a of annotations(node, attributes)) {
|
|
2178
|
+
const p = or(
|
|
2179
|
+
(a?.authorization?.validate ?? []).filter((r) => r.operations.includes(operation) && r.when.includes(when)).map((r) => this.rule(variable, node, r))
|
|
2180
|
+
);
|
|
2181
|
+
if (p !== void 0) out.push(p);
|
|
2182
|
+
}
|
|
2183
|
+
return out;
|
|
2184
|
+
}
|
|
2185
|
+
/**
|
|
2186
|
+
* `true` when one of `validations` does not hold for the node (`null` counts as not holding), or
|
|
2187
|
+
* `undefined` when there is nothing to check.
|
|
2188
|
+
*/
|
|
2189
|
+
failure(validations) {
|
|
2190
|
+
if (!validations.length) return void 0;
|
|
2191
|
+
return or(validations.map((v) => `NOT coalesce(${v}, false)`));
|
|
2192
|
+
}
|
|
2193
|
+
/** {@link failure} of the validations of `operation` / `when`. */
|
|
2194
|
+
fails(variable, node, operation, when, attributes = []) {
|
|
2195
|
+
return this.failure(this.validations(variable, node, operation, when, attributes));
|
|
2196
|
+
}
|
|
2197
|
+
/** `CASE WHEN <failure> THEN 'Forbidden' END` (a failed-check message for mutations). */
|
|
2198
|
+
check(failure) {
|
|
2199
|
+
return failure === void 0 ? void 0 : `CASE WHEN ${failure} THEN ${this.forbiddenMessage()} END`;
|
|
2200
|
+
}
|
|
2201
|
+
rule(variable, node, rule) {
|
|
2202
|
+
const auth = rule.requireAuthentication ? `${this.isAuthenticated()} = true` : void 0;
|
|
2203
|
+
const where = this.ruleWhere(variable, node, this.populate(rule.where));
|
|
2204
|
+
return and2([auth, where]);
|
|
2205
|
+
}
|
|
2206
|
+
/** `{ node, jwt, AND, OR, NOT }`: keys combined with AND. */
|
|
2207
|
+
ruleWhere(variable, node, where) {
|
|
2208
|
+
const parts = [];
|
|
2209
|
+
for (const [key, value] of Object.entries(where)) {
|
|
2210
|
+
if (value === void 0 || value === null) continue;
|
|
2211
|
+
switch (key) {
|
|
2212
|
+
case "node":
|
|
2213
|
+
parts.push(this.where.node(variable, node, value));
|
|
2214
|
+
break;
|
|
2215
|
+
case "jwt":
|
|
2216
|
+
if (!isRecord2(value)) throw new GraphQLError3("Invalid authorization rule: jwt");
|
|
2217
|
+
parts.push(this.jwt(value));
|
|
2218
|
+
break;
|
|
2219
|
+
case "AND":
|
|
2220
|
+
case "OR": {
|
|
2221
|
+
const items = (Array.isArray(value) ? value : [value]).map((w) => {
|
|
2222
|
+
if (!isRecord2(w)) throw new GraphQLError3(`Invalid authorization rule: ${key}`);
|
|
2223
|
+
return this.ruleWhere(variable, node, w);
|
|
2224
|
+
});
|
|
2225
|
+
parts.push(key === "AND" ? and2(items) : or(items));
|
|
2226
|
+
break;
|
|
2227
|
+
}
|
|
2228
|
+
case "NOT": {
|
|
2229
|
+
if (!isRecord2(value)) throw new GraphQLError3("Invalid authorization rule: NOT");
|
|
2230
|
+
const inner = this.ruleWhere(variable, node, value);
|
|
2231
|
+
parts.push(inner === void 0 ? void 0 : `NOT (${inner})`);
|
|
2232
|
+
break;
|
|
2233
|
+
}
|
|
2234
|
+
default:
|
|
2235
|
+
throw new GraphQLError3(`Invalid authorization rule key ${key}`);
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
return and2(parts);
|
|
2239
|
+
}
|
|
2240
|
+
/** `jwt: { roles: { includes: "admin" } }`: `($claim IS NOT NULL AND $value IN $claim)`. */
|
|
2241
|
+
jwt(where) {
|
|
2242
|
+
const parts = [];
|
|
2243
|
+
for (const [key, value] of Object.entries(where)) {
|
|
2244
|
+
if (value === void 0) continue;
|
|
2245
|
+
if (key === "AND" || key === "OR") {
|
|
2246
|
+
const items = (Array.isArray(value) ? value : [value]).map((w) => {
|
|
2247
|
+
if (!isRecord2(w)) throw new GraphQLError3(`Invalid JWT filter ${key}`);
|
|
2248
|
+
return this.jwt(w);
|
|
2249
|
+
});
|
|
2250
|
+
parts.push(key === "AND" ? and2(items) : or(items));
|
|
2251
|
+
continue;
|
|
2252
|
+
}
|
|
2253
|
+
if (key === "NOT") {
|
|
2254
|
+
if (!isRecord2(value)) throw new GraphQLError3("Invalid JWT filter NOT");
|
|
2255
|
+
const inner = this.jwt(value);
|
|
2256
|
+
parts.push(inner === void 0 ? void 0 : `NOT (${inner})`);
|
|
2257
|
+
continue;
|
|
2258
|
+
}
|
|
2259
|
+
const { field, operator } = parseJwtWhereKey(key);
|
|
2260
|
+
const claim = this.ctx.param(claimValue(this.auth, field) ?? null);
|
|
2261
|
+
const comparisons = [];
|
|
2262
|
+
if (operator) {
|
|
2263
|
+
comparisons.push(jwtComparison(operator, claim, this.ctx.param(this.unwrap(value))));
|
|
2264
|
+
} else {
|
|
2265
|
+
if (!isRecord2(value)) throw new GraphQLError3(`Invalid JWT filter ${key}`);
|
|
2266
|
+
for (const [op, v] of Object.entries(value)) {
|
|
2267
|
+
if (v === void 0) continue;
|
|
2268
|
+
const legacy = GENERIC_OPERATORS[op];
|
|
2269
|
+
if (!legacy)
|
|
2270
|
+
throw new GraphQLError3(`Invalid operator ${op} in an authorization JWT filter`);
|
|
2271
|
+
comparisons.push(jwtComparison(legacy, claim, this.ctx.param(this.unwrap(v))));
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
const cmp = and2(comparisons);
|
|
2275
|
+
parts.push(cmp === void 0 ? void 0 : `(${claim} IS NOT NULL AND ${cmp})`);
|
|
2276
|
+
}
|
|
2277
|
+
return and2(parts);
|
|
2278
|
+
}
|
|
2279
|
+
unwrap(v) {
|
|
2280
|
+
return v instanceof AuthValue ? v.value ?? null : v ?? null;
|
|
2281
|
+
}
|
|
2282
|
+
/**
|
|
2283
|
+
* Copy of a rule `where` with `$jwt.<path>` / `$context.<path>` strings replaced by their values
|
|
2284
|
+
* for this request ({@link AuthValue}); like v7, strings inside lists are left as they are.
|
|
2285
|
+
*/
|
|
2286
|
+
populate(value, key) {
|
|
2287
|
+
if (typeof value === "string") return this.reference(value);
|
|
2288
|
+
if (Array.isArray(value)) {
|
|
2289
|
+
return key === "AND" || key === "OR" ? value.map((v) => this.populate(v)) : value;
|
|
2290
|
+
}
|
|
2291
|
+
if (isRecord2(value)) {
|
|
2292
|
+
const out = {};
|
|
2293
|
+
for (const [k, v] of Object.entries(value)) out[k] = this.populate(v, k);
|
|
2294
|
+
return out;
|
|
2295
|
+
}
|
|
2296
|
+
return value;
|
|
2297
|
+
}
|
|
2298
|
+
reference(value) {
|
|
2299
|
+
if (value.startsWith("$jwt")) {
|
|
2300
|
+
const path = value.substring(5);
|
|
2301
|
+
const mapped = this.auth.claims?.get(path) ?? path;
|
|
2302
|
+
return new AuthValue(readPath(this.auth.jwt ?? {}, mapped.split(".")));
|
|
2303
|
+
}
|
|
2304
|
+
if (value.startsWith("$context")) {
|
|
2305
|
+
return new AuthValue(readPath(this.auth.context, value.substring(9).split(".")));
|
|
2306
|
+
}
|
|
2307
|
+
return value;
|
|
2308
|
+
}
|
|
2309
|
+
};
|
|
2310
|
+
|
|
2311
|
+
// src/v7/model.ts
|
|
2312
|
+
import {
|
|
2313
|
+
Kind as Kind3,
|
|
2314
|
+
parse as parse2,
|
|
2315
|
+
valueFromASTUntyped as valueFromASTUntyped2
|
|
2316
|
+
} from "graphql";
|
|
2317
|
+
|
|
2318
|
+
// src/v7/naming.ts
|
|
2319
|
+
import pluralizeLib from "pluralize";
|
|
2320
|
+
function upperFirst(s) {
|
|
2321
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
2322
|
+
}
|
|
2323
|
+
function camelCase(input) {
|
|
2324
|
+
const s = input.replace(/^_+/, "");
|
|
2325
|
+
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);
|
|
2326
|
+
return words.map((w, i) => i === 0 ? w.toLowerCase() : upperFirst(w.toLowerCase())).join("");
|
|
2327
|
+
}
|
|
2328
|
+
function leadingUnderscores(name) {
|
|
2329
|
+
return /^_+/.exec(name)?.[0] ?? "";
|
|
2330
|
+
}
|
|
2331
|
+
function pluralize(word) {
|
|
2332
|
+
return pluralizeLib(word);
|
|
2333
|
+
}
|
|
2334
|
+
function entityPlural(name, pluralOverride) {
|
|
2335
|
+
if (pluralOverride !== void 0)
|
|
2336
|
+
return `${leadingUnderscores(pluralOverride)}${camelCase(pluralOverride)}`;
|
|
2337
|
+
return `${leadingUnderscores(name)}${pluralizeLib(camelCase(name))}`;
|
|
2338
|
+
}
|
|
2339
|
+
|
|
2340
|
+
// src/v7/model.ts
|
|
2341
|
+
var SUPPORTED_SCALARS = [
|
|
2342
|
+
"ID",
|
|
2343
|
+
"String",
|
|
2344
|
+
"Int",
|
|
2345
|
+
"Float",
|
|
2346
|
+
"Boolean",
|
|
2347
|
+
"BigInt",
|
|
2348
|
+
"Date",
|
|
2349
|
+
"DateTime"
|
|
2350
|
+
];
|
|
2351
|
+
var UNSUPPORTED_SCALARS = /* @__PURE__ */ new Set([
|
|
2352
|
+
"LocalDateTime",
|
|
2353
|
+
"Time",
|
|
2354
|
+
"LocalTime",
|
|
2355
|
+
"Duration",
|
|
2356
|
+
"Point",
|
|
2357
|
+
"CartesianPoint"
|
|
2358
|
+
]);
|
|
2359
|
+
var AUTH_OPERATIONS = [
|
|
2360
|
+
"READ",
|
|
2361
|
+
"AGGREGATE",
|
|
2362
|
+
"CREATE",
|
|
2363
|
+
"UPDATE",
|
|
2364
|
+
"DELETE",
|
|
2365
|
+
"CREATE_RELATIONSHIP",
|
|
2366
|
+
"DELETE_RELATIONSHIP",
|
|
2367
|
+
"SUBSCRIBE"
|
|
2368
|
+
];
|
|
2369
|
+
var FILTER_OPERATIONS = [
|
|
2370
|
+
"READ",
|
|
2371
|
+
"AGGREGATE",
|
|
2372
|
+
"UPDATE",
|
|
2373
|
+
"DELETE",
|
|
2374
|
+
"CREATE_RELATIONSHIP",
|
|
2375
|
+
"DELETE_RELATIONSHIP"
|
|
2376
|
+
];
|
|
2377
|
+
var VALIDATE_OPERATIONS = [
|
|
2378
|
+
"READ",
|
|
2379
|
+
"AGGREGATE",
|
|
2380
|
+
"CREATE",
|
|
2381
|
+
"UPDATE",
|
|
2382
|
+
"DELETE",
|
|
2383
|
+
"CREATE_RELATIONSHIP",
|
|
2384
|
+
"DELETE_RELATIONSHIP"
|
|
2385
|
+
];
|
|
2386
|
+
var UnsupportedTypeDefsError = class extends Error {
|
|
2387
|
+
name = "UnsupportedTypeDefsError";
|
|
2388
|
+
};
|
|
2389
|
+
function directive2(dirs, name) {
|
|
2390
|
+
return dirs?.find((d) => d.name.value === name);
|
|
2391
|
+
}
|
|
2392
|
+
function arg2(d, name) {
|
|
2393
|
+
return d?.arguments?.find((a) => a.name.value === name)?.value;
|
|
2394
|
+
}
|
|
2395
|
+
function stringArg2(d, name) {
|
|
2396
|
+
const v = arg2(d, name);
|
|
2397
|
+
return v && (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) ? v.value : void 0;
|
|
2398
|
+
}
|
|
2399
|
+
function listArg(d, name) {
|
|
2400
|
+
const v = arg2(d, name);
|
|
2401
|
+
if (!v) return void 0;
|
|
2402
|
+
if (v.kind === Kind3.LIST) {
|
|
2403
|
+
return v.values.flatMap(
|
|
2404
|
+
(x) => x.kind === Kind3.STRING || x.kind === Kind3.ENUM ? [x.value] : []
|
|
2405
|
+
);
|
|
2406
|
+
}
|
|
2407
|
+
if (v.kind === Kind3.STRING || v.kind === Kind3.ENUM) return [v.value];
|
|
2408
|
+
return void 0;
|
|
2409
|
+
}
|
|
2410
|
+
function typeRef(t) {
|
|
2411
|
+
let cur = t;
|
|
2412
|
+
let required = false;
|
|
2413
|
+
if (cur.kind === Kind3.NON_NULL_TYPE) {
|
|
2414
|
+
required = true;
|
|
2415
|
+
cur = cur.type;
|
|
2416
|
+
}
|
|
2417
|
+
if (cur.kind === Kind3.LIST_TYPE) {
|
|
2418
|
+
let inner = cur.type;
|
|
2419
|
+
let elementRequired = false;
|
|
2420
|
+
if (inner.kind === Kind3.NON_NULL_TYPE) {
|
|
2421
|
+
elementRequired = true;
|
|
2422
|
+
inner = inner.type;
|
|
2423
|
+
}
|
|
2424
|
+
if (inner.kind !== Kind3.NAMED_TYPE)
|
|
2425
|
+
throw new UnsupportedTypeDefsError("Nested lists are not supported.");
|
|
2426
|
+
return { name: inner.name.value, list: true, required, elementRequired };
|
|
2427
|
+
}
|
|
2428
|
+
return {
|
|
2429
|
+
name: cur.name.value,
|
|
2430
|
+
list: false,
|
|
2431
|
+
required,
|
|
2432
|
+
elementRequired: false
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
var ACCEPTED_FIELD_DIRECTIVES = /* @__PURE__ */ new Set([
|
|
2436
|
+
"authentication",
|
|
2437
|
+
"authorization",
|
|
2438
|
+
"id",
|
|
2439
|
+
"default",
|
|
2440
|
+
"timestamp",
|
|
2441
|
+
"cypher",
|
|
2442
|
+
"relationship",
|
|
2443
|
+
"alias",
|
|
2444
|
+
"deprecated",
|
|
2445
|
+
"coalesce",
|
|
2446
|
+
"unique"
|
|
2447
|
+
]);
|
|
2448
|
+
var ACCEPTED_TYPE_DIRECTIVES = /* @__PURE__ */ new Set([
|
|
2449
|
+
"node",
|
|
2450
|
+
"fulltext",
|
|
2451
|
+
"plural",
|
|
2452
|
+
"authentication",
|
|
2453
|
+
"authorization",
|
|
2454
|
+
"relationshipProperties",
|
|
2455
|
+
"jwt"
|
|
2456
|
+
]);
|
|
2457
|
+
function deprecationReason(dirs) {
|
|
2458
|
+
const d = directive2(dirs, "deprecated");
|
|
2459
|
+
if (!d) return void 0;
|
|
2460
|
+
return stringArg2(d, "reason") ?? "No longer supported";
|
|
2461
|
+
}
|
|
2462
|
+
function readAttribute(owner, f, enums) {
|
|
2463
|
+
for (const d of f.directives ?? []) {
|
|
2464
|
+
if (!ACCEPTED_FIELD_DIRECTIVES.has(d.name.value)) {
|
|
2465
|
+
throw new UnsupportedTypeDefsError(
|
|
2466
|
+
`${owner}.${f.name.value}: @${d.name.value} is not supported by @cyphra/graphql yet.`
|
|
2467
|
+
);
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
const cypher = readCypher(`${owner}.${f.name.value}`, directive2(f.directives, "cypher"));
|
|
2471
|
+
if (f.arguments?.length && !cypher) {
|
|
2472
|
+
throw new UnsupportedTypeDefsError(
|
|
2473
|
+
`${owner}.${f.name.value}: field arguments are only supported on @cypher fields.`
|
|
2474
|
+
);
|
|
2475
|
+
}
|
|
2476
|
+
const type = typeRef(f.type);
|
|
2477
|
+
const isEnum = enums.has(type.name);
|
|
2478
|
+
if (!isEnum && !SUPPORTED_SCALARS.includes(type.name)) {
|
|
2479
|
+
if (UNSUPPORTED_SCALARS.has(type.name)) {
|
|
2480
|
+
throw new UnsupportedTypeDefsError(
|
|
2481
|
+
`${owner}.${f.name.value}: ${type.name} is not supported by @cyphra/graphql yet.`
|
|
2482
|
+
);
|
|
2483
|
+
}
|
|
2484
|
+
throw new UnsupportedTypeDefsError(
|
|
2485
|
+
`${owner}.${f.name.value}: type ${type.name} is not a supported scalar or enum (fields returning objects need @relationship).`
|
|
2486
|
+
);
|
|
2487
|
+
}
|
|
2488
|
+
const dirs = f.directives;
|
|
2489
|
+
const def = directive2(dirs, "default");
|
|
2490
|
+
const defaultAst = arg2(def, "value");
|
|
2491
|
+
const ts = directive2(dirs, "timestamp");
|
|
2492
|
+
const alias = directive2(dirs, "alias");
|
|
2493
|
+
return {
|
|
2494
|
+
name: f.name.value,
|
|
2495
|
+
property: stringArg2(alias, "property") ?? f.name.value,
|
|
2496
|
+
type,
|
|
2497
|
+
kind: isEnum ? "enum" : "scalar",
|
|
2498
|
+
description: f.description?.value,
|
|
2499
|
+
id: !!directive2(dirs, "id"),
|
|
2500
|
+
defaultAst,
|
|
2501
|
+
defaultValue: defaultAst ? valueFromASTUntyped2(defaultAst) : void 0,
|
|
2502
|
+
timestamp: ts ? listArg(ts, "operations") ?? ["CREATE", "UPDATE"] : void 0,
|
|
2503
|
+
cypher,
|
|
2504
|
+
args: readArguments(`${owner}.${f.name.value}`, f, enums),
|
|
2505
|
+
deprecated: deprecationReason(dirs),
|
|
2506
|
+
auth: readAuthAnnotations(`${owner}.${f.name.value}`, dirs)
|
|
2507
|
+
};
|
|
2508
|
+
}
|
|
2509
|
+
function readCypher(where, d) {
|
|
2510
|
+
if (!d) return void 0;
|
|
2511
|
+
for (const a of d.arguments ?? []) {
|
|
2512
|
+
if (!["statement", "columnName"].includes(a.name.value)) {
|
|
2513
|
+
throw new UnsupportedTypeDefsError(`${where}: @cypher(${a.name.value}) is not supported.`);
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2516
|
+
const statement = stringArg2(d, "statement");
|
|
2517
|
+
const columnName = stringArg2(d, "columnName");
|
|
2518
|
+
if (!statement || !columnName) {
|
|
2519
|
+
throw new UnsupportedTypeDefsError(`${where}: @cypher needs a statement and a columnName.`);
|
|
2520
|
+
}
|
|
2521
|
+
return { statement, columnName };
|
|
2522
|
+
}
|
|
2523
|
+
function readArguments(where, f, enums) {
|
|
2524
|
+
return (f.arguments ?? []).map((a) => {
|
|
2525
|
+
if (a.directives?.length) {
|
|
2526
|
+
throw new UnsupportedTypeDefsError(
|
|
2527
|
+
`${where}(${a.name.value}): directives on arguments are not supported.`
|
|
2528
|
+
);
|
|
2529
|
+
}
|
|
2530
|
+
const type = typeRef(a.type);
|
|
2531
|
+
const isEnum = enums.has(type.name);
|
|
2532
|
+
if (!isEnum && !SUPPORTED_SCALARS.includes(type.name)) {
|
|
2533
|
+
throw new UnsupportedTypeDefsError(
|
|
2534
|
+
`${where}(${a.name.value}): arguments of type ${type.name} are not supported by @cyphra/graphql yet (scalars and enums only).`
|
|
2535
|
+
);
|
|
2536
|
+
}
|
|
2537
|
+
return {
|
|
2538
|
+
name: a.name.value,
|
|
2539
|
+
type,
|
|
2540
|
+
kind: isEnum ? "enum" : "scalar",
|
|
2541
|
+
description: a.description?.value,
|
|
2542
|
+
defaultAst: a.defaultValue
|
|
2543
|
+
};
|
|
2544
|
+
});
|
|
2545
|
+
}
|
|
2546
|
+
function isRecord3(v) {
|
|
2547
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2548
|
+
}
|
|
2549
|
+
function operationList(where, value, allowed) {
|
|
2550
|
+
if (value === void 0 || value === null) return void 0;
|
|
2551
|
+
const list2 = Array.isArray(value) ? value : [value];
|
|
2552
|
+
return list2.map((op) => {
|
|
2553
|
+
if (typeof op !== "string" || !allowed.includes(op)) {
|
|
2554
|
+
throw new UnsupportedTypeDefsError(`${where}: invalid operation ${String(op)}.`);
|
|
2555
|
+
}
|
|
2556
|
+
return op;
|
|
2557
|
+
});
|
|
2558
|
+
}
|
|
2559
|
+
var RULE_WHERE_KEYS = /* @__PURE__ */ new Set(["node", "jwt", "AND", "OR", "NOT"]);
|
|
2560
|
+
function checkRuleWhere(where, value) {
|
|
2561
|
+
if (!isRecord3(value))
|
|
2562
|
+
throw new UnsupportedTypeDefsError(`${where}: \`where\` must be an object.`);
|
|
2563
|
+
for (const [k, v] of Object.entries(value)) {
|
|
2564
|
+
if (!RULE_WHERE_KEYS.has(k)) {
|
|
2565
|
+
throw new UnsupportedTypeDefsError(`${where}: unknown key ${k} in \`where\`.`);
|
|
2566
|
+
}
|
|
2567
|
+
if (k === "AND" || k === "OR") {
|
|
2568
|
+
if (!Array.isArray(v)) throw new UnsupportedTypeDefsError(`${where}: ${k} must be a list.`);
|
|
2569
|
+
v.forEach((x) => checkRuleWhere(where, x));
|
|
2570
|
+
} else if (k === "NOT") {
|
|
2571
|
+
checkRuleWhere(where, v);
|
|
2572
|
+
} else if (!isRecord3(v)) {
|
|
2573
|
+
throw new UnsupportedTypeDefsError(`${where}: \`${k}\` must be an object.`);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
return value;
|
|
2577
|
+
}
|
|
2578
|
+
function readRules(where, value, allowed) {
|
|
2579
|
+
if (value === void 0 || value === null) return [];
|
|
2580
|
+
const list2 = Array.isArray(value) ? value : [value];
|
|
2581
|
+
return list2.map((rule, i) => {
|
|
2582
|
+
const at = `${where}[${i}]`;
|
|
2583
|
+
if (!isRecord3(rule)) throw new UnsupportedTypeDefsError(`${at}: a rule must be an object.`);
|
|
2584
|
+
for (const k of Object.keys(rule)) {
|
|
2585
|
+
if (!["operations", "requireAuthentication", "where", "when"].includes(k)) {
|
|
2586
|
+
throw new UnsupportedTypeDefsError(`${at}: unknown rule argument ${k}.`);
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
if (rule.requireAuthentication !== void 0 && typeof rule.requireAuthentication !== "boolean") {
|
|
2590
|
+
throw new UnsupportedTypeDefsError(`${at}: requireAuthentication must be a Boolean.`);
|
|
2591
|
+
}
|
|
2592
|
+
return {
|
|
2593
|
+
operations: operationList(at, rule.operations, allowed) ?? [...allowed],
|
|
2594
|
+
requireAuthentication: rule.requireAuthentication !== false,
|
|
2595
|
+
where: checkRuleWhere(at, rule.where),
|
|
2596
|
+
raw: rule
|
|
2597
|
+
};
|
|
2598
|
+
});
|
|
2599
|
+
}
|
|
2600
|
+
function readAuthentication(where, d) {
|
|
2601
|
+
if (!d) return void 0;
|
|
2602
|
+
for (const a of d.arguments ?? []) {
|
|
2603
|
+
if (!["operations", "jwt"].includes(a.name.value)) {
|
|
2604
|
+
throw new UnsupportedTypeDefsError(
|
|
2605
|
+
`${where}: @authentication(${a.name.value}) is not supported.`
|
|
2606
|
+
);
|
|
2607
|
+
}
|
|
2608
|
+
}
|
|
2609
|
+
const opsArg = arg2(d, "operations");
|
|
2610
|
+
const jwtArg = arg2(d, "jwt");
|
|
2611
|
+
const jwt = jwtArg ? valueFromASTUntyped2(jwtArg) : void 0;
|
|
2612
|
+
if (jwt !== void 0 && jwt !== null && !isRecord3(jwt)) {
|
|
2613
|
+
throw new UnsupportedTypeDefsError(`${where}: @authentication(jwt) must be an object.`);
|
|
2614
|
+
}
|
|
2615
|
+
const operations = operationList(
|
|
2616
|
+
`${where} @authentication`,
|
|
2617
|
+
opsArg ? valueFromASTUntyped2(opsArg) : void 0,
|
|
2618
|
+
AUTH_OPERATIONS
|
|
2619
|
+
) ?? AUTH_OPERATIONS;
|
|
2620
|
+
return { operations: new Set(operations), jwt: jwt ?? void 0 };
|
|
2621
|
+
}
|
|
2622
|
+
function readAuthorization(where, d) {
|
|
2623
|
+
if (!d) return void 0;
|
|
2624
|
+
for (const a of d.arguments ?? []) {
|
|
2625
|
+
if (!["filter", "validate"].includes(a.name.value)) {
|
|
2626
|
+
throw new UnsupportedTypeDefsError(
|
|
2627
|
+
`${where}: @authorization(${a.name.value}) is not supported.`
|
|
2628
|
+
);
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
const filterArg = arg2(d, "filter");
|
|
2632
|
+
const validateArg = arg2(d, "validate");
|
|
2633
|
+
const filter = readRules(
|
|
2634
|
+
`${where} @authorization(filter)`,
|
|
2635
|
+
filterArg ? valueFromASTUntyped2(filterArg) : void 0,
|
|
2636
|
+
FILTER_OPERATIONS
|
|
2637
|
+
).map((r) => {
|
|
2638
|
+
if (r.raw.when !== void 0) {
|
|
2639
|
+
throw new UnsupportedTypeDefsError(
|
|
2640
|
+
`${where} @authorization(filter): \`when\` only applies to validate rules.`
|
|
2641
|
+
);
|
|
2642
|
+
}
|
|
2643
|
+
return {
|
|
2644
|
+
operations: r.operations,
|
|
2645
|
+
requireAuthentication: r.requireAuthentication,
|
|
2646
|
+
where: r.where
|
|
2647
|
+
};
|
|
2648
|
+
});
|
|
2649
|
+
const validate = readRules(
|
|
2650
|
+
`${where} @authorization(validate)`,
|
|
2651
|
+
validateArg ? valueFromASTUntyped2(validateArg) : void 0,
|
|
2652
|
+
VALIDATE_OPERATIONS
|
|
2653
|
+
).map((r) => {
|
|
2654
|
+
const when = r.raw.when === void 0 || r.raw.when === null ? ["BEFORE", "AFTER"] : r.raw.when;
|
|
2655
|
+
const list2 = Array.isArray(when) ? when : [when];
|
|
2656
|
+
for (const w of list2) {
|
|
2657
|
+
if (w !== "BEFORE" && w !== "AFTER") {
|
|
2658
|
+
throw new UnsupportedTypeDefsError(
|
|
2659
|
+
`${where} @authorization(validate): invalid when ${String(w)}.`
|
|
2660
|
+
);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
return {
|
|
2664
|
+
operations: r.operations,
|
|
2665
|
+
requireAuthentication: r.requireAuthentication,
|
|
2666
|
+
where: r.where,
|
|
2667
|
+
when: list2
|
|
2668
|
+
};
|
|
2669
|
+
});
|
|
2670
|
+
return { filter, validate };
|
|
2671
|
+
}
|
|
2672
|
+
function readAuthAnnotations(where, dirs) {
|
|
2673
|
+
const authentication = readAuthentication(where, directive2(dirs, "authentication"));
|
|
2674
|
+
const authorization = readAuthorization(where, directive2(dirs, "authorization"));
|
|
2675
|
+
return authentication || authorization ? { authentication, authorization } : void 0;
|
|
2676
|
+
}
|
|
2677
|
+
function readJwtClaims(o) {
|
|
2678
|
+
const claims = /* @__PURE__ */ new Map();
|
|
2679
|
+
for (const f of o.fields ?? []) {
|
|
2680
|
+
for (const d of f.directives ?? []) {
|
|
2681
|
+
if (d.name.value !== "jwtClaim") {
|
|
2682
|
+
throw new UnsupportedTypeDefsError(
|
|
2683
|
+
`${o.name.value}.${f.name.value}: @${d.name.value} is not supported on the @jwt type.`
|
|
2684
|
+
);
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
const path = stringArg2(directive2(f.directives, "jwtClaim"), "path");
|
|
2688
|
+
if (path) claims.set(f.name.value, path);
|
|
2689
|
+
}
|
|
2690
|
+
return claims;
|
|
2691
|
+
}
|
|
2692
|
+
var CYPHER_FIELD_DIRECTIVES = /* @__PURE__ */ new Set(["cypher", "deprecated"]);
|
|
2693
|
+
function readCypherNodeField(owner, f, enums) {
|
|
2694
|
+
const where = `${owner}.${f.name.value}`;
|
|
2695
|
+
for (const d of f.directives ?? []) {
|
|
2696
|
+
if (!CYPHER_FIELD_DIRECTIVES.has(d.name.value)) {
|
|
2697
|
+
throw new UnsupportedTypeDefsError(
|
|
2698
|
+
`${where}: @${d.name.value} on a @cypher field returning nodes is not supported by @cyphra/graphql yet.`
|
|
2699
|
+
);
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
const type = typeRef(f.type);
|
|
2703
|
+
return {
|
|
2704
|
+
name: f.name.value,
|
|
2705
|
+
target: type.name,
|
|
2706
|
+
type,
|
|
2707
|
+
cypher: readCypher(where, directive2(f.directives, "cypher")),
|
|
2708
|
+
args: readArguments(where, f, enums),
|
|
2709
|
+
description: f.description?.value,
|
|
2710
|
+
deprecated: deprecationReason(f.directives)
|
|
2711
|
+
};
|
|
2712
|
+
}
|
|
2713
|
+
function readRootType(o, enums, nodes) {
|
|
2714
|
+
if (!o) return { fields: [] };
|
|
2715
|
+
const type = o.name.value;
|
|
2716
|
+
let authentication;
|
|
2717
|
+
for (const d of o.directives ?? []) {
|
|
2718
|
+
if (d.name.value !== "authentication") {
|
|
2719
|
+
throw new UnsupportedTypeDefsError(
|
|
2720
|
+
`type ${type}: @${d.name.value} is not supported by @cyphra/graphql yet.`
|
|
2721
|
+
);
|
|
2722
|
+
}
|
|
2723
|
+
authentication = readAuthentication(`type ${type}`, d);
|
|
2724
|
+
}
|
|
2725
|
+
const fields = (o.fields ?? []).map((f) => {
|
|
2726
|
+
const where = `${type}.${f.name.value}`;
|
|
2727
|
+
for (const d of f.directives ?? []) {
|
|
2728
|
+
if (!["cypher", "deprecated", "authentication"].includes(d.name.value)) {
|
|
2729
|
+
throw new UnsupportedTypeDefsError(
|
|
2730
|
+
`${where}: @${d.name.value} is not supported on ${type} fields by @cyphra/graphql yet.`
|
|
2731
|
+
);
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
const cypher = readCypher(where, directive2(f.directives, "cypher"));
|
|
2735
|
+
if (!cypher) {
|
|
2736
|
+
throw new UnsupportedTypeDefsError(
|
|
2737
|
+
`${where}: custom ${type} fields need @cypher (custom resolvers are not supported by @cyphra/graphql).`
|
|
2738
|
+
);
|
|
2739
|
+
}
|
|
2740
|
+
const t = typeRef(f.type);
|
|
2741
|
+
const kind = nodes.has(t.name) ? "node" : enums.has(t.name) ? "enum" : "scalar";
|
|
2742
|
+
if (kind === "scalar" && !SUPPORTED_SCALARS.includes(t.name)) {
|
|
2743
|
+
throw new UnsupportedTypeDefsError(
|
|
2744
|
+
`${where}: type ${t.name} is not supported by @cyphra/graphql yet (@node types, scalars and enums only).`
|
|
2745
|
+
);
|
|
2746
|
+
}
|
|
2747
|
+
return {
|
|
2748
|
+
name: f.name.value,
|
|
2749
|
+
type: t,
|
|
2750
|
+
kind,
|
|
2751
|
+
cypher,
|
|
2752
|
+
args: readArguments(where, f, enums),
|
|
2753
|
+
description: f.description?.value,
|
|
2754
|
+
deprecated: deprecationReason(f.directives),
|
|
2755
|
+
authentication: readAuthentication(where, directive2(f.directives, "authentication"))
|
|
2756
|
+
};
|
|
2757
|
+
});
|
|
2758
|
+
return { fields, authentication };
|
|
2759
|
+
}
|
|
2760
|
+
function readFulltext(owner, d, attributes) {
|
|
2761
|
+
if (!d) return [];
|
|
2762
|
+
const where = `type ${owner} @fulltext`;
|
|
2763
|
+
const value = arg2(d, "indexes");
|
|
2764
|
+
const indexes = value ? valueFromASTUntyped2(value) : void 0;
|
|
2765
|
+
if (!Array.isArray(indexes))
|
|
2766
|
+
throw new UnsupportedTypeDefsError(`${where}: indexes must be a list.`);
|
|
2767
|
+
return indexes.map((ix, i) => {
|
|
2768
|
+
if (!isRecord3(ix))
|
|
2769
|
+
throw new UnsupportedTypeDefsError(`${where}: indexes[${i}] must be an object.`);
|
|
2770
|
+
for (const k of Object.keys(ix)) {
|
|
2771
|
+
if (!["indexName", "queryName", "fields"].includes(k)) {
|
|
2772
|
+
throw new UnsupportedTypeDefsError(`${where}: unknown index argument ${k}.`);
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
const { indexName, queryName, fields } = ix;
|
|
2776
|
+
if (typeof indexName !== "string" || typeof queryName !== "string" || !Array.isArray(fields)) {
|
|
2777
|
+
throw new UnsupportedTypeDefsError(
|
|
2778
|
+
`${where}: indexes[${i}] needs indexName, queryName and fields.`
|
|
2779
|
+
);
|
|
2780
|
+
}
|
|
2781
|
+
for (const field of fields) {
|
|
2782
|
+
const a = attributes.find((x) => x.name === field);
|
|
2783
|
+
if (!a || a.cypher || a.type.name !== "String" && a.type.name !== "ID") {
|
|
2784
|
+
throw new UnsupportedTypeDefsError(
|
|
2785
|
+
`${where}: field ${String(field)} must be a String or ID field of ${owner}.`
|
|
2786
|
+
);
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
return { indexName, queryName, fields };
|
|
2790
|
+
});
|
|
2791
|
+
}
|
|
2792
|
+
function readTypeDefs(typeDefs) {
|
|
2793
|
+
const doc = parse2(typeDefs);
|
|
2794
|
+
const objects = [];
|
|
2795
|
+
const enums = /* @__PURE__ */ new Map();
|
|
2796
|
+
let schemaAuthentication;
|
|
2797
|
+
for (const def of doc.definitions) {
|
|
2798
|
+
switch (def.kind) {
|
|
2799
|
+
case Kind3.SCHEMA_EXTENSION:
|
|
2800
|
+
case Kind3.SCHEMA_DEFINITION: {
|
|
2801
|
+
if (def.operationTypes?.length) {
|
|
2802
|
+
throw new UnsupportedTypeDefsError(
|
|
2803
|
+
"schema: custom root operation types are not supported by @cyphra/graphql yet."
|
|
2804
|
+
);
|
|
2805
|
+
}
|
|
2806
|
+
for (const d of def.directives ?? []) {
|
|
2807
|
+
if (d.name.value !== "authentication") {
|
|
2808
|
+
throw new UnsupportedTypeDefsError(
|
|
2809
|
+
`schema: @${d.name.value} is not supported by @cyphra/graphql yet.`
|
|
2810
|
+
);
|
|
2811
|
+
}
|
|
2812
|
+
if (schemaAuthentication) {
|
|
2813
|
+
throw new UnsupportedTypeDefsError("schema: @authentication is set more than once.");
|
|
2814
|
+
}
|
|
2815
|
+
schemaAuthentication = readAuthentication("schema", d);
|
|
2816
|
+
}
|
|
2817
|
+
break;
|
|
2818
|
+
}
|
|
2819
|
+
case Kind3.OBJECT_TYPE_DEFINITION:
|
|
2820
|
+
objects.push(def);
|
|
2821
|
+
break;
|
|
2822
|
+
case Kind3.ENUM_TYPE_DEFINITION:
|
|
2823
|
+
enums.set(def.name.value, {
|
|
2824
|
+
name: def.name.value,
|
|
2825
|
+
description: def.description?.value,
|
|
2826
|
+
values: (def.values ?? []).map((v) => ({
|
|
2827
|
+
name: v.name.value,
|
|
2828
|
+
description: v.description?.value,
|
|
2829
|
+
deprecated: deprecationReason(v.directives)
|
|
2830
|
+
}))
|
|
2831
|
+
});
|
|
2832
|
+
break;
|
|
2833
|
+
case Kind3.SCALAR_TYPE_DEFINITION:
|
|
2834
|
+
if (!SUPPORTED_SCALARS.includes(def.name.value)) {
|
|
2835
|
+
throw new UnsupportedTypeDefsError(
|
|
2836
|
+
`scalar ${def.name.value}: custom scalars are not supported by @cyphra/graphql yet.`
|
|
2837
|
+
);
|
|
2838
|
+
}
|
|
2839
|
+
break;
|
|
2840
|
+
case Kind3.DIRECTIVE_DEFINITION:
|
|
2841
|
+
break;
|
|
2842
|
+
default:
|
|
2843
|
+
throw new UnsupportedTypeDefsError(
|
|
2844
|
+
`${def.kind}${"name" in def && def.name ? ` ${def.name.value}` : ""}: not supported by @cyphra/graphql yet (only object types, enums and relationship properties).`
|
|
2845
|
+
);
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
const enumNames = new Set(enums.keys());
|
|
2849
|
+
const properties = /* @__PURE__ */ new Map();
|
|
2850
|
+
const nodeDefs = [];
|
|
2851
|
+
const rootDefs = /* @__PURE__ */ new Map();
|
|
2852
|
+
let jwtClaims;
|
|
2853
|
+
for (const o of objects) {
|
|
2854
|
+
const name = o.name.value;
|
|
2855
|
+
if (name === "Subscription") {
|
|
2856
|
+
throw new UnsupportedTypeDefsError(
|
|
2857
|
+
"type Subscription: subscriptions are not supported by @cyphra/graphql yet."
|
|
2858
|
+
);
|
|
2859
|
+
}
|
|
2860
|
+
if (name === "Query" || name === "Mutation") {
|
|
2861
|
+
if (rootDefs.has(name)) {
|
|
2862
|
+
throw new UnsupportedTypeDefsError(`type ${name}: defined more than once.`);
|
|
2863
|
+
}
|
|
2864
|
+
rootDefs.set(name, o);
|
|
2865
|
+
continue;
|
|
2866
|
+
}
|
|
2867
|
+
if (o.interfaces?.length) {
|
|
2868
|
+
throw new UnsupportedTypeDefsError(
|
|
2869
|
+
`type ${name}: interfaces are not supported by @cyphra/graphql yet.`
|
|
2870
|
+
);
|
|
2871
|
+
}
|
|
2872
|
+
for (const d of o.directives ?? []) {
|
|
2873
|
+
if (!ACCEPTED_TYPE_DIRECTIVES.has(d.name.value)) {
|
|
2874
|
+
throw new UnsupportedTypeDefsError(
|
|
2875
|
+
`type ${name}: @${d.name.value} is not supported by @cyphra/graphql yet.`
|
|
2876
|
+
);
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
if (directive2(o.directives, "jwt")) {
|
|
2880
|
+
if (jwtClaims)
|
|
2881
|
+
throw new UnsupportedTypeDefsError(`type ${name}: only one @jwt type is allowed.`);
|
|
2882
|
+
jwtClaims = readJwtClaims(o);
|
|
2883
|
+
continue;
|
|
2884
|
+
}
|
|
2885
|
+
if (directive2(o.directives, "relationshipProperties")) {
|
|
2886
|
+
properties.set(name, {
|
|
2887
|
+
name,
|
|
2888
|
+
attributes: (o.fields ?? []).map((f) => {
|
|
2889
|
+
const a = readAttribute(name, f, enumNames);
|
|
2890
|
+
if (a.auth) {
|
|
2891
|
+
throw new UnsupportedTypeDefsError(
|
|
2892
|
+
`${name}.${f.name.value}: @authentication / @authorization on relationship properties are not supported.`
|
|
2893
|
+
);
|
|
2894
|
+
}
|
|
2895
|
+
return a;
|
|
2896
|
+
})
|
|
2897
|
+
});
|
|
2898
|
+
continue;
|
|
2899
|
+
}
|
|
2900
|
+
if (!directive2(o.directives, "node")) {
|
|
2901
|
+
throw new UnsupportedTypeDefsError(
|
|
2902
|
+
`type ${name}: object types without @node are not supported by @cyphra/graphql yet.`
|
|
2903
|
+
);
|
|
2904
|
+
}
|
|
2905
|
+
nodeDefs.push(o);
|
|
2906
|
+
}
|
|
2907
|
+
const nodeNames = new Set(nodeDefs.map((o) => o.name.value));
|
|
2908
|
+
const nodes = nodeDefs.map((o) => {
|
|
2909
|
+
const name = o.name.value;
|
|
2910
|
+
const attributes = [];
|
|
2911
|
+
const relationships = [];
|
|
2912
|
+
const cypherNodes = [];
|
|
2913
|
+
for (const f of o.fields ?? []) {
|
|
2914
|
+
const rel = directive2(f.directives, "relationship");
|
|
2915
|
+
const cypher = directive2(f.directives, "cypher");
|
|
2916
|
+
if (cypher && !rel && nodeNames.has(typeRef(f.type).name)) {
|
|
2917
|
+
cypherNodes.push(readCypherNodeField(name, f, enumNames));
|
|
2918
|
+
continue;
|
|
2919
|
+
}
|
|
2920
|
+
if (!rel) {
|
|
2921
|
+
attributes.push(readAttribute(name, f, enumNames));
|
|
2922
|
+
continue;
|
|
2923
|
+
}
|
|
2924
|
+
for (const d of f.directives ?? []) {
|
|
2925
|
+
if (d.name.value === "authentication" || d.name.value === "authorization") {
|
|
2926
|
+
throw new UnsupportedTypeDefsError(
|
|
2927
|
+
`${name}.${f.name.value}: @${d.name.value} on a relationship field is not supported (put the rules on the related type).`
|
|
2928
|
+
);
|
|
2929
|
+
}
|
|
2930
|
+
}
|
|
2931
|
+
const t = typeRef(f.type);
|
|
2932
|
+
if (!nodeNames.has(t.name)) {
|
|
2933
|
+
throw new UnsupportedTypeDefsError(
|
|
2934
|
+
`${name}.${f.name.value}: relationships to ${t.name} are not supported by @cyphra/graphql yet (target must be a @node type).`
|
|
2935
|
+
);
|
|
2936
|
+
}
|
|
2937
|
+
for (const a of rel.arguments ?? []) {
|
|
2938
|
+
if (!["type", "direction", "properties"].includes(a.name.value)) {
|
|
2939
|
+
throw new UnsupportedTypeDefsError(
|
|
2940
|
+
`${name}.${f.name.value}: @relationship(${a.name.value}) is not supported by @cyphra/graphql yet.`
|
|
2941
|
+
);
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
const props = stringArg2(rel, "properties");
|
|
2945
|
+
if (props && !properties.has(props)) {
|
|
2946
|
+
throw new UnsupportedTypeDefsError(
|
|
2947
|
+
`${name}.${f.name.value}: properties type ${props} must be a @relationshipProperties type.`
|
|
2948
|
+
);
|
|
2949
|
+
}
|
|
2950
|
+
relationships.push({
|
|
2951
|
+
name: f.name.value,
|
|
2952
|
+
source: name,
|
|
2953
|
+
target: t.name,
|
|
2954
|
+
type: stringArg2(rel, "type") ?? "",
|
|
2955
|
+
direction: stringArg2(rel, "direction") === "IN" ? "IN" : "OUT",
|
|
2956
|
+
properties: props,
|
|
2957
|
+
list: t.list,
|
|
2958
|
+
required: t.required,
|
|
2959
|
+
elementRequired: t.elementRequired,
|
|
2960
|
+
description: f.description?.value,
|
|
2961
|
+
deprecated: deprecationReason(f.directives)
|
|
2962
|
+
});
|
|
2963
|
+
}
|
|
2964
|
+
const nodeDir = directive2(o.directives, "node");
|
|
2965
|
+
const labels2 = listArg(nodeDir, "labels") ?? [name];
|
|
2966
|
+
const pluralDir = directive2(o.directives, "plural");
|
|
2967
|
+
const plural = entityPlural(name, stringArg2(pluralDir, "value"));
|
|
2968
|
+
return {
|
|
2969
|
+
name,
|
|
2970
|
+
description: o.description?.value,
|
|
2971
|
+
labels: labels2,
|
|
2972
|
+
plural,
|
|
2973
|
+
pascalPlural: upperFirst(plural),
|
|
2974
|
+
attributes,
|
|
2975
|
+
relationships,
|
|
2976
|
+
cypherNodes,
|
|
2977
|
+
fulltext: readFulltext(name, directive2(o.directives, "fulltext"), attributes),
|
|
2978
|
+
auth: readAuthAnnotations(`type ${name}`, o.directives) ?? {}
|
|
2979
|
+
};
|
|
2980
|
+
});
|
|
2981
|
+
const byName0 = new Map(nodes.map((n) => [n.name, n]));
|
|
2982
|
+
const root = (type) => readRootType(rootDefs.get(type), enumNames, nodeNames);
|
|
2983
|
+
const query = root("Query");
|
|
2984
|
+
const mutation = root("Mutation");
|
|
2985
|
+
const generated = /* @__PURE__ */ new Set();
|
|
2986
|
+
for (const n of byName0.values()) {
|
|
2987
|
+
generated.add(n.plural);
|
|
2988
|
+
generated.add(`${n.plural}Connection`);
|
|
2989
|
+
for (const ft of n.fulltext) {
|
|
2990
|
+
if (generated.has(ft.queryName)) {
|
|
2991
|
+
throw new UnsupportedTypeDefsError(
|
|
2992
|
+
`type ${n.name} @fulltext: queryName ${ft.queryName} is already a Query field.`
|
|
2993
|
+
);
|
|
2994
|
+
}
|
|
2995
|
+
generated.add(ft.queryName);
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
for (const f of query.fields) {
|
|
2999
|
+
if (generated.has(f.name)) {
|
|
3000
|
+
throw new UnsupportedTypeDefsError(
|
|
3001
|
+
`Query.${f.name}: conflicts with a generated Query field.`
|
|
3002
|
+
);
|
|
3003
|
+
}
|
|
3004
|
+
}
|
|
3005
|
+
const generatedMutations = new Set(
|
|
3006
|
+
[...byName0.values()].flatMap(
|
|
3007
|
+
(n) => ["create", "update", "delete"].map((k) => `${k}${n.pascalPlural}`)
|
|
3008
|
+
)
|
|
3009
|
+
);
|
|
3010
|
+
for (const f of mutation.fields) {
|
|
3011
|
+
if (generatedMutations.has(f.name)) {
|
|
3012
|
+
throw new UnsupportedTypeDefsError(
|
|
3013
|
+
`Mutation.${f.name}: conflicts with a generated Mutation field.`
|
|
3014
|
+
);
|
|
3015
|
+
}
|
|
3016
|
+
}
|
|
3017
|
+
const byName = new Map(nodes.map((n) => [n.name, n]));
|
|
3018
|
+
return {
|
|
3019
|
+
nodes,
|
|
3020
|
+
authentication: schemaAuthentication,
|
|
3021
|
+
jwtClaims: jwtClaims ?? /* @__PURE__ */ new Map(),
|
|
3022
|
+
properties,
|
|
3023
|
+
enums,
|
|
3024
|
+
query,
|
|
3025
|
+
mutation,
|
|
3026
|
+
node(name) {
|
|
3027
|
+
const n = byName.get(name);
|
|
3028
|
+
if (!n) throw new Error(`Unknown node type ${name}`);
|
|
3029
|
+
return n;
|
|
3030
|
+
}
|
|
3031
|
+
};
|
|
3032
|
+
}
|
|
1893
3033
|
|
|
1894
3034
|
// src/v7/cypher/select.ts
|
|
3035
|
+
var FORBIDDEN_KEY = "cyphra:forbidden";
|
|
3036
|
+
var FORBIDDEN_MARKER = `{ ${"`"}${FORBIDDEN_KEY}${"`"}: true }`;
|
|
3037
|
+
function containsForbidden(raw) {
|
|
3038
|
+
if (Array.isArray(raw)) return raw.some(containsForbidden);
|
|
3039
|
+
if (typeof raw !== "object" || raw === null) return false;
|
|
3040
|
+
const proto = Object.getPrototypeOf(raw);
|
|
3041
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
3042
|
+
if (Object.prototype.hasOwnProperty.call(raw, FORBIDDEN_KEY)) return true;
|
|
3043
|
+
return Object.values(raw).some(containsForbidden);
|
|
3044
|
+
}
|
|
3045
|
+
function and3(parts) {
|
|
3046
|
+
const ps = parts.filter((p) => p !== void 0);
|
|
3047
|
+
if (ps.length === 0) return void 0;
|
|
3048
|
+
if (ps.length === 1) return ps[0];
|
|
3049
|
+
return ps.map((p) => `(${p})`).join(" AND ");
|
|
3050
|
+
}
|
|
3051
|
+
function rowGate(failure, expr, marker) {
|
|
3052
|
+
return failure === void 0 ? expr : `CASE WHEN ${failure} THEN ${marker} ELSE ${expr} END`;
|
|
3053
|
+
}
|
|
3054
|
+
function gate(match, predicate, failure, expr, marker) {
|
|
3055
|
+
if (failure === void 0) return expr;
|
|
3056
|
+
return `CASE WHEN EXISTS { MATCH ${match} WHERE ${and3([predicate, failure])} } THEN ${marker} ELSE ${expr} END`;
|
|
3057
|
+
}
|
|
3058
|
+
function sortScope() {
|
|
3059
|
+
return { clauses: [], vars: /* @__PURE__ */ new Map() };
|
|
3060
|
+
}
|
|
1895
3061
|
var CURSOR_PREFIX = "arrayconnection:";
|
|
1896
3062
|
function offsetToCursor(offset) {
|
|
1897
3063
|
return Buffer.from(`${CURSOR_PREFIX}${offset}`, "utf8").toString("base64");
|
|
@@ -1950,12 +3116,15 @@ function attributeDecoder(a) {
|
|
|
1950
3116
|
}
|
|
1951
3117
|
return (v) => v ?? null;
|
|
1952
3118
|
}
|
|
3119
|
+
function toFloat(v) {
|
|
3120
|
+
return isInt(v) ? v.toNumber() : Number(v);
|
|
3121
|
+
}
|
|
1953
3122
|
function toNumber(v) {
|
|
1954
3123
|
return isInt(v) ? v.toNumber() : Number(v);
|
|
1955
3124
|
}
|
|
1956
3125
|
function intParam(ctx, value) {
|
|
1957
3126
|
if (typeof value !== "number") return void 0;
|
|
1958
|
-
return ctx.param(
|
|
3127
|
+
return ctx.param(neo4j3.int(Math.max(0, Math.trunc(value))));
|
|
1959
3128
|
}
|
|
1960
3129
|
function paging(ctx, offset, limit) {
|
|
1961
3130
|
const parts = [];
|
|
@@ -1965,9 +3134,10 @@ function paging(ctx, offset, limit) {
|
|
|
1965
3134
|
if (l) parts.push(`LIMIT ${l}`);
|
|
1966
3135
|
return parts.join(" ");
|
|
1967
3136
|
}
|
|
1968
|
-
function withClause(vars, order, page) {
|
|
3137
|
+
function withClause(vars, order, page, sort) {
|
|
1969
3138
|
if (!order && !page) return "";
|
|
1970
|
-
|
|
3139
|
+
const all = [vars, ...sort ? sort.vars.values() : []].join(", ");
|
|
3140
|
+
return ["WITH", all, order, page].filter(Boolean).join(" ");
|
|
1971
3141
|
}
|
|
1972
3142
|
var AGGREGATE_FUNCTIONS = {
|
|
1973
3143
|
min: "min",
|
|
@@ -1989,62 +3159,153 @@ function mapDecoder(decoders) {
|
|
|
1989
3159
|
};
|
|
1990
3160
|
}
|
|
1991
3161
|
var SelectionCompiler = class {
|
|
1992
|
-
constructor(model, info) {
|
|
3162
|
+
constructor(model, info, auth) {
|
|
1993
3163
|
this.model = model;
|
|
1994
3164
|
this.info = info;
|
|
1995
|
-
this.
|
|
3165
|
+
this.auth = auth;
|
|
3166
|
+
this.where = new WhereCompiler(model, this.ctx);
|
|
3167
|
+
this.rules = new AuthRules(model, this.ctx, auth);
|
|
3168
|
+
this.ctx.jwt = auth.jwt ?? {};
|
|
1996
3169
|
}
|
|
1997
3170
|
model;
|
|
1998
3171
|
info;
|
|
3172
|
+
auth;
|
|
1999
3173
|
ctx = new CypherContext();
|
|
2000
3174
|
where;
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
3175
|
+
rules;
|
|
3176
|
+
/**
|
|
3177
|
+
* `COLLECT { <body> RETURN ret }` / `COUNT { <body> }` / `EXISTS { <body> }` as an expression or,
|
|
3178
|
+
* when the subquery contains a `@cypher` statement, hoisted into `scope` as
|
|
3179
|
+
* `CALL (*) { <body> RETURN collect(ret) | count(*) AS v }` (the variable is the value).
|
|
3180
|
+
*/
|
|
3181
|
+
subquery(scope, kind, body, ret) {
|
|
3182
|
+
const text = body.filter(Boolean).join(" ");
|
|
3183
|
+
if (!hasStatement(text, ret)) {
|
|
3184
|
+
if (kind === "collect") return `COLLECT { ${text} RETURN ${ret} }`;
|
|
3185
|
+
if (kind === "count") return `COUNT { ${text}${ret ? ` RETURN ${ret}` : ""} }`;
|
|
3186
|
+
return `EXISTS { ${text} }`;
|
|
2007
3187
|
}
|
|
3188
|
+
const v = this.ctx.variable("sub");
|
|
3189
|
+
const agg = kind === "collect" ? `collect(${ret})` : kind === "count" ? "count(*)" : "count(*) > 0";
|
|
3190
|
+
scope.push(["CALL (*) {", text, `RETURN ${agg} AS ${v}`, "}"].join("\n"));
|
|
3191
|
+
return v;
|
|
3192
|
+
}
|
|
3193
|
+
/** {@link gate} with the existence check hoisted when it contains a statement. */
|
|
3194
|
+
gate(scope, match, predicate, failure, expr, marker) {
|
|
3195
|
+
if (failure === void 0) return expr;
|
|
3196
|
+
if (!hasStatement(predicate, failure)) return gate(match, predicate, failure, expr, marker);
|
|
3197
|
+
const denied = this.subquery(scope, "exists", [
|
|
3198
|
+
`MATCH ${match} WHERE ${and3([predicate, failure])}`
|
|
3199
|
+
]);
|
|
3200
|
+
return `CASE WHEN ${denied} THEN ${marker} ELSE ${expr} END`;
|
|
3201
|
+
}
|
|
3202
|
+
/** {@link rowGate} with the check hoisted when it contains a statement. */
|
|
3203
|
+
rowGate(scope, failure, expr, marker) {
|
|
3204
|
+
if (failure === void 0 || !hasStatement(failure)) return rowGate(failure, expr, marker);
|
|
3205
|
+
const denied = this.subquery(scope, "exists", [`WITH * WHERE ${failure}`]);
|
|
3206
|
+
return `CASE WHEN ${denied} THEN ${marker} ELSE ${expr} END`;
|
|
3207
|
+
}
|
|
3208
|
+
/** `@authentication` for `operation` on the type (and on each of `fields`). */
|
|
3209
|
+
authenticate(node, operation, fields = []) {
|
|
3210
|
+
checkAuthentication(this.model, this.auth, node, [operation]);
|
|
3211
|
+
for (const f of fields) checkAuthentication(this.model, this.auth, node, [operation], f);
|
|
3212
|
+
}
|
|
3213
|
+
/** Attributes of `node` selected in `fieldNodes` (they bring their field-level rules). */
|
|
3214
|
+
selectedAttributes(node, fieldNodes) {
|
|
3215
|
+
const names = new Set(
|
|
3216
|
+
[...collectFields(this.info, subSelections(fieldNodes)).values()].map(
|
|
3217
|
+
(n) => n[0].name.value
|
|
3218
|
+
)
|
|
3219
|
+
);
|
|
3220
|
+
return node.attributes.filter((a) => names.has(a.name));
|
|
3221
|
+
}
|
|
3222
|
+
/**
|
|
3223
|
+
* READ rules of a node selection: the `filter` predicate and the `validate` failure (BEFORE) for
|
|
3224
|
+
* the type and the selected attributes.
|
|
3225
|
+
*/
|
|
3226
|
+
readRules(variable, node, fieldNodes) {
|
|
3227
|
+
const attrs = this.selectedAttributes(node, fieldNodes);
|
|
3228
|
+
return {
|
|
3229
|
+
filter: this.rules.filter(variable, node, "READ", attrs),
|
|
3230
|
+
failure: this.rules.fails(variable, node, "READ", "BEFORE", attrs)
|
|
3231
|
+
};
|
|
3232
|
+
}
|
|
3233
|
+
/** `[marker]` for a list selection that is not allowed. */
|
|
3234
|
+
forbiddenList() {
|
|
3235
|
+
return `[${FORBIDDEN_MARKER}]`;
|
|
3236
|
+
}
|
|
3237
|
+
forbiddenMap() {
|
|
3238
|
+
return FORBIDDEN_MARKER;
|
|
2008
3239
|
}
|
|
2009
|
-
sortItems(variable, attributes, sort, owner) {
|
|
3240
|
+
sortItems(variable, attributes, sort, owner, pre) {
|
|
2010
3241
|
const items = [];
|
|
2011
3242
|
if (sort === null || typeof sort !== "object") return items;
|
|
2012
3243
|
for (const [field, dir] of Object.entries(sort)) {
|
|
2013
3244
|
if (dir !== "ASC" && dir !== "DESC") continue;
|
|
2014
3245
|
const a = attributes.find((x) => x.name === field);
|
|
2015
3246
|
if (!a) throw new Error(`Unknown sort field ${owner}.${field}`);
|
|
2016
|
-
if (a.cypher)
|
|
2017
|
-
|
|
3247
|
+
if (a.cypher) {
|
|
3248
|
+
items.push(`${this.sortValue(variable, a, pre)} ${dir}`);
|
|
3249
|
+
continue;
|
|
3250
|
+
}
|
|
2018
3251
|
items.push(`${variable}.${q(a.property)} ${dir}`);
|
|
2019
3252
|
}
|
|
2020
3253
|
return items;
|
|
2021
3254
|
}
|
|
2022
|
-
|
|
3255
|
+
/** The variable holding a `@cypher` sort value, computed once per field (v7). */
|
|
3256
|
+
sortValue(variable, a, pre) {
|
|
3257
|
+
const key = `${variable}.${a.name}`;
|
|
3258
|
+
let v = pre.vars.get(key);
|
|
3259
|
+
if (!v) {
|
|
3260
|
+
const c = scalarClause(this.ctx, variable, a.cypher, a.args, {}, a.type.list);
|
|
3261
|
+
pre.clauses.push(c.clause);
|
|
3262
|
+
pre.vars.set(key, c.variable);
|
|
3263
|
+
v = c.variable;
|
|
3264
|
+
}
|
|
3265
|
+
return v;
|
|
3266
|
+
}
|
|
3267
|
+
nodeOrder(variable, node, sort, pre) {
|
|
2023
3268
|
const items = (Array.isArray(sort) ? sort : []).flatMap(
|
|
2024
|
-
(s) => this.sortItems(variable, node.attributes, s, node.name)
|
|
3269
|
+
(s) => this.sortItems(variable, node.attributes, s, node.name, pre)
|
|
2025
3270
|
);
|
|
2026
3271
|
return items.length ? `ORDER BY ${items.join(", ")}` : "";
|
|
2027
3272
|
}
|
|
2028
|
-
connectionOrder(relVar, nodeVar, rel, sort) {
|
|
3273
|
+
connectionOrder(relVar, nodeVar, rel, sort, pre) {
|
|
2029
3274
|
const target = this.model.node(rel.target);
|
|
2030
3275
|
const props = this.props(rel);
|
|
2031
3276
|
const items = [];
|
|
2032
3277
|
for (const s of Array.isArray(sort) ? sort : []) {
|
|
2033
3278
|
if (s === null || typeof s !== "object") continue;
|
|
2034
3279
|
for (const [k, v] of Object.entries(s)) {
|
|
2035
|
-
if (k === "node")
|
|
3280
|
+
if (k === "node")
|
|
3281
|
+
items.push(...this.sortItems(nodeVar, target.attributes, v, target.name, pre));
|
|
2036
3282
|
else if (k === "edge" && props)
|
|
2037
|
-
items.push(...this.sortItems(relVar, props.attributes, v, props.name));
|
|
3283
|
+
items.push(...this.sortItems(relVar, props.attributes, v, props.name, pre));
|
|
2038
3284
|
}
|
|
2039
3285
|
}
|
|
2040
3286
|
return items.length ? `ORDER BY ${items.join(", ")}` : "";
|
|
2041
3287
|
}
|
|
3288
|
+
/**
|
|
3289
|
+
* The value of a scalar `@cypher` field of `variable` for the response key: the sort value when
|
|
3290
|
+
* the field was sorted on (same field, no arguments), else a new `CALL` clause in `scope`.
|
|
3291
|
+
*/
|
|
3292
|
+
cypherValue(scope, variable, attr, fieldNode, gqlType, pre) {
|
|
3293
|
+
const reused = attr.args.length ? void 0 : pre?.vars.get(`${variable}.${attr.name}`);
|
|
3294
|
+
if (reused) return reused;
|
|
3295
|
+
const values = attr.args.length ? fieldArgs(gqlType.getFields()[attr.name], fieldNode, this.info) : {};
|
|
3296
|
+
const c = scalarClause(this.ctx, variable, attr.cypher, attr.args, values, attr.type.list);
|
|
3297
|
+
scope.push(c.clause);
|
|
3298
|
+
return c.variable;
|
|
3299
|
+
}
|
|
2042
3300
|
props(rel) {
|
|
2043
3301
|
return rel.properties ? this.model.properties.get(rel.properties) : void 0;
|
|
2044
3302
|
}
|
|
2045
3303
|
/** `{ key: expr, … }` for a selection on a node variable, and its decoder. */
|
|
2046
|
-
projectNode(variable, node, fieldNodes) {
|
|
2047
|
-
this.
|
|
3304
|
+
projectNode(variable, node, fieldNodes, scope, pre) {
|
|
3305
|
+
const fields = [...collectFields(this.info, subSelections(fieldNodes)).values()].map(
|
|
3306
|
+
(n) => n[0].name.value
|
|
3307
|
+
);
|
|
3308
|
+
this.authenticate(node, "READ", fields);
|
|
2048
3309
|
const type = objectType(this.info, node.name);
|
|
2049
3310
|
const gqlFields = type.getFields();
|
|
2050
3311
|
const entries = [];
|
|
@@ -2054,25 +3315,31 @@ var SelectionCompiler = class {
|
|
|
2054
3315
|
if (name === "__typename") continue;
|
|
2055
3316
|
const attr = node.attributes.find((a) => a.name === name);
|
|
2056
3317
|
if (attr) {
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
entries.push(`${q(key)}: ${variable}.${q(attr.property)}`);
|
|
3318
|
+
const value = attr.cypher ? this.cypherValue(scope, variable, attr, nodes[0], type, pre) : `${variable}.${q(attr.property)}`;
|
|
3319
|
+
entries.push(`${q(key)}: ${value}`);
|
|
2060
3320
|
decoders.push([key, attributeDecoder(attr)]);
|
|
2061
3321
|
continue;
|
|
2062
3322
|
}
|
|
2063
3323
|
const gqlField = gqlFields[name];
|
|
2064
3324
|
if (!gqlField) throw new Error(`Unknown field ${node.name}.${name}`);
|
|
2065
3325
|
const args = fieldArgs(gqlField, nodes[0], this.info);
|
|
3326
|
+
const cypherNode = node.cypherNodes.find((c) => c.name === name);
|
|
3327
|
+
if (cypherNode) {
|
|
3328
|
+
const p = this.cypherNodeField(scope, variable, cypherNode, args, nodes);
|
|
3329
|
+
entries.push(`${q(key)}: ${p.expr}`);
|
|
3330
|
+
decoders.push([key, p.decode]);
|
|
3331
|
+
continue;
|
|
3332
|
+
}
|
|
2066
3333
|
const rel = node.relationships.find((r) => r.name === name);
|
|
2067
3334
|
if (rel) {
|
|
2068
|
-
const p = this.relationshipList(variable, rel, args, nodes);
|
|
3335
|
+
const p = this.relationshipList(scope, variable, rel, args, nodes);
|
|
2069
3336
|
entries.push(`${q(key)}: ${p.expr}`);
|
|
2070
3337
|
decoders.push([key, p.decode]);
|
|
2071
3338
|
continue;
|
|
2072
3339
|
}
|
|
2073
3340
|
const connRel = name.endsWith("Connection") ? node.relationships.find((r) => `${r.name}Connection` === name) : void 0;
|
|
2074
3341
|
if (connRel) {
|
|
2075
|
-
const p = this.relationshipConnection(variable, connRel, args, nodes);
|
|
3342
|
+
const p = this.relationshipConnection(scope, variable, connRel, args, nodes);
|
|
2076
3343
|
entries.push(`${q(key)}: ${p.expr}`);
|
|
2077
3344
|
decoders.push([key, p.decode]);
|
|
2078
3345
|
continue;
|
|
@@ -2089,15 +3356,17 @@ var SelectionCompiler = class {
|
|
|
2089
3356
|
}
|
|
2090
3357
|
};
|
|
2091
3358
|
}
|
|
2092
|
-
projectProperties(relVar, props, fieldNodes) {
|
|
3359
|
+
projectProperties(relVar, props, fieldNodes, scope, pre) {
|
|
2093
3360
|
const entries = [];
|
|
2094
3361
|
const decoders = [];
|
|
3362
|
+
const type = objectType(this.info, props.name);
|
|
2095
3363
|
for (const [key, nodes] of collectFields(this.info, subSelections(fieldNodes))) {
|
|
2096
3364
|
const name = nodes[0].name.value;
|
|
2097
3365
|
if (name === "__typename") continue;
|
|
2098
3366
|
const attr = props.attributes.find((a) => a.name === name);
|
|
2099
3367
|
if (!attr) throw new Error(`Unknown field ${props.name}.${name}`);
|
|
2100
|
-
|
|
3368
|
+
const value = attr.cypher ? this.cypherValue(scope, relVar, attr, nodes[0], type, pre) : `${relVar}.${q(attr.property)}`;
|
|
3369
|
+
entries.push(`${q(key)}: ${value}`);
|
|
2101
3370
|
decoders.push([key, attributeDecoder(attr)]);
|
|
2102
3371
|
}
|
|
2103
3372
|
return {
|
|
@@ -2110,23 +3379,66 @@ var SelectionCompiler = class {
|
|
|
2110
3379
|
}
|
|
2111
3380
|
};
|
|
2112
3381
|
}
|
|
2113
|
-
relationshipList(variable, rel, args, fieldNodes) {
|
|
3382
|
+
relationshipList(scope, variable, rel, args, fieldNodes) {
|
|
2114
3383
|
const target = this.model.node(rel.target);
|
|
2115
3384
|
const m = this.ctx.variable("this");
|
|
2116
3385
|
const pattern = relationshipPattern(this.model, variable, rel, m);
|
|
2117
|
-
const
|
|
2118
|
-
const
|
|
3386
|
+
const auth = this.readRules(m, target, fieldNodes);
|
|
3387
|
+
const pred = and3([this.where.node(m, target, args.where), auth.filter]);
|
|
3388
|
+
const pre = sortScope();
|
|
3389
|
+
const order = this.nodeOrder(m, target, args.sort, pre);
|
|
2119
3390
|
const page = paging(this.ctx, args.offset, args.limit);
|
|
2120
|
-
const inner =
|
|
3391
|
+
const inner = [];
|
|
3392
|
+
const proj = this.projectNode(m, target, fieldNodes, inner, pre);
|
|
3393
|
+
const row = this.rowGate(inner, auth.failure, proj.expr, this.forbiddenMap());
|
|
2121
3394
|
const body = [
|
|
2122
3395
|
`MATCH ${pattern}`,
|
|
2123
3396
|
pred ? `WHERE ${pred}` : "",
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
3397
|
+
...pre.clauses,
|
|
3398
|
+
withClause(m, order, page, pre),
|
|
3399
|
+
...inner
|
|
3400
|
+
];
|
|
3401
|
+
const list2 = this.subquery(scope, "collect", body, row);
|
|
3402
|
+
return {
|
|
3403
|
+
expr: this.gate(scope, pattern, pred, auth.failure, list2, this.forbiddenList()),
|
|
3404
|
+
decode: (raw) => Array.isArray(raw) ? raw.map(proj.decode) : []
|
|
3405
|
+
};
|
|
3406
|
+
}
|
|
3407
|
+
/**
|
|
3408
|
+
* A `@cypher` field returning nodes: `CALL (v) { <statement> WITH col AS n WHERE n IS NOT NULL
|
|
3409
|
+
* AND <READ filter> … RETURN collect(<projection>) AS s }` (`head(…)` for one node). The READ rules
|
|
3410
|
+
* of the returned type apply (a node failing `validate` makes the field `Forbidden`), like v7.
|
|
3411
|
+
*/
|
|
3412
|
+
cypherNodeField(scope, variable, field, args, fieldNodes) {
|
|
3413
|
+
const target = this.model.node(field.target);
|
|
3414
|
+
const call = statementCall(this.ctx, field.cypher, field.args, args, variable);
|
|
3415
|
+
const p = this.cypherNodes(call, field.cypher, target, fieldNodes);
|
|
3416
|
+
const s = this.ctx.variable("cypher");
|
|
3417
|
+
const value = field.type.list ? `collect(${p.row})` : `head(collect(${p.row}))`;
|
|
3418
|
+
scope.push([`CALL (${variable}) {`, ...p.clauses, `RETURN ${value} AS ${s}`, "}"].join("\n"));
|
|
3419
|
+
return {
|
|
3420
|
+
expr: s,
|
|
3421
|
+
decode: field.type.list ? (raw) => Array.isArray(raw) ? raw.map(p.decode) : [] : (raw) => raw === null || raw === void 0 ? null : p.decode(raw)
|
|
3422
|
+
};
|
|
3423
|
+
}
|
|
3424
|
+
/**
|
|
3425
|
+
* Clauses that run a statement returning nodes and keep the readable ones (`WHERE n IS NOT NULL
|
|
3426
|
+
* AND <READ filter>`), and the projection of one row (or the forbidden marker).
|
|
3427
|
+
*/
|
|
3428
|
+
cypherNodes(call, cypher, target, fieldNodes) {
|
|
3429
|
+
const n = this.ctx.variable("this");
|
|
3430
|
+
const auth = this.readRules(n, target, fieldNodes);
|
|
3431
|
+
const inner = [];
|
|
3432
|
+
const proj = this.projectNode(n, target, fieldNodes, inner);
|
|
3433
|
+
const row = this.rowGate(inner, auth.failure, proj.expr, this.forbiddenMap());
|
|
2127
3434
|
return {
|
|
2128
|
-
|
|
2129
|
-
|
|
3435
|
+
clauses: [
|
|
3436
|
+
call,
|
|
3437
|
+
`WITH ${column(cypher)} AS ${n} WHERE ${and3([`${n} IS NOT NULL`, auth.filter])}`,
|
|
3438
|
+
...inner
|
|
3439
|
+
],
|
|
3440
|
+
row,
|
|
3441
|
+
decode: proj.decode
|
|
2130
3442
|
};
|
|
2131
3443
|
}
|
|
2132
3444
|
/**
|
|
@@ -2138,6 +3450,10 @@ var SelectionCompiler = class {
|
|
|
2138
3450
|
const afterOffset = cursorToOffset(opts.args.after);
|
|
2139
3451
|
const offset = afterOffset === void 0 ? 0 : afterOffset + 1;
|
|
2140
3452
|
const conn = collectFields(this.info, subSelections(opts.fieldNodes));
|
|
3453
|
+
this.authenticate(opts.node, "READ");
|
|
3454
|
+
const edgeNodeFields = [...collectFields(this.info, subSelections(conn.get("edges") ?? []))].filter(([, n]) => n[0].name.value === "node").flatMap(([, n]) => n);
|
|
3455
|
+
const readAuth = this.readRules(opts.nodeVar, opts.node, edgeNodeFields);
|
|
3456
|
+
const readPredicate = and3([opts.predicate, readAuth.filter]);
|
|
2141
3457
|
const edgeEntries = [];
|
|
2142
3458
|
const edgeDecoders = [];
|
|
2143
3459
|
const edgeFieldNodes = [];
|
|
@@ -2145,13 +3461,32 @@ var SelectionCompiler = class {
|
|
|
2145
3461
|
const aggregateEntries = [];
|
|
2146
3462
|
let needsTotal = false;
|
|
2147
3463
|
let needsEdges = false;
|
|
2148
|
-
const where =
|
|
3464
|
+
const where = readPredicate ? ` WHERE ${readPredicate}` : "";
|
|
2149
3465
|
for (const [key, nodes] of conn) {
|
|
2150
3466
|
const name = nodes[0].name.value;
|
|
2151
3467
|
if (name === "aggregate") {
|
|
3468
|
+
const aggNodeFields = [...collectFields(this.info, subSelections(nodes))].filter(([, n]) => n[0].name.value === "node").flatMap(([, n]) => n);
|
|
3469
|
+
const aggAttrs = this.selectedAttributes(opts.node, aggNodeFields);
|
|
3470
|
+
this.authenticate(
|
|
3471
|
+
opts.node,
|
|
3472
|
+
"AGGREGATE",
|
|
3473
|
+
aggAttrs.map((a) => a.name)
|
|
3474
|
+
);
|
|
3475
|
+
const aggPredicate = and3([
|
|
3476
|
+
opts.predicate,
|
|
3477
|
+
this.rules.filter(opts.nodeVar, opts.node, "AGGREGATE", aggAttrs)
|
|
3478
|
+
]);
|
|
3479
|
+
const aggFailure = this.rules.fails(
|
|
3480
|
+
opts.nodeVar,
|
|
3481
|
+
opts.node,
|
|
3482
|
+
"AGGREGATE",
|
|
3483
|
+
"BEFORE",
|
|
3484
|
+
aggAttrs
|
|
3485
|
+
);
|
|
2152
3486
|
const p = this.aggregate(
|
|
2153
3487
|
{
|
|
2154
|
-
|
|
3488
|
+
scope: opts.scope,
|
|
3489
|
+
base: `MATCH ${opts.match}${aggPredicate ? ` WHERE ${aggPredicate}` : ""}`,
|
|
2155
3490
|
nodeVar: opts.nodeVar,
|
|
2156
3491
|
relVar: opts.relVar,
|
|
2157
3492
|
node: opts.node,
|
|
@@ -2160,39 +3495,59 @@ var SelectionCompiler = class {
|
|
|
2160
3495
|
},
|
|
2161
3496
|
nodes
|
|
2162
3497
|
);
|
|
2163
|
-
aggregateEntries.push(
|
|
3498
|
+
aggregateEntries.push(
|
|
3499
|
+
`${q(key)}: ${this.gate(opts.scope, opts.match, aggPredicate, aggFailure, p.expr, this.forbiddenMap())}`
|
|
3500
|
+
);
|
|
2164
3501
|
aggregates.push([key, p.decode]);
|
|
2165
3502
|
}
|
|
2166
3503
|
if (name === "edges") edgeFieldNodes.push(...nodes);
|
|
2167
3504
|
if (name === "edges" || name === "pageInfo") needsEdges = true;
|
|
2168
3505
|
if (name === "totalCount" || name === "pageInfo") needsTotal = true;
|
|
2169
3506
|
}
|
|
3507
|
+
const edgeScope = [];
|
|
2170
3508
|
for (const [key, nodes] of collectFields(this.info, subSelections(edgeFieldNodes))) {
|
|
2171
3509
|
const name = nodes[0].name.value;
|
|
2172
3510
|
if (name === "cursor") {
|
|
2173
3511
|
edgeDecoders.push([key, (_raw, i) => offsetToCursor(offset + i)]);
|
|
2174
3512
|
} else if (name === "node") {
|
|
2175
|
-
const p = opts.projectNode(nodes);
|
|
3513
|
+
const p = opts.projectNode(nodes, edgeScope, opts.pre);
|
|
2176
3514
|
edgeEntries.push(`${q(key)}: ${p.expr}`);
|
|
2177
3515
|
edgeDecoders.push([key, (raw) => p.decode(raw[key])]);
|
|
2178
3516
|
} else if (name === "properties" && opts.projectProperties) {
|
|
2179
|
-
const p = opts.projectProperties(nodes);
|
|
3517
|
+
const p = opts.projectProperties(nodes, edgeScope, opts.pre);
|
|
2180
3518
|
edgeEntries.push(`${q(key)}: ${p.expr}`);
|
|
2181
3519
|
edgeDecoders.push([key, (raw) => p.decode(raw[key])]);
|
|
2182
3520
|
}
|
|
2183
3521
|
}
|
|
2184
3522
|
const withVars = opts.relVar ? `${opts.relVar}, ${opts.nodeVar}` : opts.nodeVar;
|
|
2185
3523
|
const page = paging(this.ctx, offset || void 0, opts.args.first);
|
|
3524
|
+
const edgeRow = this.rowGate(
|
|
3525
|
+
edgeScope,
|
|
3526
|
+
needsEdges ? readAuth.failure : void 0,
|
|
3527
|
+
`{ ${edgeEntries.join(", ")} }`,
|
|
3528
|
+
this.forbiddenMap()
|
|
3529
|
+
);
|
|
2186
3530
|
const edgesBody = [
|
|
2187
3531
|
`MATCH ${opts.match}${where}`,
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
3532
|
+
...opts.pre.clauses,
|
|
3533
|
+
withClause(withVars, opts.order, page, opts.pre),
|
|
3534
|
+
...edgeScope
|
|
3535
|
+
];
|
|
2191
3536
|
const parts = [];
|
|
2192
|
-
if (needsTotal)
|
|
2193
|
-
|
|
3537
|
+
if (needsTotal)
|
|
3538
|
+
parts.push(`total: ${this.subquery(opts.scope, "count", [`MATCH ${opts.match}${where}`])}`);
|
|
3539
|
+
if (needsEdges)
|
|
3540
|
+
parts.push(`edges: ${this.subquery(opts.scope, "collect", edgesBody, edgeRow)}`);
|
|
2194
3541
|
if (aggregateEntries.length) parts.push(`aggregate: { ${aggregateEntries.join(", ")} }`);
|
|
2195
|
-
const
|
|
3542
|
+
const map = `{ ${parts.join(", ")} }`;
|
|
3543
|
+
const expr = needsTotal || needsEdges ? this.gate(
|
|
3544
|
+
opts.scope,
|
|
3545
|
+
opts.match,
|
|
3546
|
+
readPredicate,
|
|
3547
|
+
readAuth.failure,
|
|
3548
|
+
map,
|
|
3549
|
+
this.forbiddenMap()
|
|
3550
|
+
) : map;
|
|
2196
3551
|
return {
|
|
2197
3552
|
expr,
|
|
2198
3553
|
decode: (raw) => {
|
|
@@ -2255,7 +3610,9 @@ var SelectionCompiler = class {
|
|
|
2255
3610
|
const what = cn[0].name.value;
|
|
2256
3611
|
const v = what === "nodes" ? scope.nodeVar : what === "edges" ? scope.relVar : void 0;
|
|
2257
3612
|
if (!v) continue;
|
|
2258
|
-
counts.push(
|
|
3613
|
+
counts.push(
|
|
3614
|
+
`${q(ck)}: ${this.subquery(scope.scope, "count", [scope.base, `WITH DISTINCT ${v}`], v)}`
|
|
3615
|
+
);
|
|
2259
3616
|
keys.push(ck);
|
|
2260
3617
|
}
|
|
2261
3618
|
entries.push(`${q(key)}: { ${counts.join(", ")} }`);
|
|
@@ -2275,7 +3632,6 @@ var SelectionCompiler = class {
|
|
|
2275
3632
|
const attributes = isEdge ? scope.props?.attributes : scope.node.attributes;
|
|
2276
3633
|
if (!variable || !attributes)
|
|
2277
3634
|
throw new Error(`Unknown field ${scope.owner}.aggregate.${name}`);
|
|
2278
|
-
this.assertReadable(scope.node);
|
|
2279
3635
|
const fieldEntries = [];
|
|
2280
3636
|
const fieldDecoders = [];
|
|
2281
3637
|
for (const [fk, fn] of collectFields(this.info, subSelections(nodes))) {
|
|
@@ -2283,7 +3639,7 @@ var SelectionCompiler = class {
|
|
|
2283
3639
|
if (field === "__typename") continue;
|
|
2284
3640
|
const attr = attributes.find((a) => a.name === field);
|
|
2285
3641
|
if (!attr) throw new Error(`Unknown field ${scope.owner}.aggregate.${name}.${field}`);
|
|
2286
|
-
const p = this.aggregateAttribute(scope.base, variable, attr, fn);
|
|
3642
|
+
const p = this.aggregateAttribute(scope.scope, scope.base, variable, attr, fn);
|
|
2287
3643
|
fieldEntries.push(`${q(fk)}: ${p.expr}`);
|
|
2288
3644
|
fieldDecoders.push([fk, p.decode]);
|
|
2289
3645
|
}
|
|
@@ -2293,7 +3649,7 @@ var SelectionCompiler = class {
|
|
|
2293
3649
|
return { expr: `{ ${entries.join(", ")} }`, decode: mapDecoder(decoders) };
|
|
2294
3650
|
}
|
|
2295
3651
|
/** `min` / `max` / `average` / `sum` / `shortest` / `longest` of one attribute, v7 semantics. */
|
|
2296
|
-
aggregateAttribute(base, variable, attr, fieldNodes) {
|
|
3652
|
+
aggregateAttribute(scope, base, variable, attr, fieldNodes) {
|
|
2297
3653
|
const prop = `${variable}.${q(attr.property)}`;
|
|
2298
3654
|
const type = attr.type.name;
|
|
2299
3655
|
const ops = [];
|
|
@@ -2306,7 +3662,12 @@ var SelectionCompiler = class {
|
|
|
2306
3662
|
const l = this.ctx.variable("list");
|
|
2307
3663
|
const values = `${base} WITH DISTINCT ${variable} WHERE ${prop} IS NOT NULL`;
|
|
2308
3664
|
if (type === "String") {
|
|
2309
|
-
const list3 =
|
|
3665
|
+
const list3 = this.subquery(
|
|
3666
|
+
scope,
|
|
3667
|
+
"collect",
|
|
3668
|
+
[values, `WITH ${variable} ORDER BY size(${prop}) DESC`],
|
|
3669
|
+
prop
|
|
3670
|
+
);
|
|
2310
3671
|
const items2 = ops.map(
|
|
2311
3672
|
([k, op]) => `${q(k)}: ${op === "longest" ? `head(${l})` : op === "shortest" ? `last(${l})` : "null"}`
|
|
2312
3673
|
);
|
|
@@ -2315,7 +3676,7 @@ var SelectionCompiler = class {
|
|
|
2315
3676
|
decode: mapDecoder(decoders)
|
|
2316
3677
|
};
|
|
2317
3678
|
}
|
|
2318
|
-
const list2 =
|
|
3679
|
+
const list2 = this.subquery(scope, "collect", [values], prop);
|
|
2319
3680
|
const items = ops.map(([k, op]) => {
|
|
2320
3681
|
const fn = AGGREGATE_FUNCTIONS[op];
|
|
2321
3682
|
return `${q(k)}: ${fn ? listAggregate(fn, l) : "null"}`;
|
|
@@ -2325,20 +3686,22 @@ var SelectionCompiler = class {
|
|
|
2325
3686
|
decode: mapDecoder(decoders)
|
|
2326
3687
|
};
|
|
2327
3688
|
}
|
|
2328
|
-
relationshipConnection(variable, rel, args, fieldNodes) {
|
|
3689
|
+
relationshipConnection(scope, variable, rel, args, fieldNodes) {
|
|
2329
3690
|
const target = this.model.node(rel.target);
|
|
2330
|
-
this.assertReadable(target);
|
|
2331
3691
|
const m = this.ctx.variable("this");
|
|
2332
3692
|
const r = this.ctx.variable("edge");
|
|
2333
3693
|
const props = this.props(rel);
|
|
3694
|
+
const pre = sortScope();
|
|
2334
3695
|
return this.connection({
|
|
3696
|
+
scope,
|
|
2335
3697
|
match: relationshipPattern(this.model, variable, rel, m, r),
|
|
2336
3698
|
predicate: this.where.connection(r, m, rel, args.where),
|
|
2337
|
-
order: this.connectionOrder(r, m, rel, args.sort),
|
|
3699
|
+
order: this.connectionOrder(r, m, rel, args.sort, pre),
|
|
3700
|
+
pre,
|
|
2338
3701
|
nodeVar: m,
|
|
2339
3702
|
relVar: r,
|
|
2340
|
-
projectNode: (nodes) => this.projectNode(m, target, nodes),
|
|
2341
|
-
projectProperties: props ? (nodes) => this.projectProperties(r, props, nodes) : void 0,
|
|
3703
|
+
projectNode: (nodes, sc, p) => this.projectNode(m, target, nodes, sc, p),
|
|
3704
|
+
projectProperties: props ? (nodes, sc, p) => this.projectProperties(r, props, nodes, sc, p) : void 0,
|
|
2342
3705
|
node: target,
|
|
2343
3706
|
props,
|
|
2344
3707
|
args,
|
|
@@ -2348,45 +3711,194 @@ var SelectionCompiler = class {
|
|
|
2348
3711
|
}
|
|
2349
3712
|
/** `movies(where, sort, limit, offset)`. */
|
|
2350
3713
|
rootList(node, args, fieldNodes) {
|
|
2351
|
-
this.assertReadable(node);
|
|
2352
3714
|
const v = this.ctx.variable("this");
|
|
2353
|
-
const
|
|
2354
|
-
const
|
|
3715
|
+
const auth = this.readRules(v, node, fieldNodes);
|
|
3716
|
+
const pred = and3([this.where.node(v, node, args.where), auth.filter]);
|
|
3717
|
+
const pre = sortScope();
|
|
3718
|
+
const order = this.nodeOrder(v, node, args.sort, pre);
|
|
2355
3719
|
const page = paging(this.ctx, args.offset, args.limit);
|
|
2356
|
-
const
|
|
2357
|
-
const
|
|
3720
|
+
const inner = [];
|
|
3721
|
+
const proj = this.projectNode(v, node, fieldNodes, inner, pre);
|
|
3722
|
+
const head = [
|
|
2358
3723
|
`MATCH (${v}${labels(node.labels)})`,
|
|
2359
3724
|
pred ? `WHERE ${pred}` : "",
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
3725
|
+
...pre.clauses,
|
|
3726
|
+
withClause(v, order, page, pre),
|
|
3727
|
+
...inner
|
|
3728
|
+
];
|
|
3729
|
+
if (auth.failure !== void 0) {
|
|
3730
|
+
const root = [];
|
|
3731
|
+
const row = this.rowGate(inner, auth.failure, proj.expr, this.forbiddenMap());
|
|
3732
|
+
const list2 = this.subquery(root, "collect", head, row);
|
|
3733
|
+
const match = `(${v}${labels(node.labels)})`;
|
|
3734
|
+
const value = this.gate(root, match, pred, auth.failure, list2, this.forbiddenList());
|
|
3735
|
+
return {
|
|
3736
|
+
cypher: [...root, `RETURN ${value} AS this`].join("\n"),
|
|
3737
|
+
params: this.ctx.params,
|
|
3738
|
+
decode: (rows) => Array.isArray(rows[0]) ? rows[0].map(proj.decode) : []
|
|
3739
|
+
};
|
|
3740
|
+
}
|
|
3741
|
+
const cypher = [...head, `RETURN ${proj.expr} AS this`].filter(Boolean).join("\n");
|
|
2363
3742
|
return { cypher, params: this.ctx.params, decode: (rows) => rows.map(proj.decode) };
|
|
2364
3743
|
}
|
|
2365
3744
|
/** `moviesConnection(where, sort, first, after)`. */
|
|
2366
3745
|
rootConnection(node, args, fieldNodes) {
|
|
2367
|
-
this.assertReadable(node);
|
|
2368
3746
|
const v = this.ctx.variable("this");
|
|
3747
|
+
const root = [];
|
|
3748
|
+
const pre = sortScope();
|
|
2369
3749
|
const c = this.connection({
|
|
3750
|
+
scope: root,
|
|
2370
3751
|
match: `(${v}${labels(node.labels)})`,
|
|
2371
3752
|
predicate: this.where.node(v, node, args.where),
|
|
2372
|
-
order: this.nodeOrder(v, node, args.sort),
|
|
3753
|
+
order: this.nodeOrder(v, node, args.sort, pre),
|
|
3754
|
+
pre,
|
|
2373
3755
|
nodeVar: v,
|
|
2374
|
-
projectNode: (nodes) => this.projectNode(v, node, nodes),
|
|
3756
|
+
projectNode: (nodes, sc, p) => this.projectNode(v, node, nodes, sc, p),
|
|
2375
3757
|
node,
|
|
2376
3758
|
args,
|
|
2377
3759
|
fieldNodes,
|
|
2378
3760
|
owner: `${node.plural}Connection`
|
|
2379
3761
|
});
|
|
2380
3762
|
return {
|
|
2381
|
-
cypher: `RETURN ${c.expr} AS this
|
|
3763
|
+
cypher: [...root, `RETURN ${c.expr} AS this`].join("\n"),
|
|
2382
3764
|
params: this.ctx.params,
|
|
2383
3765
|
decode: (rows) => c.decode(rows[0])
|
|
2384
3766
|
};
|
|
2385
3767
|
}
|
|
3768
|
+
/**
|
|
3769
|
+
* A `Query` / `Mutation` `@cypher` field: `CALL () { <statement> }` then one row per returned
|
|
3770
|
+
* value (a scalar list column is flattened, like v7). A non-list field takes the first row.
|
|
3771
|
+
* Returned nodes get the READ rules of their type and the selection's projection.
|
|
3772
|
+
*/
|
|
3773
|
+
rootCypher(field, args, fieldNodes) {
|
|
3774
|
+
const call = statementCall(this.ctx, field.cypher, field.args, args);
|
|
3775
|
+
const list2 = field.type.list;
|
|
3776
|
+
if (field.kind !== "node") {
|
|
3777
|
+
const decode = attributeDecoder({ kind: field.kind, type: field.type });
|
|
3778
|
+
const x = this.ctx.variable("value");
|
|
3779
|
+
const cypher = list2 ? [call, `UNWIND ${column(field.cypher)} AS ${x}`, `RETURN ${x} AS this`] : [call, `RETURN ${column(field.cypher)} AS this`];
|
|
3780
|
+
return {
|
|
3781
|
+
cypher: cypher.join("\n"),
|
|
3782
|
+
params: this.ctx.params,
|
|
3783
|
+
decode: list2 ? (rows) => rows.map((r) => decode(r)) : (rows) => rows.length ? decode(rows[0]) : null
|
|
3784
|
+
};
|
|
3785
|
+
}
|
|
3786
|
+
const target = this.model.node(field.type.name);
|
|
3787
|
+
this.authenticate(target, "READ");
|
|
3788
|
+
const p = this.cypherNodes(call, field.cypher, target, fieldNodes);
|
|
3789
|
+
return {
|
|
3790
|
+
cypher: [...p.clauses, `RETURN ${p.row} AS this`].join("\n"),
|
|
3791
|
+
params: this.ctx.params,
|
|
3792
|
+
decode: list2 ? (rows) => rows.map(p.decode) : (rows) => rows.length ? p.decode(rows[0]) : null
|
|
3793
|
+
};
|
|
3794
|
+
}
|
|
3795
|
+
/**
|
|
3796
|
+
* A `@fulltext` query (`moviesByTitle(phrase, where, sort, first, after)`), v7 7.6:
|
|
3797
|
+
* `db.index.fulltext.queryNodes(index, phrase)` keeps the nodes of the type that match `where`
|
|
3798
|
+
* (`score: { min, max }` and `node`) and its READ filter rules; `totalCount` counts them,
|
|
3799
|
+
* `edges` (`node`, `score`, offset cursors) are ordered by `sort` (no order: the index order,
|
|
3800
|
+
* best score first) and paginated by `first` / `after`. A matching node that fails READ
|
|
3801
|
+
* `validate` rules makes the query `Forbidden`.
|
|
3802
|
+
*/
|
|
3803
|
+
rootFulltext(node, index, args, fieldNodes) {
|
|
3804
|
+
this.authenticate(node, "READ");
|
|
3805
|
+
const v = this.ctx.variable("this");
|
|
3806
|
+
const score = this.ctx.variable("score");
|
|
3807
|
+
const conn = collectFields(this.info, subSelections(fieldNodes));
|
|
3808
|
+
const edgeFields = [...conn].filter(([, n]) => n[0].name.value === "edges").flatMap(([, n]) => n);
|
|
3809
|
+
const nodeFields = [...collectFields(this.info, subSelections(edgeFields))].filter(([, n]) => n[0].name.value === "node").flatMap(([, n]) => n);
|
|
3810
|
+
const auth = this.readRules(v, node, nodeFields);
|
|
3811
|
+
const where = args.where ?? {};
|
|
3812
|
+
const scoreWhere = where.score ?? {};
|
|
3813
|
+
const pred = and3([
|
|
3814
|
+
`${v}${labels(node.labels)}`,
|
|
3815
|
+
typeof scoreWhere.min === "number" ? `${score} >= ${this.ctx.param(scoreWhere.min)}` : void 0,
|
|
3816
|
+
typeof scoreWhere.max === "number" ? `${score} <= ${this.ctx.param(scoreWhere.max)}` : void 0,
|
|
3817
|
+
this.where.node(v, node, where.node),
|
|
3818
|
+
auth.filter
|
|
3819
|
+
]);
|
|
3820
|
+
const pre = sortScope();
|
|
3821
|
+
const items = [];
|
|
3822
|
+
for (const s of Array.isArray(args.sort) ? args.sort : []) {
|
|
3823
|
+
if (s === null || typeof s !== "object") continue;
|
|
3824
|
+
for (const [k, dir] of Object.entries(s)) {
|
|
3825
|
+
if (k === "score" && (dir === "ASC" || dir === "DESC")) items.push(`${score} ${dir}`);
|
|
3826
|
+
else if (k === "node")
|
|
3827
|
+
items.push(...this.sortItems(v, node.attributes, dir, node.name, pre));
|
|
3828
|
+
}
|
|
3829
|
+
}
|
|
3830
|
+
const afterOffset = cursorToOffset(args.after);
|
|
3831
|
+
const offset = afterOffset === void 0 ? 0 : afterOffset + 1;
|
|
3832
|
+
const page = paging(this.ctx, offset || void 0, args.first);
|
|
3833
|
+
const edges = this.ctx.variable("edges");
|
|
3834
|
+
const e = this.ctx.variable("edge");
|
|
3835
|
+
const inner = [];
|
|
3836
|
+
const entries = [`score: ${score}`];
|
|
3837
|
+
const decoders = [];
|
|
3838
|
+
for (const [key, nodes] of collectFields(this.info, subSelections(edgeFields))) {
|
|
3839
|
+
const name = nodes[0].name.value;
|
|
3840
|
+
if (name === "cursor") decoders.push([key, (_r, i) => offsetToCursor(offset + i)]);
|
|
3841
|
+
else if (name === "score") decoders.push([key, (r) => toFloat(r.score)]);
|
|
3842
|
+
else if (name === "node") {
|
|
3843
|
+
const p = this.projectNode(v, node, nodes, inner, pre);
|
|
3844
|
+
entries.push(`${q(key)}: ${p.expr}`);
|
|
3845
|
+
decoders.push([key, (r) => p.decode(r[key])]);
|
|
3846
|
+
}
|
|
3847
|
+
}
|
|
3848
|
+
const order = items.length ? `ORDER BY ${items.join(", ")}` : "";
|
|
3849
|
+
const denied = this.ctx.variable("denied");
|
|
3850
|
+
const pageVar = this.ctx.variable("page");
|
|
3851
|
+
const result = `{ edges: ${pageVar}, total: size(${edges}) }`;
|
|
3852
|
+
const cypher = [
|
|
3853
|
+
`CALL db.index.fulltext.queryNodes(${this.ctx.param(index.indexName)}, ${this.ctx.param(args.phrase ?? "")}) YIELD node AS ${v}, score AS ${score}`,
|
|
3854
|
+
`WHERE ${pred}`,
|
|
3855
|
+
`WITH collect({ node: ${v}, score: ${score} }) AS ${edges}${auth.failure ? `, sum(CASE WHEN ${auth.failure} THEN 1 ELSE 0 END) > 0 AS ${denied}` : ""}`,
|
|
3856
|
+
`CALL (${edges}) {`,
|
|
3857
|
+
`UNWIND ${edges} AS ${e}`,
|
|
3858
|
+
`WITH ${e}.node AS ${v}, ${e}.score AS ${score}`,
|
|
3859
|
+
...pre.clauses,
|
|
3860
|
+
withClause(`${v}, ${score}`, order, page, pre),
|
|
3861
|
+
...inner,
|
|
3862
|
+
`RETURN collect({ ${entries.join(", ")} }) AS ${pageVar}`,
|
|
3863
|
+
`}`,
|
|
3864
|
+
`RETURN ${auth.failure ? `CASE WHEN ${denied} THEN ${this.forbiddenMap()} ELSE ${result} END` : result} AS this`
|
|
3865
|
+
].filter(Boolean).join("\n");
|
|
3866
|
+
return {
|
|
3867
|
+
cypher,
|
|
3868
|
+
params: this.ctx.params,
|
|
3869
|
+
decode: (rows) => {
|
|
3870
|
+
const r = rows[0] ?? {};
|
|
3871
|
+
const total = toNumber(r.total ?? 0);
|
|
3872
|
+
const rawEdges = Array.isArray(r.edges) ? r.edges : [];
|
|
3873
|
+
const out = {};
|
|
3874
|
+
const list2 = rawEdges.map(
|
|
3875
|
+
(raw, i) => Object.fromEntries(decoders.map(([k, dec]) => [k, dec(raw ?? {}, i)]))
|
|
3876
|
+
);
|
|
3877
|
+
for (const [key, nodes] of conn) {
|
|
3878
|
+
const name = nodes[0].name.value;
|
|
3879
|
+
if (name === "totalCount") out[key] = total;
|
|
3880
|
+
else if (name === "edges") out[key] = list2;
|
|
3881
|
+
else if (name === "pageInfo") {
|
|
3882
|
+
const info = {};
|
|
3883
|
+
for (const [pk, pn] of collectFields(this.info, subSelections(nodes))) {
|
|
3884
|
+
const n = pn[0].name.value;
|
|
3885
|
+
if (n === "hasNextPage") info[pk] = offset + list2.length < total;
|
|
3886
|
+
else if (n === "hasPreviousPage") info[pk] = offset > 0;
|
|
3887
|
+
else if (n === "startCursor") info[pk] = list2.length ? offsetToCursor(offset) : null;
|
|
3888
|
+
else if (n === "endCursor")
|
|
3889
|
+
info[pk] = list2.length ? offsetToCursor(offset + list2.length - 1) : null;
|
|
3890
|
+
}
|
|
3891
|
+
out[key] = info;
|
|
3892
|
+
}
|
|
3893
|
+
}
|
|
3894
|
+
return out;
|
|
3895
|
+
}
|
|
3896
|
+
};
|
|
3897
|
+
}
|
|
2386
3898
|
};
|
|
2387
3899
|
|
|
2388
3900
|
// src/v7/cypher/mutate.ts
|
|
2389
|
-
import { GraphQLError as
|
|
3901
|
+
import { GraphQLError as GraphQLError4 } from "graphql";
|
|
2390
3902
|
import { isInt as isInt2 } from "neo4j-driver";
|
|
2391
3903
|
var COUNTER_KEYS = {
|
|
2392
3904
|
nodesCreated: "nc",
|
|
@@ -2471,25 +3983,49 @@ function decodeCounts(fields, counts) {
|
|
|
2471
3983
|
);
|
|
2472
3984
|
}
|
|
2473
3985
|
var MutationCompiler = class {
|
|
2474
|
-
constructor(model, info) {
|
|
3986
|
+
constructor(model, info, auth) {
|
|
2475
3987
|
this.model = model;
|
|
2476
3988
|
this.info = info;
|
|
2477
|
-
this.
|
|
3989
|
+
this.auth = auth;
|
|
3990
|
+
this.select = new SelectionCompiler(model, info, auth);
|
|
2478
3991
|
this.ctx = this.select.ctx;
|
|
2479
|
-
this.
|
|
3992
|
+
this.rules = this.select.rules;
|
|
3993
|
+
this.where = new WhereCompiler(model, this.ctx);
|
|
2480
3994
|
}
|
|
2481
3995
|
model;
|
|
2482
3996
|
info;
|
|
3997
|
+
auth;
|
|
2483
3998
|
select;
|
|
2484
3999
|
where;
|
|
2485
4000
|
ctx;
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
4001
|
+
rules;
|
|
4002
|
+
/** `@authentication` for `operation` on the type and on the written `fields`. */
|
|
4003
|
+
authenticate(node, operation, fields = []) {
|
|
4004
|
+
checkAuthentication(this.model, this.auth, node, [operation]);
|
|
4005
|
+
for (const f of fields) checkAuthentication(this.model, this.auth, node, [operation], f);
|
|
4006
|
+
}
|
|
4007
|
+
/** Attributes written by a create / update input (`title`, `title_SET`, …). */
|
|
4008
|
+
writtenAttributes(node, input) {
|
|
4009
|
+
if (!isPlainObject2(input)) return [];
|
|
4010
|
+
const out = /* @__PURE__ */ new Set();
|
|
4011
|
+
for (const [key, value] of Object.entries(input)) {
|
|
4012
|
+
if (value === void 0) continue;
|
|
4013
|
+
const attr = node.attributes.find((a) => a.name === key) ?? node.attributes.find(
|
|
4014
|
+
(a) => key.startsWith(`${a.name}_`) && key.slice(a.name.length + 1) in LEGACY_UPDATE_OPERATORS
|
|
2491
4015
|
);
|
|
4016
|
+
if (attr) out.add(attr);
|
|
2492
4017
|
}
|
|
4018
|
+
return [...out];
|
|
4019
|
+
}
|
|
4020
|
+
/**
|
|
4021
|
+
* Evaluates `check` (a `CASE WHEN … THEN 'Forbidden' END`) on the current rows and keeps its result
|
|
4022
|
+
* (`WITH *, … AS authN`), so a BEFORE check sees the graph as it was before the writes that follow.
|
|
4023
|
+
*/
|
|
4024
|
+
capture(block, check) {
|
|
4025
|
+
if (check === void 0) return;
|
|
4026
|
+
const v = this.ctx.variable("auth");
|
|
4027
|
+
block.add(`WITH *, ${check} AS ${v}`);
|
|
4028
|
+
block.check([v]);
|
|
2493
4029
|
}
|
|
2494
4030
|
props(rel) {
|
|
2495
4031
|
return rel.properties ? this.model.properties.get(rel.properties) : void 0;
|
|
@@ -2556,7 +4092,7 @@ ${indent(inner.clauses)}
|
|
|
2556
4092
|
const sets = [];
|
|
2557
4093
|
for (const [attr, { keys, ops }] of byAttribute) {
|
|
2558
4094
|
if (keys.length > 1) {
|
|
2559
|
-
throw new
|
|
4095
|
+
throw new GraphQLError4(
|
|
2560
4096
|
`Conflicting modification of ${keys.map((k) => `[[${k}]]`).join(", ")} on type ${owner}`
|
|
2561
4097
|
);
|
|
2562
4098
|
}
|
|
@@ -2615,7 +4151,12 @@ ${indent(inner.clauses)}
|
|
|
2615
4151
|
// ---------------------------------------------------------------------------------------------
|
|
2616
4152
|
/** `CREATE (v:Label) SET …` and the nested writes of a `${Node}CreateInput`. */
|
|
2617
4153
|
createNode(block, v, node, input, afterCreate) {
|
|
2618
|
-
this.
|
|
4154
|
+
const written = this.writtenAttributes(node, input);
|
|
4155
|
+
this.authenticate(
|
|
4156
|
+
node,
|
|
4157
|
+
"CREATE",
|
|
4158
|
+
written.map((a) => a.name)
|
|
4159
|
+
);
|
|
2619
4160
|
block.add(`CREATE (${v}${labels(node.labels)})`);
|
|
2620
4161
|
const sets = [
|
|
2621
4162
|
...onCreateGenerated(v, node.attributes),
|
|
@@ -2624,13 +4165,16 @@ ${indent(inner.clauses)}
|
|
|
2624
4165
|
if (sets.length) block.add(`SET ${sets.join(", ")}`);
|
|
2625
4166
|
block.count("nc", "1");
|
|
2626
4167
|
afterCreate?.();
|
|
2627
|
-
if (
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
4168
|
+
if (isPlainObject2(input)) {
|
|
4169
|
+
for (const rel of node.relationships) {
|
|
4170
|
+
const field = input[rel.name];
|
|
4171
|
+
if (!isPlainObject2(field)) continue;
|
|
4172
|
+
for (const el of asList(field.create)) this.nestedCreate(block, v, rel, el);
|
|
4173
|
+
for (const el of asList(field.connect)) this.connect(block, v, rel, el);
|
|
4174
|
+
}
|
|
2633
4175
|
}
|
|
4176
|
+
const after = this.rules.check(this.rules.fails(v, node, "CREATE", "AFTER", written));
|
|
4177
|
+
if (after) block.check([after]);
|
|
2634
4178
|
}
|
|
2635
4179
|
/** `{ node, edge }` of a relationship `create`: a new related node and the edge to it. */
|
|
2636
4180
|
nestedCreate(block, from, rel, el) {
|
|
@@ -2657,12 +4201,21 @@ ${indent(inner.clauses)}
|
|
|
2657
4201
|
connect(block, from, rel, el) {
|
|
2658
4202
|
if (!isPlainObject2(el)) return;
|
|
2659
4203
|
const target = this.model.node(rel.target);
|
|
2660
|
-
this.
|
|
4204
|
+
const source = this.model.node(rel.source);
|
|
4205
|
+
this.authenticate(target, "CREATE_RELATIONSHIP");
|
|
4206
|
+
this.authenticate(source, "CREATE_RELATIONSHIP");
|
|
2661
4207
|
const inner = new Block();
|
|
2662
4208
|
const t = this.ctx.variable("this");
|
|
2663
4209
|
const where = isPlainObject2(el.where) ? el.where.node : void 0;
|
|
2664
|
-
const pred =
|
|
4210
|
+
const pred = and4([
|
|
4211
|
+
this.where.node(t, target, where),
|
|
4212
|
+
this.rules.filter(t, target, "CREATE_RELATIONSHIP")
|
|
4213
|
+
]);
|
|
2665
4214
|
inner.add(`MATCH (${t}${labels(target.labels)})${pred ? ` WHERE ${pred}` : ""}`);
|
|
4215
|
+
this.capture(
|
|
4216
|
+
inner,
|
|
4217
|
+
this.rules.check(this.rules.fails(t, target, "CREATE_RELATIONSHIP", "BEFORE"))
|
|
4218
|
+
);
|
|
2666
4219
|
for (const nested of asList(el.connect)) {
|
|
2667
4220
|
if (!isPlainObject2(nested)) continue;
|
|
2668
4221
|
for (const [name, els] of Object.entries(nested)) {
|
|
@@ -2678,6 +4231,11 @@ ${indent(inner.clauses)}
|
|
|
2678
4231
|
if (sets.length) inner.add(`SET ${sets.join(", ")}`);
|
|
2679
4232
|
}
|
|
2680
4233
|
inner.count("rc", "1");
|
|
4234
|
+
const after = [
|
|
4235
|
+
this.rules.check(this.rules.fails(t, target, "CREATE_RELATIONSHIP", "AFTER")),
|
|
4236
|
+
this.rules.check(this.rules.fails(from, source, "CREATE_RELATIONSHIP", "AFTER"))
|
|
4237
|
+
].filter((c) => c !== void 0);
|
|
4238
|
+
if (after.length) inner.check(after);
|
|
2681
4239
|
this.call(block, [from], inner);
|
|
2682
4240
|
}
|
|
2683
4241
|
// ---------------------------------------------------------------------------------------------
|
|
@@ -2719,15 +4277,25 @@ ${indent(inner.clauses)}
|
|
|
2719
4277
|
nestedUpdate(block, from, rel, el) {
|
|
2720
4278
|
if (!isPlainObject2(el)) return;
|
|
2721
4279
|
const target = this.model.node(rel.target);
|
|
2722
|
-
this.
|
|
4280
|
+
const written = this.writtenAttributes(target, el.node);
|
|
4281
|
+
this.authenticate(
|
|
4282
|
+
target,
|
|
4283
|
+
"UPDATE",
|
|
4284
|
+
written.map((a) => a.name)
|
|
4285
|
+
);
|
|
4286
|
+
const typeRules = written.length > 0 || this.hasNestedUpdate(target, el.node);
|
|
2723
4287
|
const props = this.props(rel);
|
|
2724
4288
|
const inner = new Block();
|
|
2725
4289
|
const t = this.ctx.variable("this");
|
|
2726
4290
|
const r = this.ctx.variable("edge");
|
|
2727
|
-
const pred =
|
|
4291
|
+
const pred = and4([
|
|
4292
|
+
this.where.connection(r, t, rel, el.where),
|
|
4293
|
+
typeRules ? this.rules.filter(t, target, "UPDATE") : void 0
|
|
4294
|
+
]);
|
|
2728
4295
|
inner.add(
|
|
2729
4296
|
`MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`
|
|
2730
4297
|
);
|
|
4298
|
+
this.capture(inner, this.updateCheck(t, target, "BEFORE", written, typeRules));
|
|
2731
4299
|
const checks = [];
|
|
2732
4300
|
const sets = [
|
|
2733
4301
|
...onUpdateGenerated(t, target.attributes),
|
|
@@ -2745,20 +4313,66 @@ ${indent(inner.clauses)}
|
|
|
2745
4313
|
if (sets.length) inner.add(`SET ${sets.join(", ")}`);
|
|
2746
4314
|
inner.check(checks);
|
|
2747
4315
|
this.updateRelationships(inner, t, target, el.node);
|
|
4316
|
+
const after = this.updateCheck(t, target, "AFTER", written, typeRules);
|
|
4317
|
+
if (after) inner.check([after]);
|
|
2748
4318
|
if (!inner.hasCounts() && inner.clauses.length === 1) return;
|
|
2749
4319
|
this.call(block, [from], inner);
|
|
2750
4320
|
}
|
|
4321
|
+
/** Whether an update input has a nested `update` on one of its relationships. */
|
|
4322
|
+
hasNestedUpdate(node, input) {
|
|
4323
|
+
if (!isPlainObject2(input)) return false;
|
|
4324
|
+
return node.relationships.some(
|
|
4325
|
+
(rel) => asList(input[rel.name]).some(
|
|
4326
|
+
(el) => isPlainObject2(el) && el.update !== void 0 && el.update !== null
|
|
4327
|
+
)
|
|
4328
|
+
);
|
|
4329
|
+
}
|
|
4330
|
+
/** UPDATE `validate` check: the type's rules (when they apply) and the written attributes' rules. */
|
|
4331
|
+
updateCheck(v, node, when, written, typeRules) {
|
|
4332
|
+
const validations = [
|
|
4333
|
+
...typeRules ? this.rules.validations(v, node, "UPDATE", when) : [],
|
|
4334
|
+
...written.flatMap(
|
|
4335
|
+
(a) => this.rules.validations(v, { ...node, auth: {} }, "UPDATE", when, [a])
|
|
4336
|
+
)
|
|
4337
|
+
];
|
|
4338
|
+
return this.rules.check(this.rules.failure(validations));
|
|
4339
|
+
}
|
|
2751
4340
|
/** `{ where, disconnect }`: deletes the matching relationships (then nested disconnects). */
|
|
2752
4341
|
disconnect(block, from, rel, el) {
|
|
2753
4342
|
if (!isPlainObject2(el)) return;
|
|
2754
4343
|
const target = this.model.node(rel.target);
|
|
2755
|
-
this.
|
|
4344
|
+
const source = this.model.node(rel.source);
|
|
4345
|
+
this.authenticate(target, "DELETE_RELATIONSHIP");
|
|
4346
|
+
this.authenticate(source, "DELETE_RELATIONSHIP");
|
|
2756
4347
|
const inner = new Block();
|
|
2757
4348
|
const t = this.ctx.variable("this");
|
|
2758
4349
|
const r = this.ctx.variable("edge");
|
|
2759
|
-
const pred =
|
|
2760
|
-
|
|
2761
|
-
|
|
4350
|
+
const pred = and4([
|
|
4351
|
+
this.where.connection(r, t, rel, el.where),
|
|
4352
|
+
this.rules.filter(t, target, "DELETE_RELATIONSHIP")
|
|
4353
|
+
]);
|
|
4354
|
+
const pattern = relationshipPattern(this.model, from, rel, t, r);
|
|
4355
|
+
const sourceBefore = this.rules.fails(from, source, "DELETE_RELATIONSHIP", "BEFORE");
|
|
4356
|
+
const targetOnNull = this.onNull(
|
|
4357
|
+
t,
|
|
4358
|
+
(n) => this.rules.failure([
|
|
4359
|
+
...this.rules.validations(n, target, "DELETE_RELATIONSHIP", "BEFORE"),
|
|
4360
|
+
...this.rules.validations(n, target, "DELETE_RELATIONSHIP", "AFTER")
|
|
4361
|
+
])
|
|
4362
|
+
);
|
|
4363
|
+
this.capture(
|
|
4364
|
+
block,
|
|
4365
|
+
this.rules.check(
|
|
4366
|
+
orParts([
|
|
4367
|
+
sourceBefore,
|
|
4368
|
+
targetOnNull ? `(NOT EXISTS { MATCH ${pattern}${pred ? ` WHERE ${pred}` : ""} } AND ${targetOnNull})` : void 0
|
|
4369
|
+
])
|
|
4370
|
+
)
|
|
4371
|
+
);
|
|
4372
|
+
inner.add(`MATCH ${pattern}${pred ? ` WHERE ${pred}` : ""}`);
|
|
4373
|
+
this.capture(
|
|
4374
|
+
inner,
|
|
4375
|
+
this.rules.check(this.rules.fails(t, target, "DELETE_RELATIONSHIP", "BEFORE"))
|
|
2762
4376
|
);
|
|
2763
4377
|
if (isPlainObject2(el.disconnect)) {
|
|
2764
4378
|
for (const [name, els] of Object.entries(el.disconnect)) {
|
|
@@ -2769,7 +4383,24 @@ ${indent(inner.clauses)}
|
|
|
2769
4383
|
if (inner.clauses.length > 1) inner.add("WITH *");
|
|
2770
4384
|
inner.add(`DELETE ${r}`);
|
|
2771
4385
|
inner.count("rd", "1");
|
|
4386
|
+
const targetAfter = this.rules.check(
|
|
4387
|
+
this.rules.fails(t, target, "DELETE_RELATIONSHIP", "AFTER")
|
|
4388
|
+
);
|
|
4389
|
+
if (targetAfter) inner.check([targetAfter]);
|
|
2772
4390
|
this.call(block, [from], inner);
|
|
4391
|
+
this.capture(
|
|
4392
|
+
block,
|
|
4393
|
+
this.rules.check(this.rules.fails(from, source, "DELETE_RELATIONSHIP", "AFTER"))
|
|
4394
|
+
);
|
|
4395
|
+
}
|
|
4396
|
+
/**
|
|
4397
|
+
* `failure(n)` evaluated with `n` bound to `null` (`[n IN [null] | …][0]`), or `undefined` when there
|
|
4398
|
+
* are no rules: what v7's OPTIONAL MATCH checks when no node matched.
|
|
4399
|
+
*/
|
|
4400
|
+
onNull(name, failure) {
|
|
4401
|
+
const n = this.ctx.variable(`${name}_null`);
|
|
4402
|
+
const f = failure(n);
|
|
4403
|
+
return f === void 0 ? void 0 : `[${n} IN [null] | ${f}][0]`;
|
|
2773
4404
|
}
|
|
2774
4405
|
// ---------------------------------------------------------------------------------------------
|
|
2775
4406
|
// Delete
|
|
@@ -2779,8 +4410,7 @@ ${indent(inner.clauses)}
|
|
|
2779
4410
|
* matching `where` and, through nested `delete`, nodes related to them. `match` is the chain of
|
|
2780
4411
|
* `MATCH … WHERE …` that binds `t`.
|
|
2781
4412
|
*/
|
|
2782
|
-
deleteLists(match, t, node, del) {
|
|
2783
|
-
this.assertWritable(node);
|
|
4413
|
+
deleteLists(match, t, node, del, failures) {
|
|
2784
4414
|
const lists = [`COLLECT { ${match} RETURN DISTINCT ${t} }`];
|
|
2785
4415
|
if (!isPlainObject2(del)) return lists;
|
|
2786
4416
|
for (const [name, els] of Object.entries(del)) {
|
|
@@ -2788,15 +4418,34 @@ ${indent(inner.clauses)}
|
|
|
2788
4418
|
const target = this.model.node(rel.target);
|
|
2789
4419
|
for (const el of asList(els)) {
|
|
2790
4420
|
if (!isPlainObject2(el)) continue;
|
|
2791
|
-
const u = this.
|
|
2792
|
-
|
|
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));
|
|
4421
|
+
const { chain, u } = this.nestedDeleteMatch(match, t, rel, target, el, failures);
|
|
4422
|
+
lists.push(...this.deleteLists(chain, u, target, el.delete, failures));
|
|
2796
4423
|
}
|
|
2797
4424
|
}
|
|
2798
4425
|
return lists;
|
|
2799
4426
|
}
|
|
4427
|
+
/**
|
|
4428
|
+
* `MATCH` of a nested `{ where, delete }` from `t` (after `parent`, the chain binding `t`), with the
|
|
4429
|
+
* target's DELETE filter; pushes to `failures` the list of failed DELETE validations of the matched
|
|
4430
|
+
* nodes (v7: OPTIONAL MATCH, so the rules are also evaluated on `null` when nothing matches).
|
|
4431
|
+
*/
|
|
4432
|
+
nestedDeleteMatch(parent, t, rel, target, el, failures) {
|
|
4433
|
+
this.authenticate(target, "DELETE");
|
|
4434
|
+
const u = this.ctx.variable("this");
|
|
4435
|
+
const r = this.ctx.variable("edge");
|
|
4436
|
+
const pred = and4([
|
|
4437
|
+
this.where.connection(r, u, rel, el.where),
|
|
4438
|
+
this.rules.filter(u, target, "DELETE")
|
|
4439
|
+
]);
|
|
4440
|
+
const step = `${relationshipPattern(this.model, t, rel, u, r)}${pred ? ` WHERE ${pred}` : ""}`;
|
|
4441
|
+
const failure = this.rules.fails(u, target, "DELETE", "BEFORE");
|
|
4442
|
+
if (failure) {
|
|
4443
|
+
failures.push(
|
|
4444
|
+
`COLLECT { ${parent ? `${parent} ` : ""}OPTIONAL MATCH ${step} WITH * WHERE ${failure} RETURN ${this.rules.forbiddenMessage()} }`
|
|
4445
|
+
);
|
|
4446
|
+
}
|
|
4447
|
+
return { chain: `${parent ? `${parent} ` : ""}MATCH ${step}`, u };
|
|
4448
|
+
}
|
|
2800
4449
|
/**
|
|
2801
4450
|
* Deletes the distinct nodes of `list` with their relationships, counting both
|
|
2802
4451
|
* (`WITH … AS deleted, COUNT { … } AS …`, then `FOREACH … DETACH DELETE`).
|
|
@@ -2819,13 +4468,18 @@ ${indent(inner.clauses)}
|
|
|
2819
4468
|
nestedDelete(block, from, rel, el) {
|
|
2820
4469
|
if (!isPlainObject2(el)) return;
|
|
2821
4470
|
const target = this.model.node(rel.target);
|
|
2822
|
-
const
|
|
2823
|
-
const
|
|
2824
|
-
const
|
|
2825
|
-
const match = `MATCH ${relationshipPattern(this.model, from, rel, t, r)}${pred ? ` WHERE ${pred}` : ""}`;
|
|
2826
|
-
const lists = this.deleteLists(match, t, target, el.delete);
|
|
4471
|
+
const failures = [];
|
|
4472
|
+
const { chain, u } = this.nestedDeleteMatch("", from, rel, target, el, failures);
|
|
4473
|
+
const lists = this.deleteLists(chain, u, target, el.delete, failures);
|
|
2827
4474
|
const inner = new Block();
|
|
2828
|
-
|
|
4475
|
+
const keep = [];
|
|
4476
|
+
if (failures.length) {
|
|
4477
|
+
const f = this.ctx.variable("authDelete");
|
|
4478
|
+
inner.add(`WITH ${failures.join(" + ")} AS ${f}`);
|
|
4479
|
+
inner.errors.push(f);
|
|
4480
|
+
keep.push(f);
|
|
4481
|
+
}
|
|
4482
|
+
this.deleteNodes(inner, `(${lists.join(" + ")})`, keep);
|
|
2829
4483
|
this.call(block, [from], inner);
|
|
2830
4484
|
}
|
|
2831
4485
|
// ---------------------------------------------------------------------------------------------
|
|
@@ -2835,7 +4489,7 @@ ${indent(inner.clauses)}
|
|
|
2835
4489
|
* `WITH <nodes> AS nodes, <info>`, the projections of the response's node list (one per response
|
|
2836
4490
|
* key) and the decoder of the `{ info, <plural> }` response.
|
|
2837
4491
|
*/
|
|
2838
|
-
response(block, nodes, info, node, fieldNodes) {
|
|
4492
|
+
response(block, nodes, info, node, fieldNodes, readRules2) {
|
|
2839
4493
|
const list2 = this.ctx.variable("nodes");
|
|
2840
4494
|
block.add(`WITH ${nodes} AS ${list2}, ${info} AS info`);
|
|
2841
4495
|
const entries = [];
|
|
@@ -2856,11 +4510,18 @@ ${indent(inner.clauses)}
|
|
|
2856
4510
|
} else if (name === node.plural) {
|
|
2857
4511
|
const v = this.ctx.variable("this");
|
|
2858
4512
|
const d = this.ctx.variable("data");
|
|
2859
|
-
const
|
|
4513
|
+
const auth = readRules2 ? this.select.readRules(v, node, nodesOfKey) : {};
|
|
4514
|
+
const scope = [];
|
|
4515
|
+
const proj = this.select.projectNode(v, node, nodesOfKey, scope);
|
|
4516
|
+
const value = auth.failure ? `CASE WHEN ${auth.failure} THEN ${this.select.forbiddenMap()} ELSE ${proj.expr} END` : proj.expr;
|
|
4517
|
+
const filter = auth.filter ? `
|
|
4518
|
+
WITH ${v} WHERE ${auth.filter}` : "";
|
|
4519
|
+
const clauses = scope.map((c) => `
|
|
4520
|
+
${indent([c])}`).join("");
|
|
2860
4521
|
block.add(
|
|
2861
4522
|
`CALL (${list2}) {
|
|
2862
|
-
UNWIND ${list2} AS ${v}
|
|
2863
|
-
RETURN collect(${
|
|
4523
|
+
UNWIND ${list2} AS ${v}${filter}${clauses}
|
|
4524
|
+
RETURN collect(${value}) AS ${d}
|
|
2864
4525
|
}`
|
|
2865
4526
|
);
|
|
2866
4527
|
entries.push(`${q(key)}: ${d}`);
|
|
@@ -2874,28 +4535,30 @@ ${indent(inner.clauses)}
|
|
|
2874
4535
|
}
|
|
2875
4536
|
}
|
|
2876
4537
|
const data = entries.length ? `{ ${entries.join(", ")} }` : "{}";
|
|
2877
|
-
block.
|
|
4538
|
+
const gated = block.errors.length ? `CASE WHEN size(info.errors) = 0 THEN ${data} ELSE {} END` : data;
|
|
4539
|
+
block.add(`RETURN { info: info, data: ${gated} } AS this`);
|
|
2878
4540
|
return {
|
|
2879
4541
|
cypher: block.clauses.join("\n"),
|
|
2880
4542
|
params: this.ctx.params,
|
|
2881
4543
|
decode: (rows) => {
|
|
2882
4544
|
const raw = rows[0] ?? {};
|
|
2883
4545
|
const errors = (raw.info ?? {}).errors;
|
|
2884
|
-
if (Array.isArray(errors) && errors.length) throw new
|
|
4546
|
+
if (Array.isArray(errors) && errors.length) throw new GraphQLError4(String(errors[0]));
|
|
2885
4547
|
return Object.fromEntries(decoders.map(([k, dec]) => [k, dec(raw)]));
|
|
2886
4548
|
}
|
|
2887
4549
|
};
|
|
2888
4550
|
}
|
|
2889
4551
|
/** `createMovies(input: [...])`. */
|
|
2890
4552
|
rootCreate(node, args, fieldNodes) {
|
|
2891
|
-
this.
|
|
4553
|
+
this.authenticate(node, "CREATE");
|
|
2892
4554
|
const block = new Block();
|
|
2893
4555
|
const groups = [];
|
|
2894
4556
|
const inputs = asList(args.input);
|
|
4557
|
+
const checked2 = this.hasCreateChecks(node);
|
|
2895
4558
|
let i = 0;
|
|
2896
4559
|
while (i < inputs.length) {
|
|
2897
4560
|
let j = i;
|
|
2898
|
-
while (j < inputs.length && !this.hasRelationshipInput(node, inputs[j])) j++;
|
|
4561
|
+
while (j < inputs.length && !checked2 && !this.hasRelationshipInput(node, inputs[j])) j++;
|
|
2899
4562
|
if (j > i) {
|
|
2900
4563
|
groups.push(this.createFlat(block, node, inputs.slice(i, j)));
|
|
2901
4564
|
i = j;
|
|
@@ -2922,7 +4585,15 @@ ${indent(inner.clauses)}
|
|
|
2922
4585
|
groups.length ? groups.join(" + ") : "[]",
|
|
2923
4586
|
block.aggregate(false),
|
|
2924
4587
|
node,
|
|
2925
|
-
fieldNodes
|
|
4588
|
+
fieldNodes,
|
|
4589
|
+
false
|
|
4590
|
+
);
|
|
4591
|
+
}
|
|
4592
|
+
/** Whether creating `node` has `validate` rules or field-level `@authentication` to check. */
|
|
4593
|
+
hasCreateChecks(node) {
|
|
4594
|
+
const rules = [node.auth, ...node.attributes.map((a) => a.auth)];
|
|
4595
|
+
return rules.some(
|
|
4596
|
+
(a) => a?.authorization?.validate.some((r) => r.operations.includes("CREATE")) || a !== node.auth && a?.authentication !== void 0
|
|
2926
4597
|
);
|
|
2927
4598
|
}
|
|
2928
4599
|
hasRelationshipInput(node, input) {
|
|
@@ -2930,6 +4601,7 @@ ${indent(inner.clauses)}
|
|
|
2930
4601
|
}
|
|
2931
4602
|
/** `UNWIND $rows AS row CREATE (n:Label) SET n.p = row.p, …` for inputs without relationships. */
|
|
2932
4603
|
createFlat(block, node, inputs) {
|
|
4604
|
+
this.authenticate(node, "CREATE");
|
|
2933
4605
|
const keys = /* @__PURE__ */ new Set();
|
|
2934
4606
|
for (const input of inputs) {
|
|
2935
4607
|
if (!isPlainObject2(input)) continue;
|
|
@@ -2967,12 +4639,22 @@ ${indent(lines)}
|
|
|
2967
4639
|
}
|
|
2968
4640
|
/** `updateMovies(where, update)`; without `update` it only reads (and refreshes UPDATE timestamps). */
|
|
2969
4641
|
rootUpdate(node, args, fieldNodes) {
|
|
2970
|
-
this.
|
|
4642
|
+
const written = this.writtenAttributes(node, args.update);
|
|
4643
|
+
this.authenticate(
|
|
4644
|
+
node,
|
|
4645
|
+
"UPDATE",
|
|
4646
|
+
written.map((a) => a.name)
|
|
4647
|
+
);
|
|
4648
|
+
const typeRules = written.length > 0;
|
|
2971
4649
|
const block = new Block();
|
|
2972
4650
|
const v = this.ctx.variable("this");
|
|
2973
|
-
const pred =
|
|
4651
|
+
const pred = and4([
|
|
4652
|
+
this.where.node(v, node, args.where),
|
|
4653
|
+
typeRules ? this.rules.filter(v, node, "UPDATE") : void 0
|
|
4654
|
+
]);
|
|
2974
4655
|
block.add(`MATCH (${v}${labels(node.labels)})${pred ? `
|
|
2975
4656
|
WHERE ${pred}` : ""}`);
|
|
4657
|
+
this.capture(block, this.updateCheck(v, node, "BEFORE", written, typeRules));
|
|
2976
4658
|
const checks = [];
|
|
2977
4659
|
const sets = [
|
|
2978
4660
|
...onUpdateGenerated(v, node.attributes),
|
|
@@ -2988,42 +4670,57 @@ WHERE ${pred}` : ""}`);
|
|
|
2988
4670
|
if (sets.length) block.add(`SET ${sets.join(", ")}`);
|
|
2989
4671
|
block.check(checks);
|
|
2990
4672
|
this.updateRelationships(block, v, node, args.update);
|
|
2991
|
-
|
|
4673
|
+
const after = this.updateCheck(v, node, "AFTER", written, typeRules);
|
|
4674
|
+
if (after) block.check([after]);
|
|
4675
|
+
return this.response(block, `collect(${v})`, block.aggregate(), node, fieldNodes, true);
|
|
2992
4676
|
}
|
|
2993
4677
|
/** `deleteMovies(where, delete)`: one `DeleteInfo`. */
|
|
2994
4678
|
rootDelete(node, args, fieldNodes) {
|
|
2995
|
-
this.
|
|
4679
|
+
this.authenticate(node, "DELETE");
|
|
2996
4680
|
const block = new Block();
|
|
2997
4681
|
const v = this.ctx.variable("this");
|
|
2998
|
-
const pred = this.where.node(v, node, args.where);
|
|
4682
|
+
const pred = and4([this.where.node(v, node, args.where), this.rules.filter(v, node, "DELETE")]);
|
|
2999
4683
|
block.add(`MATCH (${v}${labels(node.labels)})${pred ? `
|
|
3000
4684
|
WHERE ${pred}` : ""}`);
|
|
3001
4685
|
const roots = this.ctx.variable("roots");
|
|
3002
4686
|
const nested = [];
|
|
4687
|
+
const failures = [];
|
|
4688
|
+
const rootFailure = this.rules.check(this.rules.fails(v, node, "DELETE", "BEFORE"));
|
|
3003
4689
|
if (isPlainObject2(args.delete)) {
|
|
3004
4690
|
for (const [name, els] of Object.entries(args.delete)) {
|
|
3005
4691
|
const rel = this.relationship(node, name);
|
|
3006
4692
|
const target = this.model.node(rel.target);
|
|
3007
4693
|
for (const el of asList(els)) {
|
|
3008
4694
|
if (!isPlainObject2(el)) continue;
|
|
3009
|
-
const
|
|
3010
|
-
|
|
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));
|
|
4695
|
+
const { chain, u } = this.nestedDeleteMatch("", v, rel, target, el, failures);
|
|
4696
|
+
nested.push(...this.deleteLists(chain, u, target, el.delete, failures));
|
|
3014
4697
|
}
|
|
3015
4698
|
}
|
|
3016
4699
|
}
|
|
4700
|
+
const errorParts = [
|
|
4701
|
+
...rootFailure ? [`collect(${rootFailure})`] : [],
|
|
4702
|
+
...failures.length ? [`reduce(acc = [], l IN collect(${failures.join(" + ")}) | acc + l)`] : []
|
|
4703
|
+
];
|
|
4704
|
+
const keep = [];
|
|
4705
|
+
let errors;
|
|
4706
|
+
if (errorParts.length) {
|
|
4707
|
+
errors = this.ctx.variable("authErrors");
|
|
4708
|
+
keep.push(errors);
|
|
4709
|
+
}
|
|
4710
|
+
const errorsItem = errors ? `, ${errorParts.join(" + ")} AS ${errors}` : "";
|
|
3017
4711
|
let list2;
|
|
3018
4712
|
if (nested.length) {
|
|
3019
4713
|
const related = this.ctx.variable("related");
|
|
3020
|
-
block.add(
|
|
4714
|
+
block.add(
|
|
4715
|
+
`WITH collect(${v}) AS ${roots}, collect(${nested.join(" + ")}) AS ${related}${errorsItem}`
|
|
4716
|
+
);
|
|
3021
4717
|
list2 = `(${roots} + reduce(acc = [], l IN ${related} | acc + l))`;
|
|
3022
4718
|
} else {
|
|
3023
|
-
block.add(`WITH collect(${v}) AS ${roots}`);
|
|
4719
|
+
block.add(`WITH collect(${v}) AS ${roots}${errorsItem}`);
|
|
3024
4720
|
list2 = roots;
|
|
3025
4721
|
}
|
|
3026
|
-
this.deleteNodes(block, list2,
|
|
4722
|
+
this.deleteNodes(block, list2, keep);
|
|
4723
|
+
if (errors) block.errors.push(errors);
|
|
3027
4724
|
const fields = [...collectFields(this.info, subSelections(fieldNodes))].map(
|
|
3028
4725
|
([k, n]) => [k, n[0].name.value]
|
|
3029
4726
|
);
|
|
@@ -3033,21 +4730,36 @@ WHERE ${pred}` : ""}`);
|
|
|
3033
4730
|
params: this.ctx.params,
|
|
3034
4731
|
decode: (rows) => {
|
|
3035
4732
|
const counts = rows[0] ?? {};
|
|
4733
|
+
const errors2 = counts.errors;
|
|
4734
|
+
if (Array.isArray(errors2) && errors2.length) throw new GraphQLError4(String(errors2[0]));
|
|
3036
4735
|
return decodeCounts(fields, counts);
|
|
3037
4736
|
}
|
|
3038
4737
|
};
|
|
3039
4738
|
}
|
|
3040
4739
|
};
|
|
4740
|
+
function and4(parts) {
|
|
4741
|
+
const ps = parts.filter((p) => p !== void 0);
|
|
4742
|
+
if (ps.length === 0) return void 0;
|
|
4743
|
+
if (ps.length === 1) return ps[0];
|
|
4744
|
+
return ps.map((p) => `(${p})`).join(" AND ");
|
|
4745
|
+
}
|
|
4746
|
+
function orParts(parts) {
|
|
4747
|
+
const ps = parts.filter((p) => p !== void 0);
|
|
4748
|
+
if (ps.length === 0) return void 0;
|
|
4749
|
+
if (ps.length === 1) return ps[0];
|
|
4750
|
+
return ps.map((p) => `(${p})`).join(" OR ");
|
|
4751
|
+
}
|
|
3041
4752
|
var intAttribute = {
|
|
3042
4753
|
name: "pop",
|
|
3043
4754
|
property: "pop",
|
|
3044
4755
|
type: { name: "Int", list: false, required: true, elementRequired: false },
|
|
3045
4756
|
kind: "scalar",
|
|
3046
|
-
id: false
|
|
4757
|
+
id: false,
|
|
4758
|
+
args: []
|
|
3047
4759
|
};
|
|
3048
4760
|
|
|
3049
4761
|
// src/v7/execute.ts
|
|
3050
|
-
import
|
|
4762
|
+
import neo4j4 from "neo4j-driver";
|
|
3051
4763
|
function createExecutors(opts) {
|
|
3052
4764
|
const log = (cypher, params) => {
|
|
3053
4765
|
if (opts.debug)
|
|
@@ -3072,7 +4784,7 @@ function createExecutors(opts) {
|
|
|
3072
4784
|
const withSession = async (mode, fn) => {
|
|
3073
4785
|
const session = driver.session({
|
|
3074
4786
|
database: opts.database,
|
|
3075
|
-
defaultAccessMode:
|
|
4787
|
+
defaultAccessMode: neo4j4.session[mode]
|
|
3076
4788
|
});
|
|
3077
4789
|
try {
|
|
3078
4790
|
return await fn(session);
|
|
@@ -3114,8 +4826,8 @@ import {
|
|
|
3114
4826
|
} from "graphql";
|
|
3115
4827
|
|
|
3116
4828
|
// src/v7/scalars.ts
|
|
3117
|
-
import { GraphQLError as
|
|
3118
|
-
import
|
|
4829
|
+
import { GraphQLError as GraphQLError5, GraphQLScalarType, Kind as Kind5 } from "graphql";
|
|
4830
|
+
import neo4j5, { isDate, isDateTime, isInt as isInt3 } from "neo4j-driver";
|
|
3119
4831
|
var GraphQLBigInt = new GraphQLScalarType({
|
|
3120
4832
|
name: "BigInt",
|
|
3121
4833
|
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 +4835,18 @@ var GraphQLBigInt = new GraphQLScalarType({
|
|
|
3123
4835
|
if (isInt3(value)) return value.toString(10);
|
|
3124
4836
|
if (typeof value === "string") return value;
|
|
3125
4837
|
if (typeof value === "number" || typeof value === "bigint") return value.toString(10);
|
|
3126
|
-
throw new
|
|
4838
|
+
throw new GraphQLError5(`BigInt cannot represent value: ${String(value)}`);
|
|
3127
4839
|
},
|
|
3128
4840
|
parseValue(value) {
|
|
3129
4841
|
if (typeof value !== "string") {
|
|
3130
|
-
throw new
|
|
4842
|
+
throw new GraphQLError5(
|
|
3131
4843
|
"BigInt values are not JSON serializable. Please pass as a string in variables, or inline in the GraphQL query."
|
|
3132
4844
|
);
|
|
3133
4845
|
}
|
|
3134
4846
|
try {
|
|
3135
|
-
return
|
|
4847
|
+
return neo4j5.int(value, { strictStringValidation: true });
|
|
3136
4848
|
} catch {
|
|
3137
|
-
throw new
|
|
4849
|
+
throw new GraphQLError5(
|
|
3138
4850
|
"Value must be either a BigInt, or a string representing a BigInt value."
|
|
3139
4851
|
);
|
|
3140
4852
|
}
|
|
@@ -3142,11 +4854,11 @@ var GraphQLBigInt = new GraphQLScalarType({
|
|
|
3142
4854
|
parseLiteral(ast) {
|
|
3143
4855
|
if (ast.kind === Kind5.INT || ast.kind === Kind5.STRING) {
|
|
3144
4856
|
try {
|
|
3145
|
-
return
|
|
4857
|
+
return neo4j5.int(ast.value, { strictStringValidation: true });
|
|
3146
4858
|
} catch {
|
|
3147
4859
|
}
|
|
3148
4860
|
}
|
|
3149
|
-
throw new
|
|
4861
|
+
throw new GraphQLError5(
|
|
3150
4862
|
"Value must be either a BigInt, or a string representing a BigInt value."
|
|
3151
4863
|
);
|
|
3152
4864
|
}
|
|
@@ -3158,22 +4870,22 @@ var GraphQLDate = new GraphQLScalarType({
|
|
|
3158
4870
|
serialize(value) {
|
|
3159
4871
|
if (typeof value === "string") return formatDate(value);
|
|
3160
4872
|
if (isDate(value)) return formatDate(String(value));
|
|
3161
|
-
throw new
|
|
4873
|
+
throw new GraphQLError5(`Date cannot represent value: ${String(value)}`);
|
|
3162
4874
|
},
|
|
3163
4875
|
parseValue(value) {
|
|
3164
4876
|
if (typeof value === "string") {
|
|
3165
4877
|
const d = new Date(value);
|
|
3166
4878
|
if (Number.isNaN(d.getTime())) {
|
|
3167
|
-
throw new
|
|
4879
|
+
throw new GraphQLError5(`Date cannot represent non temporal value: ${value}`);
|
|
3168
4880
|
}
|
|
3169
|
-
return
|
|
4881
|
+
return neo4j5.types.Date.fromStandardDate(d);
|
|
3170
4882
|
}
|
|
3171
4883
|
if (isDate(value)) return value;
|
|
3172
|
-
throw new
|
|
4884
|
+
throw new GraphQLError5(`Date cannot represent non string value: ${String(value)}`);
|
|
3173
4885
|
},
|
|
3174
4886
|
parseLiteral(ast) {
|
|
3175
|
-
if (ast.kind !== Kind5.STRING) throw new
|
|
3176
|
-
return
|
|
4887
|
+
if (ast.kind !== Kind5.STRING) throw new GraphQLError5("Date cannot represent non string value.");
|
|
4888
|
+
return neo4j5.types.Date.fromStandardDate(new Date(ast.value));
|
|
3177
4889
|
}
|
|
3178
4890
|
});
|
|
3179
4891
|
var GraphQLDateTime = new GraphQLScalarType({
|
|
@@ -3183,20 +4895,20 @@ var GraphQLDateTime = new GraphQLScalarType({
|
|
|
3183
4895
|
if (typeof value === "string") return new Date(value).toISOString();
|
|
3184
4896
|
if (isDateTime(value)) return new Date(String(value)).toISOString();
|
|
3185
4897
|
if (value instanceof Date) return value.toISOString();
|
|
3186
|
-
throw new
|
|
4898
|
+
throw new GraphQLError5(`DateTime cannot represent value: ${String(value)}`);
|
|
3187
4899
|
},
|
|
3188
4900
|
parseValue(value) {
|
|
3189
4901
|
if (typeof value === "string") {
|
|
3190
4902
|
if (Number.isNaN(new Date(value).getTime())) {
|
|
3191
|
-
throw new
|
|
4903
|
+
throw new GraphQLError5(`DateTime cannot represent non temporal value: ${value}`);
|
|
3192
4904
|
}
|
|
3193
4905
|
return value;
|
|
3194
4906
|
}
|
|
3195
|
-
throw new
|
|
4907
|
+
throw new GraphQLError5(`DateTime cannot represent non string value: ${String(value)}`);
|
|
3196
4908
|
},
|
|
3197
4909
|
parseLiteral(ast) {
|
|
3198
4910
|
if (ast.kind !== Kind5.STRING)
|
|
3199
|
-
throw new
|
|
4911
|
+
throw new GraphQLError5("DateTime cannot represent non string value.");
|
|
3200
4912
|
return ast.value;
|
|
3201
4913
|
}
|
|
3202
4914
|
});
|
|
@@ -3562,7 +5274,7 @@ var TypeRegistry = class {
|
|
|
3562
5274
|
attributeWhereFields(attributes) {
|
|
3563
5275
|
const out = {};
|
|
3564
5276
|
for (const a of attributes) {
|
|
3565
|
-
if (a.
|
|
5277
|
+
if (a.args.length) continue;
|
|
3566
5278
|
out[a.name] = { type: this.scalarFilters(a), deprecationReason: a.deprecated };
|
|
3567
5279
|
const named = this.namedType(a.type.name);
|
|
3568
5280
|
const dep = (op) => a.deprecated ?? `Please use the relevant generic filter ${a.name}: { ${op}: ... }`;
|
|
@@ -3706,7 +5418,9 @@ ${users.join("\n")}`
|
|
|
3706
5418
|
propertiesSort(p) {
|
|
3707
5419
|
return this.input(
|
|
3708
5420
|
`${p.name}Sort`,
|
|
3709
|
-
() => Object.fromEntries(
|
|
5421
|
+
() => Object.fromEntries(
|
|
5422
|
+
p.attributes.filter((a) => !a.args.length).map((a) => [a.name, { type: this.sortDirection() }])
|
|
5423
|
+
)
|
|
3710
5424
|
);
|
|
3711
5425
|
}
|
|
3712
5426
|
propertiesCreate(p) {
|
|
@@ -3738,6 +5452,14 @@ ${users.join("\n")}`
|
|
|
3738
5452
|
n.name,
|
|
3739
5453
|
() => {
|
|
3740
5454
|
const fields = attributeOutputFields(this, n.attributes);
|
|
5455
|
+
for (const c of n.cypherNodes) {
|
|
5456
|
+
fields[c.name] = {
|
|
5457
|
+
type: this.nodeRefType(c.type, c.target),
|
|
5458
|
+
description: c.description,
|
|
5459
|
+
deprecationReason: c.deprecated,
|
|
5460
|
+
args: argumentConfigs(this, c.args)
|
|
5461
|
+
};
|
|
5462
|
+
}
|
|
3741
5463
|
for (const r of n.relationships) {
|
|
3742
5464
|
const target = this.model.node(r.target);
|
|
3743
5465
|
fields[r.name] = {
|
|
@@ -3771,7 +5493,7 @@ ${users.join("\n")}`
|
|
|
3771
5493
|
return this.input(
|
|
3772
5494
|
`${n.name}Sort`,
|
|
3773
5495
|
() => Object.fromEntries(
|
|
3774
|
-
n.attributes.filter((a) => !a.type.list).map((a) => [a.name, { type: this.sortDirection() }])
|
|
5496
|
+
n.attributes.filter((a) => !a.type.list && !a.args.length).map((a) => [a.name, { type: this.sortDirection() }])
|
|
3775
5497
|
),
|
|
3776
5498
|
`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
5499
|
);
|
|
@@ -3785,6 +5507,17 @@ ${users.join("\n")}`
|
|
|
3785
5507
|
OR: { type: list(nn(self)) },
|
|
3786
5508
|
...this.attributeWhereFields(n.attributes)
|
|
3787
5509
|
};
|
|
5510
|
+
for (const c of n.cypherNodes) {
|
|
5511
|
+
if (c.args.length) continue;
|
|
5512
|
+
const target = this.model.node(c.target);
|
|
5513
|
+
if (!c.type.list) {
|
|
5514
|
+
out[c.name] = { type: this.nodeWhere(target) };
|
|
5515
|
+
continue;
|
|
5516
|
+
}
|
|
5517
|
+
out[c.name] = { type: this.relationshipFilters(target) };
|
|
5518
|
+
for (const q2 of QUANTIFIERS)
|
|
5519
|
+
out[`${c.name}_${q2.toUpperCase()}`] = { type: this.nodeWhere(target) };
|
|
5520
|
+
}
|
|
3788
5521
|
const sourcePlural = pluralize(n.name);
|
|
3789
5522
|
for (const r of n.relationships) {
|
|
3790
5523
|
const target = this.model.node(r.target);
|
|
@@ -3828,6 +5561,67 @@ ${users.join("\n")}`
|
|
|
3828
5561
|
);
|
|
3829
5562
|
});
|
|
3830
5563
|
}
|
|
5564
|
+
/** `Movie`, `[Movie!]!`, … for a field returning nodes. */
|
|
5565
|
+
nodeRefType(t, target) {
|
|
5566
|
+
const named = this.node(this.model.node(target));
|
|
5567
|
+
if (t.list) {
|
|
5568
|
+
const inner = list(t.elementRequired ? nn(named) : named);
|
|
5569
|
+
return t.required ? nn(inner) : inner;
|
|
5570
|
+
}
|
|
5571
|
+
return t.required ? nn(named) : named;
|
|
5572
|
+
}
|
|
5573
|
+
/** The type of a `Query` / `Mutation` `@cypher` field. */
|
|
5574
|
+
rootFieldType(f) {
|
|
5575
|
+
return f.kind === "node" ? this.nodeRefType(f.type, f.type.name) : this.attributeType(f.type);
|
|
5576
|
+
}
|
|
5577
|
+
floatWhere() {
|
|
5578
|
+
return this.input(
|
|
5579
|
+
"FloatWhere",
|
|
5580
|
+
() => ({ max: { type: GraphQLFloat }, min: { type: GraphQLFloat } }),
|
|
5581
|
+
"The input for filtering a float"
|
|
5582
|
+
);
|
|
5583
|
+
}
|
|
5584
|
+
fulltextEdge(n) {
|
|
5585
|
+
return this.object(`${n.name}IndexEdge`, () => ({
|
|
5586
|
+
cursor: { type: nn(GraphQLString) },
|
|
5587
|
+
node: { type: nn(this.node(n)) },
|
|
5588
|
+
score: { type: nn(GraphQLFloat) }
|
|
5589
|
+
}));
|
|
5590
|
+
}
|
|
5591
|
+
fulltextConnection(n) {
|
|
5592
|
+
return this.object(`${n.pascalPlural}IndexConnection`, () => ({
|
|
5593
|
+
edges: { type: nn(list(nn(this.fulltextEdge(n)))) },
|
|
5594
|
+
pageInfo: { type: nn(this.pageInfo()) },
|
|
5595
|
+
totalCount: { type: nn(GraphQLInt) }
|
|
5596
|
+
}));
|
|
5597
|
+
}
|
|
5598
|
+
fulltextSort(n) {
|
|
5599
|
+
return this.input(
|
|
5600
|
+
`${n.name}IndexSort`,
|
|
5601
|
+
() => ({ node: { type: this.nodeSort(n) }, score: { type: this.sortDirection() } }),
|
|
5602
|
+
`The input for sorting a Fulltext query on an index of ${n.name}`
|
|
5603
|
+
);
|
|
5604
|
+
}
|
|
5605
|
+
fulltextWhere(n) {
|
|
5606
|
+
return this.input(
|
|
5607
|
+
`${n.name}IndexWhere`,
|
|
5608
|
+
() => ({ node: { type: this.nodeWhere(n) }, score: { type: this.floatWhere() } }),
|
|
5609
|
+
`The input for filtering a full-text query on an index of ${n.name}`
|
|
5610
|
+
);
|
|
5611
|
+
}
|
|
5612
|
+
/** `moviesByTitle(phrase, where, sort, first, after)`. */
|
|
5613
|
+
fulltextField(n) {
|
|
5614
|
+
return {
|
|
5615
|
+
type: nn(this.fulltextConnection(n)),
|
|
5616
|
+
args: {
|
|
5617
|
+
after: { type: GraphQLString },
|
|
5618
|
+
first: { type: GraphQLInt },
|
|
5619
|
+
phrase: { type: nn(GraphQLString) },
|
|
5620
|
+
sort: { type: list(nn(this.fulltextSort(n))) },
|
|
5621
|
+
where: { type: this.fulltextWhere(n) }
|
|
5622
|
+
}
|
|
5623
|
+
};
|
|
5624
|
+
}
|
|
3831
5625
|
nodeAggregate(n) {
|
|
3832
5626
|
return this.object(`${n.name}Aggregate`, () => {
|
|
3833
5627
|
const fields = { count: { type: nn(this.count()) } };
|
|
@@ -4130,18 +5924,40 @@ function relationshipType(reg, r) {
|
|
|
4130
5924
|
}
|
|
4131
5925
|
return r.required ? nn(target) : target;
|
|
4132
5926
|
}
|
|
5927
|
+
function argumentConfigs(reg, args) {
|
|
5928
|
+
if (!args.length) return void 0;
|
|
5929
|
+
const out = {};
|
|
5930
|
+
for (const a of args) {
|
|
5931
|
+
const type = reg.attributeType(a.type);
|
|
5932
|
+
out[a.name] = {
|
|
5933
|
+
type,
|
|
5934
|
+
description: a.description,
|
|
5935
|
+
defaultValue: a.defaultAst ? valueFromAST(a.defaultAst, type) : void 0
|
|
5936
|
+
};
|
|
5937
|
+
}
|
|
5938
|
+
return out;
|
|
5939
|
+
}
|
|
4133
5940
|
function attributeOutputFields(reg, attributes) {
|
|
4134
5941
|
const out = {};
|
|
4135
5942
|
for (const a of attributes) {
|
|
4136
5943
|
const field = {
|
|
4137
5944
|
type: reg.attributeType(a.type),
|
|
4138
5945
|
description: a.description,
|
|
4139
|
-
deprecationReason: a.deprecated
|
|
5946
|
+
deprecationReason: a.deprecated,
|
|
5947
|
+
args: argumentConfigs(reg, a.args)
|
|
4140
5948
|
};
|
|
4141
5949
|
out[a.name] = field;
|
|
4142
5950
|
}
|
|
4143
5951
|
return out;
|
|
4144
5952
|
}
|
|
5953
|
+
function rootField(reg, f) {
|
|
5954
|
+
return {
|
|
5955
|
+
type: reg.rootFieldType(f),
|
|
5956
|
+
description: f.description,
|
|
5957
|
+
deprecationReason: f.deprecated,
|
|
5958
|
+
args: argumentConfigs(reg, f.args)
|
|
5959
|
+
};
|
|
5960
|
+
}
|
|
4145
5961
|
function aggregateSelectionFields(reg, attributes) {
|
|
4146
5962
|
return Object.fromEntries(
|
|
4147
5963
|
attributes.filter(isAggregable).map((a) => [a.name, { type: nn(reg.aggregateSelection(a.type.name)) }])
|
|
@@ -4179,7 +5995,9 @@ function buildV7Schema(model) {
|
|
|
4179
5995
|
where: { type: reg.nodeWhere(n) }
|
|
4180
5996
|
}
|
|
4181
5997
|
};
|
|
5998
|
+
for (const ft of n.fulltext) fields[ft.queryName] = reg.fulltextField(n);
|
|
4182
5999
|
}
|
|
6000
|
+
for (const f of model.query.fields) fields[f.name] = rootField(reg, f);
|
|
4183
6001
|
return fields;
|
|
4184
6002
|
}
|
|
4185
6003
|
});
|
|
@@ -4208,32 +6026,177 @@ function buildV7Schema(model) {
|
|
|
4208
6026
|
}
|
|
4209
6027
|
};
|
|
4210
6028
|
}
|
|
6029
|
+
for (const f of model.mutation.fields) fields[f.name] = rootField(reg, f);
|
|
4211
6030
|
return fields;
|
|
4212
6031
|
}
|
|
4213
6032
|
});
|
|
4214
6033
|
return new GraphQLSchema({ query, mutation });
|
|
4215
6034
|
}
|
|
4216
6035
|
|
|
6036
|
+
// src/v7/auth/jwt.ts
|
|
6037
|
+
import {
|
|
6038
|
+
createRemoteJWKSet,
|
|
6039
|
+
decodeJwt,
|
|
6040
|
+
jwtVerify
|
|
6041
|
+
} from "jose";
|
|
6042
|
+
var MAX_REMOTE_SETS = 64;
|
|
6043
|
+
function parseBearerToken(value) {
|
|
6044
|
+
if (!value.startsWith("Bearer ")) return value || void 0;
|
|
6045
|
+
return value.split("Bearer ")[1] || void 0;
|
|
6046
|
+
}
|
|
6047
|
+
var JwtDecoder = class {
|
|
6048
|
+
constructor(feature) {
|
|
6049
|
+
this.feature = feature;
|
|
6050
|
+
if (typeof feature.key !== "function") this.staticKey = this.resolve(feature.key);
|
|
6051
|
+
}
|
|
6052
|
+
feature;
|
|
6053
|
+
staticKey;
|
|
6054
|
+
remoteSets = /* @__PURE__ */ new Map();
|
|
6055
|
+
resolve(key) {
|
|
6056
|
+
if (typeof key === "string") return new TextEncoder().encode(key);
|
|
6057
|
+
if (!key || typeof key.url !== "string") {
|
|
6058
|
+
throw new TypeError(
|
|
6059
|
+
"@cyphra/graphql: features.authorization.key must be a string or { url }."
|
|
6060
|
+
);
|
|
6061
|
+
}
|
|
6062
|
+
let set = this.remoteSets.get(key.url);
|
|
6063
|
+
if (!set) {
|
|
6064
|
+
set = createRemoteJWKSet(new URL(key.url), key.options);
|
|
6065
|
+
if (this.remoteSets.size >= MAX_REMOTE_SETS) {
|
|
6066
|
+
this.remoteSets.delete(this.remoteSets.keys().next().value);
|
|
6067
|
+
}
|
|
6068
|
+
this.remoteSets.set(key.url, set);
|
|
6069
|
+
}
|
|
6070
|
+
return set;
|
|
6071
|
+
}
|
|
6072
|
+
/** The payload, or `undefined` when there is no token or it is not valid. */
|
|
6073
|
+
async decode(context) {
|
|
6074
|
+
const raw = context.token;
|
|
6075
|
+
if (typeof raw !== "string" || !raw) return void 0;
|
|
6076
|
+
const token = parseBearerToken(raw);
|
|
6077
|
+
if (!token) return void 0;
|
|
6078
|
+
try {
|
|
6079
|
+
if (this.feature.verify === false) return decodeJwt(token);
|
|
6080
|
+
const key = this.staticKey ?? this.resolve(this.feature.key(context));
|
|
6081
|
+
const { payload } = key instanceof Uint8Array ? await jwtVerify(token, key, this.feature.verifyOptions) : await jwtVerify(token, key, this.feature.verifyOptions);
|
|
6082
|
+
return payload;
|
|
6083
|
+
} catch {
|
|
6084
|
+
return void 0;
|
|
6085
|
+
}
|
|
6086
|
+
}
|
|
6087
|
+
};
|
|
6088
|
+
|
|
4217
6089
|
// src/v7/index.ts
|
|
4218
6090
|
var byResponseKey = (source, _args, _ctx, info) => source && typeof source === "object" ? source[info.path.key] : void 0;
|
|
4219
|
-
function
|
|
4220
|
-
|
|
6091
|
+
function withCypherParams(params, ctx) {
|
|
6092
|
+
const extra = ctx && typeof ctx === "object" ? ctx.cypherParams : void 0;
|
|
6093
|
+
if (extra === void 0 || extra === null) return params;
|
|
6094
|
+
if (typeof extra !== "object" || Array.isArray(extra)) {
|
|
6095
|
+
throw new GraphQLError6("context.cypherParams must be an object.");
|
|
6096
|
+
}
|
|
6097
|
+
const clash = Object.keys(extra).filter((k) => Object.prototype.hasOwnProperty.call(params, k));
|
|
6098
|
+
if (clash.length) {
|
|
6099
|
+
throw new GraphQLError6(
|
|
6100
|
+
`Duplicate parameter keys between context.cypherParams and generated parameters: [${clash.join(", ")}]`
|
|
6101
|
+
);
|
|
6102
|
+
}
|
|
6103
|
+
return { ...extra, ...params };
|
|
6104
|
+
}
|
|
6105
|
+
function checked(decode) {
|
|
6106
|
+
return (rows) => {
|
|
6107
|
+
if (containsForbidden(rows)) throw forbidden();
|
|
6108
|
+
return decode(rows);
|
|
6109
|
+
};
|
|
6110
|
+
}
|
|
6111
|
+
function rootReadResolver({ model, decoder }, execute, nodeName, kind) {
|
|
6112
|
+
return async (_source, args, ctx, info) => {
|
|
4221
6113
|
const node = model.node(nodeName);
|
|
4222
|
-
const
|
|
6114
|
+
const auth = await authContextFor(ctx, model, decoder);
|
|
6115
|
+
const compiler = new SelectionCompiler(model, info, auth);
|
|
4223
6116
|
const compiled = kind === "list" ? compiler.rootList(node, args, info.fieldNodes) : compiler.rootConnection(node, args, info.fieldNodes);
|
|
4224
|
-
return compiled.decode(
|
|
6117
|
+
return checked(compiled.decode)(
|
|
6118
|
+
await execute(compiled.cypher, withCypherParams(compiled.params, ctx))
|
|
6119
|
+
);
|
|
6120
|
+
};
|
|
6121
|
+
}
|
|
6122
|
+
function fulltextResolver({ model, decoder }, execute, nodeName, queryName) {
|
|
6123
|
+
return async (_source, args, ctx, info) => {
|
|
6124
|
+
const node = model.node(nodeName);
|
|
6125
|
+
const index = node.fulltext.find((f) => f.queryName === queryName);
|
|
6126
|
+
const auth = await authContextFor(ctx, model, decoder);
|
|
6127
|
+
const compiled = new SelectionCompiler(model, info, auth).rootFulltext(
|
|
6128
|
+
node,
|
|
6129
|
+
index,
|
|
6130
|
+
args,
|
|
6131
|
+
info.fieldNodes
|
|
6132
|
+
);
|
|
6133
|
+
return checked(compiled.decode)(
|
|
6134
|
+
await execute(compiled.cypher, withCypherParams(compiled.params, ctx))
|
|
6135
|
+
);
|
|
6136
|
+
};
|
|
6137
|
+
}
|
|
6138
|
+
function rootCypherResolver({ model, decoder }, executors, type, fieldName) {
|
|
6139
|
+
return async (_source, args, ctx, info) => {
|
|
6140
|
+
const field = (type === "Query" ? model.query : model.mutation).fields.find(
|
|
6141
|
+
(f) => f.name === fieldName
|
|
6142
|
+
);
|
|
6143
|
+
const auth = await authContextFor(ctx, model, decoder);
|
|
6144
|
+
checkRootAuthentication(model, auth, type, field);
|
|
6145
|
+
const compiled = new SelectionCompiler(model, info, auth).rootCypher(
|
|
6146
|
+
field,
|
|
6147
|
+
args,
|
|
6148
|
+
info.fieldNodes
|
|
6149
|
+
);
|
|
6150
|
+
const params = withCypherParams(compiled.params, ctx);
|
|
6151
|
+
if (type === "Query")
|
|
6152
|
+
return checked(compiled.decode)(await executors.read(compiled.cypher, params));
|
|
6153
|
+
return executors.write(compiled.cypher, params, checked(compiled.decode));
|
|
4225
6154
|
};
|
|
4226
6155
|
}
|
|
4227
|
-
function rootMutationResolver(model, execute, nodeName, kind) {
|
|
4228
|
-
return async (_source, args,
|
|
6156
|
+
function rootMutationResolver({ model, decoder }, execute, nodeName, kind) {
|
|
6157
|
+
return async (_source, args, ctx, info) => {
|
|
4229
6158
|
const node = model.node(nodeName);
|
|
4230
|
-
const
|
|
6159
|
+
const auth = await authContextFor(ctx, model, decoder);
|
|
6160
|
+
const compiler = new MutationCompiler(model, info, auth);
|
|
4231
6161
|
const a = args;
|
|
4232
6162
|
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(
|
|
6163
|
+
return execute(
|
|
6164
|
+
compiled.cypher,
|
|
6165
|
+
withCypherParams(compiled.params, ctx),
|
|
6166
|
+
checked(compiled.decode)
|
|
6167
|
+
);
|
|
6168
|
+
};
|
|
6169
|
+
}
|
|
6170
|
+
function checkRules(model) {
|
|
6171
|
+
const auth = {
|
|
6172
|
+
isAuthenticated: false,
|
|
6173
|
+
jwt: void 0,
|
|
6174
|
+
claims: void 0,
|
|
6175
|
+
context: {}
|
|
4234
6176
|
};
|
|
6177
|
+
for (const node of model.nodes) {
|
|
6178
|
+
for (const attr of [void 0, ...node.attributes]) {
|
|
6179
|
+
const annotation = attr ? attr.auth : node.auth;
|
|
6180
|
+
if (!annotation?.authorization) continue;
|
|
6181
|
+
const target = attr ? { ...node, auth: {} } : node;
|
|
6182
|
+
const attrs = attr ? [attr] : [];
|
|
6183
|
+
try {
|
|
6184
|
+
const rules = new AuthRules(model, new CypherContext(), auth);
|
|
6185
|
+
for (const op of AUTH_OPERATIONS) {
|
|
6186
|
+
rules.filter("this", target, op, attrs);
|
|
6187
|
+
rules.validations("this", target, op, "BEFORE", attrs);
|
|
6188
|
+
rules.validations("this", target, op, "AFTER", attrs);
|
|
6189
|
+
}
|
|
6190
|
+
} catch (e) {
|
|
6191
|
+
throw new UnsupportedTypeDefsError(
|
|
6192
|
+
`${node.name}${attr ? `.${attr.name}` : ""}: invalid @authorization rule: ${e.message}`
|
|
6193
|
+
);
|
|
6194
|
+
}
|
|
6195
|
+
}
|
|
6196
|
+
}
|
|
4235
6197
|
}
|
|
4236
|
-
function attachResolvers(schema,
|
|
6198
|
+
function attachResolvers(schema, auth, executors) {
|
|
6199
|
+
const model = auth.model;
|
|
4237
6200
|
const execute = executors.read;
|
|
4238
6201
|
for (const type of Object.values(schema.getTypeMap())) {
|
|
4239
6202
|
if (!isObjectType(type) || type.name.startsWith("__")) continue;
|
|
@@ -4242,19 +6205,28 @@ function attachResolvers(schema, model, executors) {
|
|
|
4242
6205
|
}
|
|
4243
6206
|
const query = schema.getQueryType().getFields();
|
|
4244
6207
|
for (const node of model.nodes) {
|
|
4245
|
-
query[node.plural].resolve = rootReadResolver(
|
|
6208
|
+
query[node.plural].resolve = rootReadResolver(auth, execute, node.name, "list");
|
|
4246
6209
|
query[`${node.plural}Connection`].resolve = rootReadResolver(
|
|
4247
|
-
|
|
6210
|
+
auth,
|
|
4248
6211
|
execute,
|
|
4249
6212
|
node.name,
|
|
4250
6213
|
"connection"
|
|
4251
6214
|
);
|
|
6215
|
+
for (const ft of node.fulltext) {
|
|
6216
|
+
query[ft.queryName].resolve = fulltextResolver(auth, execute, node.name, ft.queryName);
|
|
6217
|
+
}
|
|
6218
|
+
}
|
|
6219
|
+
for (const f of model.query.fields) {
|
|
6220
|
+
query[f.name].resolve = rootCypherResolver(auth, executors, "Query", f.name);
|
|
4252
6221
|
}
|
|
4253
6222
|
const mutation = schema.getMutationType().getFields();
|
|
6223
|
+
for (const f of model.mutation.fields) {
|
|
6224
|
+
mutation[f.name].resolve = rootCypherResolver(auth, executors, "Mutation", f.name);
|
|
6225
|
+
}
|
|
4254
6226
|
for (const node of model.nodes) {
|
|
4255
6227
|
for (const kind of ["create", "update", "delete"]) {
|
|
4256
6228
|
mutation[`${kind}${node.pascalPlural}`].resolve = rootMutationResolver(
|
|
4257
|
-
|
|
6229
|
+
auth,
|
|
4258
6230
|
executors.write,
|
|
4259
6231
|
node.name,
|
|
4260
6232
|
kind
|
|
@@ -4264,12 +6236,15 @@ function attachResolvers(schema, model, executors) {
|
|
|
4264
6236
|
}
|
|
4265
6237
|
function makeSchema(options) {
|
|
4266
6238
|
const model = readTypeDefs(options.typeDefs);
|
|
6239
|
+
checkRules(model);
|
|
4267
6240
|
const schema = buildV7Schema(model);
|
|
4268
|
-
|
|
6241
|
+
const feature = options.features?.authorization;
|
|
6242
|
+
const decoder = feature ? new JwtDecoder(feature) : void 0;
|
|
6243
|
+
attachResolvers(schema, { model, decoder }, createExecutors(options));
|
|
4269
6244
|
return schema;
|
|
4270
6245
|
}
|
|
4271
6246
|
function contextFor(opts = {}) {
|
|
4272
|
-
return opts.
|
|
6247
|
+
return Object.fromEntries(Object.entries(opts).filter(([, v]) => v !== void 0));
|
|
4273
6248
|
}
|
|
4274
6249
|
function cyphraSchema(typeDefs) {
|
|
4275
6250
|
const { document, issues } = convertGraphQLTypeDefs([
|