graphql 15.10.2 → 15.11.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.
Files changed (99) hide show
  1. package/error/GraphQLError.js +7 -6
  2. package/error/GraphQLError.js.flow +3 -3
  3. package/error/GraphQLError.mjs +8 -7
  4. package/execution/execute.d.ts +2 -0
  5. package/execution/execute.js +33 -12
  6. package/execution/execute.js.flow +32 -11
  7. package/execution/execute.mjs +33 -12
  8. package/execution/values.d.ts +1 -1
  9. package/execution/values.js +5 -5
  10. package/execution/values.js.flow +5 -2
  11. package/execution/values.mjs +4 -4
  12. package/graphql.d.ts +1 -0
  13. package/graphql.js +4 -1
  14. package/graphql.js.flow +5 -1
  15. package/graphql.mjs +4 -1
  16. package/jsutils/SetMap.js +56 -0
  17. package/jsutils/SetMap.js.flow +39 -0
  18. package/jsutils/SetMap.mjs +47 -0
  19. package/language/lexer.js +21 -2
  20. package/language/lexer.js.flow +24 -2
  21. package/language/lexer.mjs +21 -2
  22. package/language/location.d.ts +5 -0
  23. package/language/location.js +64 -0
  24. package/language/location.js.flow +39 -0
  25. package/language/location.mjs +62 -0
  26. package/language/parser.js +34 -19
  27. package/language/parser.js.flow +54 -10
  28. package/language/parser.mjs +34 -19
  29. package/language/printer.d.ts +7 -0
  30. package/language/printer.js +251 -118
  31. package/language/printer.js.flow +345 -141
  32. package/language/printer.mjs +246 -116
  33. package/language/reducer.js +99 -0
  34. package/language/reducer.js.flow +89 -0
  35. package/language/reducer.mjs +89 -0
  36. package/package.json +1 -4
  37. package/subscription/subscribe.d.ts +2 -0
  38. package/subscription/subscribe.js +4 -3
  39. package/subscription/subscribe.js.flow +6 -0
  40. package/subscription/subscribe.mjs +4 -3
  41. package/type/definition.d.ts +2 -1
  42. package/type/definition.js +8 -8
  43. package/type/definition.js.flow +13 -7
  44. package/type/definition.mjs +7 -7
  45. package/type/scalars.js +5 -5
  46. package/type/scalars.js.flow +1 -1
  47. package/type/scalars.mjs +1 -1
  48. package/utilities/buildASTSchema.js +3 -0
  49. package/utilities/buildASTSchema.js.flow +3 -0
  50. package/utilities/buildASTSchema.mjs +3 -0
  51. package/utilities/coerceInputValue.d.ts +1 -0
  52. package/utilities/coerceInputValue.js +9 -8
  53. package/utilities/coerceInputValue.js.flow +42 -9
  54. package/utilities/coerceInputValue.mjs +10 -9
  55. package/utilities/findBreakingChanges.js +3 -23
  56. package/utilities/findBreakingChanges.js.flow +2 -15
  57. package/utilities/findBreakingChanges.mjs +2 -21
  58. package/utilities/sortValueNode.js +52 -0
  59. package/utilities/sortValueNode.js.flow +42 -0
  60. package/utilities/sortValueNode.mjs +42 -0
  61. package/utilities/valueFromAST.js +2 -2
  62. package/utilities/valueFromAST.js.flow +8 -2
  63. package/utilities/valueFromAST.mjs +2 -2
  64. package/validation/ValidationContext.d.ts +8 -0
  65. package/validation/ValidationContext.js +82 -24
  66. package/validation/ValidationContext.js.flow +70 -21
  67. package/validation/ValidationContext.mjs +80 -24
  68. package/validation/rules/FieldsOnCorrectTypeRule.js +2 -2
  69. package/validation/rules/FieldsOnCorrectTypeRule.js.flow +8 -2
  70. package/validation/rules/FieldsOnCorrectTypeRule.mjs +2 -2
  71. package/validation/rules/KnownArgumentNamesRule.js +8 -9
  72. package/validation/rules/KnownArgumentNamesRule.js.flow +16 -6
  73. package/validation/rules/KnownArgumentNamesRule.mjs +8 -9
  74. package/validation/rules/KnownTypeNamesRule.js +1 -1
  75. package/validation/rules/KnownTypeNamesRule.js.flow +6 -4
  76. package/validation/rules/KnownTypeNamesRule.mjs +1 -1
  77. package/validation/rules/MaxIntrospectionDepthRule.js +37 -17
  78. package/validation/rules/MaxIntrospectionDepthRule.js.flow +46 -15
  79. package/validation/rules/MaxIntrospectionDepthRule.mjs +37 -17
  80. package/validation/rules/NoUnusedFragmentsRule.js +6 -13
  81. package/validation/rules/NoUnusedFragmentsRule.js.flow +6 -10
  82. package/validation/rules/NoUnusedFragmentsRule.mjs +6 -13
  83. package/validation/rules/OverlappingFieldsCanBeMergedRule.js +402 -208
  84. package/validation/rules/OverlappingFieldsCanBeMergedRule.js.flow +566 -330
  85. package/validation/rules/OverlappingFieldsCanBeMergedRule.mjs +400 -206
  86. package/validation/rules/ValuesOfCorrectTypeRule.js +6 -6
  87. package/validation/rules/ValuesOfCorrectTypeRule.js.flow +11 -6
  88. package/validation/rules/ValuesOfCorrectTypeRule.mjs +4 -4
  89. package/validation/validate.d.ts +1 -1
  90. package/validation/validate.js +6 -2
  91. package/validation/validate.js.flow +8 -2
  92. package/validation/validate.mjs +5 -2
  93. package/validation/validationAbortedError.d.ts +4 -0
  94. package/validation/validationAbortedError.js +12 -0
  95. package/validation/validationAbortedError.js.flow +7 -0
  96. package/validation/validationAbortedError.mjs +4 -0
  97. package/version.js +3 -3
  98. package/version.js.flow +3 -3
  99. package/version.mjs +3 -3
@@ -1,54 +1,48 @@
1
1
  // @flow strict
2
- import find from '../../polyfills/find';
3
- import objectEntries from '../../polyfills/objectEntries';
4
-
5
- import type { ObjMap } from '../../jsutils/ObjMap';
6
2
  import inspect from '../../jsutils/inspect';
3
+ import type { ObjMap } from '../../jsutils/ObjMap';
7
4
 
8
5
  import { GraphQLError } from '../../error/GraphQLError';
9
6
 
10
- import type { ASTVisitor } from '../../language/visitor';
11
7
  import type {
12
- SelectionSetNode,
13
- ValueNode,
14
- FieldNode,
15
8
  ArgumentNode,
9
+ FieldNode,
16
10
  FragmentDefinitionNode,
11
+ SelectionSetNode,
12
+ ValueNode,
17
13
  } from '../../language/ast';
14
+ import { isNode } from '../../language/ast';
18
15
  import { Kind } from '../../language/kinds';
19
- import { print } from '../../language/printer';
16
+ import type { ASTVisitor } from '../../language/visitor';
20
17
 
21
18
  import type {
19
+ GraphQLField,
22
20
  GraphQLNamedType,
23
21
  GraphQLOutputType,
24
- GraphQLCompositeType,
25
- GraphQLField,
26
22
  } from '../../type/definition';
27
23
  import {
28
24
  getNamedType,
29
- isNonNullType,
25
+ isInterfaceType,
30
26
  isLeafType,
31
- isObjectType,
32
27
  isListType,
33
- isInterfaceType,
28
+ isNonNullType,
29
+ isObjectType,
34
30
  } from '../../type/definition';
35
31
 
36
32
  import { typeFromAST } from '../../utilities/typeFromAST';
37
33
 
34
+ import { validationAbortedError } from '../validationAbortedError';
38
35
  import type { ValidationContext } from '../ValidationContext';
39
36
 
40
- function reasonMessage(reason: ConflictReasonMessage): string {
41
- if (Array.isArray(reason)) {
42
- return reason
43
- .map(
44
- ([responseName, subReason]) =>
45
- `subfields "${responseName}" conflict because ` +
46
- reasonMessage(subReason),
47
- )
48
- .join(' and ');
49
- }
50
- return reason;
51
- }
37
+ // Keep diagnostic detail bounded independently of document size.
38
+ const MAX_CONFLICT_DETAIL_LENGTH = 1000;
39
+ const MAX_CONFLICT_NODES = 20;
40
+ // v15 has no default validation error limit. Bound this rule's reporting locally.
41
+ const MAX_REPORTED_CONFLICTS = 100;
42
+
43
+ // Meter work that can grow through repeated comparisons.
44
+ // Collecting a selection set's fields is cached and is not charged.
45
+ const MAX_COMPLEXITY_BUDGET = 500_000;
52
46
 
53
47
  /**
54
48
  * Overlapping fields can be merged
@@ -58,32 +52,53 @@ function reasonMessage(reason: ConflictReasonMessage): string {
58
52
  * without ambiguity.
59
53
  */
60
54
  export function OverlappingFieldsCanBeMergedRule(
61
- context: ValidationContext,
55
+ validationContext: ValidationContext,
62
56
  ): ASTVisitor {
63
- // A memoization for when two fragments are compared "between" each other for
64
- // conflicts. Two fragments may be compared many times, so memoizing this can
65
- // dramatically improve the performance of this validator.
66
- const comparedFragmentPairs = new PairSet();
57
+ const ruleContext: RuleContext = {
58
+ // A memoization for when two fragments are compared for conflicts.
59
+ // Comparisons may be made many times, so memoizing this can dramatically
60
+ // improve the performance of this validator.
61
+ comparedFragmentPairs: new PairSet(),
62
+
63
+ // A cache for the "field map" and list of fragment names found in any given
64
+ // selection set.
65
+ cachedCollectFieldsResults: new Map(),
66
+ stringifiedValues: new Map(),
67
+ remainingComplexityBudget: MAX_COMPLEXITY_BUDGET,
68
+ };
67
69
 
68
- // A cache for the "field map" and list of fragment names found in any given
69
- // selection set. Selection sets may be asked for this information multiple
70
- // times, so this improves the performance of this validator.
71
- const cachedFieldsAndFragmentNames = new Map();
70
+ let reportedConflicts = 0;
72
71
 
73
72
  return {
74
- SelectionSet(selectionSet) {
73
+ SelectionSet(selectionSet, _key, parent) {
74
+ // Inline fragments are flattened into their enclosing response level.
75
+ // Their fields' own selection sets are still visited independently.
76
+ if (parent && 'kind' in parent && parent.kind === Kind.INLINE_FRAGMENT) {
77
+ return;
78
+ }
79
+ if (
80
+ selectionSet.selections.length === 0 ||
81
+ (selectionSet.selections.length === 1 &&
82
+ selectionSet.selections[0].kind !== Kind.INLINE_FRAGMENT)
83
+ ) {
84
+ return;
85
+ }
75
86
  const conflicts = findConflictsWithinSelectionSet(
76
- context,
77
- cachedFieldsAndFragmentNames,
78
- comparedFragmentPairs,
79
- context.getParentType(),
87
+ validationContext,
88
+ ruleContext,
89
+ validationContext.getParentType(),
80
90
  selectionSet,
81
91
  );
82
- for (const [[responseName, reason], fields1, fields2] of conflicts) {
83
- const reasonMsg = reasonMessage(reason);
84
- context.reportError(
92
+ for (const { responseName, reason, fields1, fields2 } of conflicts) {
93
+ if (reportedConflicts >= MAX_REPORTED_CONFLICTS) {
94
+ throw validationAbortedError;
95
+ }
96
+ reportedConflicts++;
97
+ validationContext.reportError(
85
98
  new GraphQLError(
86
- `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`,
99
+ `Fields "${maybeAbbreviate(
100
+ responseName,
101
+ )}" conflict because ${reason}. Use different aliases on the fields to fetch both if this was intentional.`,
87
102
  fields1.concat(fields2),
88
103
  ),
89
104
  );
@@ -92,21 +107,62 @@ export function OverlappingFieldsCanBeMergedRule(
92
107
  };
93
108
  }
94
109
 
95
- type Conflict = [ConflictReason, Array<FieldNode>, Array<FieldNode>];
96
- // Field name and reason.
97
- type ConflictReason = [string, ConflictReasonMessage];
98
- // Reason is a string, or a nested list of conflicts.
99
- type ConflictReasonMessage = string | Array<ConflictReason>;
100
- // Tuple defining a field node in a context.
101
- type NodeAndDef = [
102
- GraphQLCompositeType,
103
- FieldNode,
104
- ?GraphQLField<mixed, mixed>,
105
- ];
110
+ interface Conflict {
111
+ responseName: string;
112
+ reason: string;
113
+ fields1: Array<FieldNode>;
114
+ fields2: Array<FieldNode>;
115
+ }
116
+ // A field node and its definition in the parent-type context.
117
+ interface FieldDetails {
118
+ parentType: ?GraphQLNamedType;
119
+ node: FieldNode;
120
+ definition: ?GraphQLField<mixed, mixed>;
121
+ info?: FieldInfo;
122
+ isSimpleLeaf: boolean;
123
+ }
124
+ interface FieldInfo {
125
+ typeString?: string;
126
+ namedType: ?GraphQLNamedType;
127
+ // A null reason means the field names and arguments match.
128
+ comparisons: Map<FieldInfo, string | null>;
129
+ arguments: ArgumentInfo | void;
130
+ }
131
+ interface ArgumentInfo {
132
+ nodes: $ReadOnlyArray<ArgumentNode>;
133
+ values: Map<string, ValueNode>;
134
+ }
106
135
  // Map of array of those.
107
- type NodeAndDefCollection = ObjMap<Array<NodeAndDef>>;
136
+ type FieldDetailsList = Array<FieldDetails>;
137
+ type GroupedFieldSet = ObjMap<FieldDetailsList>;
138
+ type FragmentNames = Array<string>;
139
+ interface CollectFieldsResult {
140
+ groupedFieldSet: GroupedFieldSet;
141
+ responseNames: Array<string>;
142
+ fragmentNames: FragmentNames;
143
+ comparedFragments?: Map<string, boolean>;
144
+ overlappingFields?: Map<CollectFieldsResult, Array<OverlappingFields>>;
145
+ }
146
+ interface OverlappingFields {
147
+ responseName: string;
148
+ fields1: FieldDetailsList;
149
+ fields2: FieldDetailsList;
150
+ }
151
+ interface RuleContext {
152
+ remainingComplexityBudget: number;
153
+ stringifiedValues: Map<ValueNode, string>;
154
+ comparedFragmentPairs: PairSet;
155
+ cachedCollectFieldsResults: Map<
156
+ ?GraphQLNamedType,
157
+ Map<SelectionSetNode, CollectFieldsResult>,
158
+ >;
159
+ }
108
160
 
109
161
  /**
162
+ * Find all conflicts found "within" a selection set, including those found
163
+ * via spreading in fragments. Called when visiting each SelectionSet in the
164
+ * GraphQL Document.
165
+ *
110
166
  * Algorithm:
111
167
  *
112
168
  * Conflicts occur when two fields exist in a query which will produce the same
@@ -122,7 +178,7 @@ type NodeAndDefCollection = ObjMap<Array<NodeAndDef>>;
122
178
  * A) Each selection set represented in the document first compares "within" its
123
179
  * collected set of fields, finding any conflicts between every pair of
124
180
  * overlapping fields.
125
- * Note: This is the *only time* that a the fields "within" a set are compared
181
+ * Note: This is the *only time* that the fields "within" a set are compared
126
182
  * to each other. After this only fields "between" sets are compared.
127
183
  *
128
184
  * B) Also, if any fragment is referenced in a selection set, then a
@@ -134,14 +190,14 @@ type NodeAndDefCollection = ObjMap<Array<NodeAndDef>>;
134
190
  *
135
191
  * D) When comparing "between" a set of fields and a referenced fragment, first
136
192
  * a comparison is made between each field in the original set of fields and
137
- * each field in the the referenced set of fields.
193
+ * each field in the referenced set of fields.
138
194
  *
139
195
  * E) Also, if any fragment is referenced in the referenced selection set,
140
196
  * then a comparison is made "between" the original set of fields and the
141
197
  * referenced fragment (recursively referring to step D).
142
198
  *
143
199
  * F) When comparing "between" two fragments, first a comparison is made between
144
- * each field in the first referenced set of fields and each field in the the
200
+ * each field in the first referenced set of fields and each field in the
145
201
  * second referenced set of fields.
146
202
  *
147
203
  * G) Also, any fragments referenced by the first must be compared to the
@@ -158,24 +214,18 @@ type NodeAndDefCollection = ObjMap<Array<NodeAndDef>>;
158
214
  *
159
215
  * J) Also, if two fragments are referenced in both selection sets, then a
160
216
  * comparison is made "between" the two fragments.
161
- *
162
217
  */
163
-
164
- // Find all conflicts found "within" a selection set, including those found
165
- // via spreading in fragments. Called when visiting each SelectionSet in the
166
- // GraphQL Document.
167
218
  function findConflictsWithinSelectionSet(
168
- context: ValidationContext,
169
- cachedFieldsAndFragmentNames,
170
- comparedFragmentPairs: PairSet,
219
+ validationContext: ValidationContext,
220
+ ruleContext: RuleContext,
171
221
  parentType: ?GraphQLNamedType,
172
222
  selectionSet: SelectionSetNode,
173
223
  ): Array<Conflict> {
174
- const conflicts = [];
224
+ const conflicts: Array<Conflict> = [];
175
225
 
176
- const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(
177
- context,
178
- cachedFieldsAndFragmentNames,
226
+ const collectFieldsResult = collectFields(
227
+ validationContext,
228
+ ruleContext,
179
229
  parentType,
180
230
  selectionSet,
181
231
  );
@@ -183,39 +233,41 @@ function findConflictsWithinSelectionSet(
183
233
  // (A) Find find all conflicts "within" the fields of this selection set.
184
234
  // Note: this is the *only place* `collectConflictsWithin` is called.
185
235
  collectConflictsWithin(
186
- context,
236
+ validationContext,
187
237
  conflicts,
188
- cachedFieldsAndFragmentNames,
189
- comparedFragmentPairs,
190
- fieldMap,
238
+ ruleContext,
239
+ collectFieldsResult,
191
240
  );
192
241
 
193
- if (fragmentNames.length !== 0) {
242
+ // Compare fragment uses only with fields or another spread.
243
+ if (
244
+ collectFieldsResult.fragmentNames.length !== 0 &&
245
+ (collectFieldsResult.responseNames.length !== 0 ||
246
+ collectFieldsResult.fragmentNames.length > 1)
247
+ ) {
194
248
  // (B) Then collect conflicts between these fields and those represented by
195
249
  // each spread fragment name found.
196
- for (let i = 0; i < fragmentNames.length; i++) {
250
+ for (let i = 0; i < collectFieldsResult.fragmentNames.length; i++) {
197
251
  collectConflictsBetweenFieldsAndFragment(
198
- context,
252
+ validationContext,
199
253
  conflicts,
200
- cachedFieldsAndFragmentNames,
201
- comparedFragmentPairs,
254
+ ruleContext,
202
255
  false,
203
- fieldMap,
204
- fragmentNames[i],
256
+ collectFieldsResult,
257
+ collectFieldsResult.fragmentNames[i],
205
258
  );
206
259
  // (C) Then compare this fragment with all other fragments found in this
207
260
  // selection set to collect conflicts between fragments spread together.
208
261
  // This compares each item in the list of fragment names to every other
209
262
  // item in that same list (except for itself).
210
- for (let j = i + 1; j < fragmentNames.length; j++) {
263
+ for (let j = i + 1; j < collectFieldsResult.fragmentNames.length; j++) {
211
264
  collectConflictsBetweenFragments(
212
- context,
265
+ validationContext,
213
266
  conflicts,
214
- cachedFieldsAndFragmentNames,
215
- comparedFragmentPairs,
267
+ ruleContext,
216
268
  false,
217
- fragmentNames[i],
218
- fragmentNames[j],
269
+ collectFieldsResult.fragmentNames[i],
270
+ collectFieldsResult.fragmentNames[j],
219
271
  );
220
272
  }
221
273
  }
@@ -226,71 +278,72 @@ function findConflictsWithinSelectionSet(
226
278
  // Collect all conflicts found between a set of fields and a fragment reference
227
279
  // including via spreading in any nested fragments.
228
280
  function collectConflictsBetweenFieldsAndFragment(
229
- context: ValidationContext,
281
+ validationContext: ValidationContext,
230
282
  conflicts: Array<Conflict>,
231
- cachedFieldsAndFragmentNames,
232
- comparedFragmentPairs: PairSet,
283
+ ruleContext: RuleContext,
233
284
  areMutuallyExclusive: boolean,
234
- fieldMap: NodeAndDefCollection,
285
+ collectFieldsResult: CollectFieldsResult,
235
286
  fragmentName: string,
236
287
  ): void {
237
- const fragment = context.getFragment(fragmentName);
288
+ // Callers can enumerate more field-map/fragment pairs than document nodes.
289
+ // Count attempts even when an empty collection or the pair cache skips them.
290
+ spendComplexityBudget(ruleContext, 1);
291
+
292
+ if (collectFieldsResult.responseNames.length === 0) {
293
+ return;
294
+ }
295
+
296
+ const comparedFragments =
297
+ collectFieldsResult.comparedFragments ??
298
+ (collectFieldsResult.comparedFragments = new Map());
299
+ // Memoize so the fields and fragments are not compared for conflicts more
300
+ // than once.
301
+ const compared = comparedFragments.get(fragmentName);
302
+ // Only a non-exclusive comparison can be reused for overlapping parents.
303
+ if (compared === false || (areMutuallyExclusive && compared === true)) {
304
+ return;
305
+ }
306
+ comparedFragments.set(fragmentName, areMutuallyExclusive);
307
+
308
+ const fragment = validationContext.getFragment(fragmentName);
238
309
  if (!fragment) {
239
310
  return;
240
311
  }
241
312
 
242
- const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames(
243
- context,
244
- cachedFieldsAndFragmentNames,
313
+ const collectFieldsResult2 = collectFragmentFields(
314
+ validationContext,
315
+ ruleContext,
245
316
  fragment,
246
317
  );
247
318
 
248
- // Do not compare a fragment's fieldMap to itself.
249
- if (fieldMap === fieldMap2) {
319
+ // Do not compare a fragment's collectFieldsResult to itself.
320
+ if (collectFieldsResult === collectFieldsResult2) {
250
321
  return;
251
322
  }
252
323
 
253
324
  // (D) First collect any conflicts between the provided collection of fields
254
325
  // and the collection of fields represented by the given fragment.
255
326
  collectConflictsBetween(
256
- context,
327
+ validationContext,
257
328
  conflicts,
258
- cachedFieldsAndFragmentNames,
259
- comparedFragmentPairs,
329
+ ruleContext,
260
330
  areMutuallyExclusive,
261
- fieldMap,
262
- fieldMap2,
331
+ collectFieldsResult,
332
+ collectFieldsResult2,
263
333
  );
264
334
 
265
335
  // (E) Then collect any conflicts between the provided collection of fields
266
336
  // and any fragment names found in the given fragment.
267
- for (let i = 0; i < fragmentNames2.length; i++) {
268
- const referencedFragmentName = fragmentNames2[i];
269
-
270
- // Memoize so two fragments are not compared for conflicts more than once.
271
- if (
272
- comparedFragmentPairs.has(
273
- referencedFragmentName,
274
- fragmentName,
275
- areMutuallyExclusive,
276
- )
277
- ) {
278
- continue;
279
- }
280
- comparedFragmentPairs.add(
281
- referencedFragmentName,
282
- fragmentName,
283
- areMutuallyExclusive,
284
- );
337
+ for (let i = 0; i < collectFieldsResult2.fragmentNames.length; i++) {
338
+ const referencedFragmentName = collectFieldsResult2.fragmentNames[i];
285
339
 
286
340
  collectConflictsBetweenFieldsAndFragment(
287
- context,
341
+ validationContext,
288
342
  conflicts,
289
- cachedFieldsAndFragmentNames,
290
- comparedFragmentPairs,
343
+ ruleContext,
291
344
  areMutuallyExclusive,
292
- fieldMap,
293
- fragmentNames2[i],
345
+ collectFieldsResult,
346
+ referencedFragmentName,
294
347
  );
295
348
  }
296
349
  }
@@ -298,14 +351,17 @@ function collectConflictsBetweenFieldsAndFragment(
298
351
  // Collect all conflicts found between two fragments, including via spreading in
299
352
  // any nested fragments.
300
353
  function collectConflictsBetweenFragments(
301
- context: ValidationContext,
354
+ validationContext: ValidationContext,
302
355
  conflicts: Array<Conflict>,
303
- cachedFieldsAndFragmentNames,
304
- comparedFragmentPairs: PairSet,
356
+ ruleContext: RuleContext,
305
357
  areMutuallyExclusive: boolean,
306
358
  fragmentName1: string,
307
359
  fragmentName2: string,
308
360
  ): void {
361
+ // Count attempted fragment pairs, including identity and cache hits.
362
+ spendComplexityBudget(ruleContext, 2);
363
+
364
+ const { comparedFragmentPairs } = ruleContext;
309
365
  // No need to compare a fragment to itself.
310
366
  if (fragmentName1 === fragmentName2) {
311
367
  return;
@@ -323,59 +379,56 @@ function collectConflictsBetweenFragments(
323
379
  }
324
380
  comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);
325
381
 
326
- const fragment1 = context.getFragment(fragmentName1);
327
- const fragment2 = context.getFragment(fragmentName2);
382
+ const fragment1 = validationContext.getFragment(fragmentName1);
383
+ const fragment2 = validationContext.getFragment(fragmentName2);
328
384
  if (!fragment1 || !fragment2) {
329
385
  return;
330
386
  }
331
387
 
332
- const [fieldMap1, fragmentNames1] = getReferencedFieldsAndFragmentNames(
333
- context,
334
- cachedFieldsAndFragmentNames,
388
+ const collectFieldsResult1 = collectFragmentFields(
389
+ validationContext,
390
+ ruleContext,
335
391
  fragment1,
336
392
  );
337
- const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames(
338
- context,
339
- cachedFieldsAndFragmentNames,
393
+ const collectFieldsResult2 = collectFragmentFields(
394
+ validationContext,
395
+ ruleContext,
340
396
  fragment2,
341
397
  );
342
398
 
343
399
  // (F) First, collect all conflicts between these two collections of fields
344
400
  // (not including any nested fragments).
345
401
  collectConflictsBetween(
346
- context,
402
+ validationContext,
347
403
  conflicts,
348
- cachedFieldsAndFragmentNames,
349
- comparedFragmentPairs,
404
+ ruleContext,
350
405
  areMutuallyExclusive,
351
- fieldMap1,
352
- fieldMap2,
406
+ collectFieldsResult1,
407
+ collectFieldsResult2,
353
408
  );
354
409
 
355
410
  // (G) Then collect conflicts between the first fragment and any nested
356
411
  // fragments spread in the second fragment.
357
- for (let j = 0; j < fragmentNames2.length; j++) {
412
+ for (let j = 0; j < collectFieldsResult2.fragmentNames.length; j++) {
358
413
  collectConflictsBetweenFragments(
359
- context,
414
+ validationContext,
360
415
  conflicts,
361
- cachedFieldsAndFragmentNames,
362
- comparedFragmentPairs,
416
+ ruleContext,
363
417
  areMutuallyExclusive,
364
418
  fragmentName1,
365
- fragmentNames2[j],
419
+ collectFieldsResult2.fragmentNames[j],
366
420
  );
367
421
  }
368
422
 
369
423
  // (G) Then collect conflicts between the second fragment and any nested
370
424
  // fragments spread in the first fragment.
371
- for (let i = 0; i < fragmentNames1.length; i++) {
425
+ for (let i = 0; i < collectFieldsResult1.fragmentNames.length; i++) {
372
426
  collectConflictsBetweenFragments(
373
- context,
427
+ validationContext,
374
428
  conflicts,
375
- cachedFieldsAndFragmentNames,
376
- comparedFragmentPairs,
429
+ ruleContext,
377
430
  areMutuallyExclusive,
378
- fragmentNames1[i],
431
+ collectFieldsResult1.fragmentNames[i],
379
432
  fragmentName2,
380
433
  );
381
434
  }
@@ -385,69 +438,65 @@ function collectConflictsBetweenFragments(
385
438
  // via spreading in fragments. Called when determining if conflicts exist
386
439
  // between the sub-fields of two overlapping fields.
387
440
  function findConflictsBetweenSubSelectionSets(
388
- context: ValidationContext,
389
- cachedFieldsAndFragmentNames,
390
- comparedFragmentPairs: PairSet,
441
+ validationContext: ValidationContext,
442
+ ruleContext: RuleContext,
391
443
  areMutuallyExclusive: boolean,
392
444
  parentType1: ?GraphQLNamedType,
393
445
  selectionSet1: SelectionSetNode,
394
446
  parentType2: ?GraphQLNamedType,
395
447
  selectionSet2: SelectionSetNode,
396
448
  ): Array<Conflict> {
397
- const conflicts = [];
449
+ const conflicts: Array<Conflict> = [];
398
450
 
399
- const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(
400
- context,
401
- cachedFieldsAndFragmentNames,
451
+ const collectFieldsResult1 = collectFields(
452
+ validationContext,
453
+ ruleContext,
402
454
  parentType1,
403
455
  selectionSet1,
404
456
  );
405
- const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(
406
- context,
407
- cachedFieldsAndFragmentNames,
457
+ const collectFieldsResult2 = collectFields(
458
+ validationContext,
459
+ ruleContext,
408
460
  parentType2,
409
461
  selectionSet2,
410
462
  );
411
463
 
412
464
  // (H) First, collect all conflicts between these two collections of field.
413
465
  collectConflictsBetween(
414
- context,
466
+ validationContext,
415
467
  conflicts,
416
- cachedFieldsAndFragmentNames,
417
- comparedFragmentPairs,
468
+ ruleContext,
418
469
  areMutuallyExclusive,
419
- fieldMap1,
420
- fieldMap2,
470
+ collectFieldsResult1,
471
+ collectFieldsResult2,
421
472
  );
422
473
 
423
474
  // (I) Then collect conflicts between the first collection of fields and
424
475
  // those referenced by each fragment name associated with the second.
425
- if (fragmentNames2.length !== 0) {
426
- for (let j = 0; j < fragmentNames2.length; j++) {
476
+ if (collectFieldsResult2.fragmentNames.length !== 0) {
477
+ for (let j = 0; j < collectFieldsResult2.fragmentNames.length; j++) {
427
478
  collectConflictsBetweenFieldsAndFragment(
428
- context,
479
+ validationContext,
429
480
  conflicts,
430
- cachedFieldsAndFragmentNames,
431
- comparedFragmentPairs,
481
+ ruleContext,
432
482
  areMutuallyExclusive,
433
- fieldMap1,
434
- fragmentNames2[j],
483
+ collectFieldsResult1,
484
+ collectFieldsResult2.fragmentNames[j],
435
485
  );
436
486
  }
437
487
  }
438
488
 
439
489
  // (I) Then collect conflicts between the second collection of fields and
440
490
  // those referenced by each fragment name associated with the first.
441
- if (fragmentNames1.length !== 0) {
442
- for (let i = 0; i < fragmentNames1.length; i++) {
491
+ if (collectFieldsResult1.fragmentNames.length !== 0) {
492
+ for (let i = 0; i < collectFieldsResult1.fragmentNames.length; i++) {
443
493
  collectConflictsBetweenFieldsAndFragment(
444
- context,
494
+ validationContext,
445
495
  conflicts,
446
- cachedFieldsAndFragmentNames,
447
- comparedFragmentPairs,
496
+ ruleContext,
448
497
  areMutuallyExclusive,
449
- fieldMap2,
450
- fragmentNames1[i],
498
+ collectFieldsResult2,
499
+ collectFieldsResult1.fragmentNames[i],
451
500
  );
452
501
  }
453
502
  }
@@ -455,16 +504,15 @@ function findConflictsBetweenSubSelectionSets(
455
504
  // (J) Also collect conflicts between any fragment names by the first and
456
505
  // fragment names by the second. This compares each item in the first set of
457
506
  // names to each item in the second set of names.
458
- for (let i = 0; i < fragmentNames1.length; i++) {
459
- for (let j = 0; j < fragmentNames2.length; j++) {
507
+ for (let i = 0; i < collectFieldsResult1.fragmentNames.length; i++) {
508
+ for (let j = 0; j < collectFieldsResult2.fragmentNames.length; j++) {
460
509
  collectConflictsBetweenFragments(
461
- context,
510
+ validationContext,
462
511
  conflicts,
463
- cachedFieldsAndFragmentNames,
464
- comparedFragmentPairs,
512
+ ruleContext,
465
513
  areMutuallyExclusive,
466
- fragmentNames1[i],
467
- fragmentNames2[j],
514
+ collectFieldsResult1.fragmentNames[i],
515
+ collectFieldsResult2.fragmentNames[j],
468
516
  );
469
517
  }
470
518
  }
@@ -473,17 +521,17 @@ function findConflictsBetweenSubSelectionSets(
473
521
 
474
522
  // Collect all Conflicts "within" one collection of fields.
475
523
  function collectConflictsWithin(
476
- context: ValidationContext,
524
+ validationContext: ValidationContext,
477
525
  conflicts: Array<Conflict>,
478
- cachedFieldsAndFragmentNames,
479
- comparedFragmentPairs: PairSet,
480
- fieldMap: NodeAndDefCollection,
526
+ ruleContext: RuleContext,
527
+ collectFieldsResult: CollectFieldsResult,
481
528
  ): void {
482
529
  // A field map is a keyed collection, where each key represents a response
483
530
  // name and the value at that key is a list of all fields which provide that
484
531
  // response name. For every response name, if there are multiple fields, they
485
532
  // must be compared to find a potential conflict.
486
- for (const [responseName, fields] of objectEntries(fieldMap)) {
533
+ for (const responseName of collectFieldsResult.responseNames) {
534
+ const fields = collectFieldsResult.groupedFieldSet[responseName];
487
535
  // This compares every field in the list to every other field in this list
488
536
  // (except to itself). If the list only has one item, nothing needs to
489
537
  // be compared.
@@ -491,10 +539,9 @@ function collectConflictsWithin(
491
539
  for (let i = 0; i < fields.length; i++) {
492
540
  for (let j = i + 1; j < fields.length; j++) {
493
541
  const conflict = findConflict(
494
- context,
495
- cachedFieldsAndFragmentNames,
496
- comparedFragmentPairs,
497
- false, // within one collection is never mutually exclusive
542
+ validationContext,
543
+ ruleContext,
544
+ false,
498
545
  responseName,
499
546
  fields[i],
500
547
  fields[j],
@@ -514,56 +561,95 @@ function collectConflictsWithin(
514
561
  // provided collection of fields. This is true because this validator traverses
515
562
  // each individual selection set.
516
563
  function collectConflictsBetween(
517
- context: ValidationContext,
564
+ validationContext: ValidationContext,
518
565
  conflicts: Array<Conflict>,
519
- cachedFieldsAndFragmentNames,
520
- comparedFragmentPairs: PairSet,
566
+ ruleContext: RuleContext,
521
567
  parentFieldsAreMutuallyExclusive: boolean,
522
- fieldMap1: NodeAndDefCollection,
523
- fieldMap2: NodeAndDefCollection,
568
+ collectFieldsResult1: CollectFieldsResult,
569
+ collectFieldsResult2: CollectFieldsResult,
524
570
  ): void {
571
+ if (
572
+ collectFieldsResult1.responseNames.length === 0 ||
573
+ collectFieldsResult2.responseNames.length === 0
574
+ ) {
575
+ return;
576
+ }
577
+
525
578
  // A field map is a keyed collection, where each key represents a response
526
579
  // name and the value at that key is a list of all fields which provide that
527
580
  // response name. For any response name which appears in both provided field
528
581
  // maps, each field from the first field map must be compared to every field
529
582
  // in the second field map to find potential conflicts.
530
- for (const responseName of Object.keys(fieldMap1)) {
531
- const fields2 = fieldMap2[responseName];
532
- if (fields2) {
533
- const fields1 = fieldMap1[responseName];
534
- for (let i = 0; i < fields1.length; i++) {
535
- for (let j = 0; j < fields2.length; j++) {
536
- const conflict = findConflict(
537
- context,
538
- cachedFieldsAndFragmentNames,
539
- comparedFragmentPairs,
540
- parentFieldsAreMutuallyExclusive,
541
- responseName,
542
- fields1[i],
543
- fields2[j],
544
- );
545
- if (conflict) {
546
- conflicts.push(conflict);
547
- }
583
+ for (const { responseName, fields1, fields2 } of getOverlappingFields(
584
+ ruleContext,
585
+ collectFieldsResult1,
586
+ collectFieldsResult2,
587
+ )) {
588
+ for (let i = 0; i < fields1.length; i++) {
589
+ for (let j = 0; j < fields2.length; j++) {
590
+ const conflict = findConflict(
591
+ validationContext,
592
+ ruleContext,
593
+ parentFieldsAreMutuallyExclusive,
594
+ responseName,
595
+ fields1[i],
596
+ fields2[j],
597
+ );
598
+ if (conflict) {
599
+ conflicts.push(conflict);
548
600
  }
549
601
  }
550
602
  }
551
603
  }
552
604
  }
553
605
 
606
+ function getOverlappingFields(
607
+ ruleContext: RuleContext,
608
+ collectFieldsResult1: CollectFieldsResult,
609
+ collectFieldsResult2: CollectFieldsResult,
610
+ ): Array<OverlappingFields> {
611
+ // Reuse matching response groups when these collections are compared again.
612
+ const byCollectFieldsResult =
613
+ collectFieldsResult1.overlappingFields ??
614
+ (collectFieldsResult1.overlappingFields = new Map());
615
+ const cached = byCollectFieldsResult.get(collectFieldsResult2);
616
+ if (cached !== undefined) {
617
+ return cached;
618
+ }
619
+ const overlappingFields: Array<OverlappingFields> = [];
620
+ for (const responseName of collectFieldsResult1.responseNames) {
621
+ // A field map can participate in many distinct comparisons.
622
+ spendComplexityBudget(ruleContext, 1);
623
+ const fields2 = collectFieldsResult2.groupedFieldSet[responseName];
624
+ if (fields2 !== undefined) {
625
+ const fields1 = collectFieldsResult1.groupedFieldSet[responseName];
626
+ overlappingFields.push({ responseName, fields1, fields2 });
627
+ }
628
+ }
629
+ byCollectFieldsResult.set(collectFieldsResult2, overlappingFields);
630
+ return overlappingFields;
631
+ }
632
+
554
633
  // Determines if there is a conflict between two particular fields, including
555
634
  // comparing their sub-fields.
556
635
  function findConflict(
557
- context: ValidationContext,
558
- cachedFieldsAndFragmentNames,
559
- comparedFragmentPairs: PairSet,
636
+ validationContext: ValidationContext,
637
+ ruleContext: RuleContext,
560
638
  parentFieldsAreMutuallyExclusive: boolean,
561
639
  responseName: string,
562
- field1: NodeAndDef,
563
- field2: NodeAndDef,
640
+ fieldDetails1: FieldDetails,
641
+ fieldDetails2: FieldDetails,
564
642
  ): ?Conflict {
565
- const [parentType1, node1, def1] = field1;
566
- const [parentType2, node2, def2] = field2;
643
+ const {
644
+ parentType: parentType1,
645
+ node: node1,
646
+ definition: def1,
647
+ } = fieldDetails1;
648
+ const {
649
+ parentType: parentType2,
650
+ node: node2,
651
+ definition: def2,
652
+ } = fieldDetails2;
567
653
 
568
654
  // If it is known that two fields could not possibly apply at the same
569
655
  // time, due to the parent types, then it is safe to permit them to diverge
@@ -579,29 +665,45 @@ function findConflict(
579
665
  isObjectType(parentType1) &&
580
666
  isObjectType(parentType2));
581
667
 
668
+ // Count attempted field pairs, including pairs skipped by type exclusivity.
669
+ spendComplexityBudget(ruleContext, 2);
670
+ if (
671
+ fieldDetails1.isSimpleLeaf &&
672
+ fieldDetails2.isSimpleLeaf &&
673
+ def1?.type === def2?.type &&
674
+ node1.name.value === node2.name.value
675
+ ) {
676
+ return;
677
+ }
582
678
  if (!areMutuallyExclusive) {
583
- // Two aliases must refer to the same field.
584
- const name1 = node1.name.value;
585
- const name2 = node2.name.value;
586
- if (name1 !== name2) {
587
- return [
588
- [responseName, `"${name1}" and "${name2}" are different fields`],
589
- [node1],
590
- [node2],
591
- ];
679
+ const fieldInfo1 = getFieldInfo(fieldDetails1);
680
+ const fieldInfo2 = getFieldInfo(fieldDetails2);
681
+ let reason = fieldInfo1.comparisons.get(fieldInfo2);
682
+ if (reason === undefined) {
683
+ // Two aliases must refer to the same field with the same arguments.
684
+ const name1 = node1.name.value;
685
+ const name2 = node2.name.value;
686
+ reason =
687
+ name1 !== name2
688
+ ? `"${maybeAbbreviate(name1)}" and "${maybeAbbreviate(
689
+ name2,
690
+ )}" are different fields`
691
+ : sameArguments(
692
+ ruleContext,
693
+ fieldInfo1.arguments,
694
+ fieldInfo2.arguments,
695
+ )
696
+ ? null
697
+ : 'they have differing arguments';
698
+ fieldInfo1.comparisons.set(fieldInfo2, reason);
592
699
  }
593
-
594
- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
595
- const args1 = node1.arguments ?? [];
596
- // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
597
- const args2 = node2.arguments ?? [];
598
- // Two field calls must have the same arguments.
599
- if (!sameArguments(args1, args2)) {
600
- return [
601
- [responseName, 'they have differing arguments'],
602
- [node1],
603
- [node2],
604
- ];
700
+ if (reason !== null) {
701
+ return {
702
+ responseName,
703
+ reason,
704
+ fields1: [node1],
705
+ fields2: [node2],
706
+ };
605
707
  }
606
708
  }
607
709
 
@@ -609,17 +711,19 @@ function findConflict(
609
711
  const type1 = def1?.type;
610
712
  const type2 = def2?.type;
611
713
 
612
- if (type1 && type2 && doTypesConflict(type1, type2)) {
613
- return [
614
- [
615
- responseName,
616
- `they return conflicting types "${inspect(type1)}" and "${inspect(
617
- type2,
618
- )}"`,
619
- ],
620
- [node1],
621
- [node2],
622
- ];
714
+ if (type1 && type2 && doTypesConflict(ruleContext, type1, type2)) {
715
+ const fieldInfo1 = getFieldInfo(fieldDetails1);
716
+ const fieldInfo2 = getFieldInfo(fieldDetails2);
717
+ const type1String =
718
+ fieldInfo1.typeString ?? (fieldInfo1.typeString = inspect(type1));
719
+ const type2String =
720
+ fieldInfo2.typeString ?? (fieldInfo2.typeString = inspect(type2));
721
+ return {
722
+ responseName,
723
+ reason: `they return conflicting types "${type1String}" and "${type2String}"`,
724
+ fields1: [node1],
725
+ fields2: [node2],
726
+ };
623
727
  }
624
728
 
625
729
  // Collect and compare sub-fields. Use the same "visited fragment names" list
@@ -629,52 +733,126 @@ function findConflict(
629
733
  const selectionSet2 = node2.selectionSet;
630
734
  if (selectionSet1 && selectionSet2) {
631
735
  const conflicts = findConflictsBetweenSubSelectionSets(
632
- context,
633
- cachedFieldsAndFragmentNames,
634
- comparedFragmentPairs,
736
+ validationContext,
737
+ ruleContext,
635
738
  areMutuallyExclusive,
636
- getNamedType(type1),
739
+ getFieldInfo(fieldDetails1).namedType,
637
740
  selectionSet1,
638
- getNamedType(type2),
741
+ getFieldInfo(fieldDetails2).namedType,
639
742
  selectionSet2,
640
743
  );
641
744
  return subfieldConflicts(conflicts, responseName, node1, node2);
642
745
  }
643
746
  }
644
747
 
748
+ // Prepare argument lookups only when a field overlaps.
749
+ function getFieldInfo(fieldDetails: FieldDetails): FieldInfo {
750
+ if (fieldDetails.info === undefined) {
751
+ fieldDetails.info = {
752
+ comparisons: new Map(),
753
+ namedType: getNamedType(fieldDetails.definition?.type),
754
+ arguments: getArgumentInfo(fieldDetails.node.arguments),
755
+ };
756
+ }
757
+ return fieldDetails.info;
758
+ }
759
+
760
+ function getArgumentInfo(
761
+ args: $ReadOnlyArray<ArgumentNode> | void,
762
+ ): ArgumentInfo | void {
763
+ if (args === undefined || args.length === 0) {
764
+ return;
765
+ }
766
+ const values: Map<string, ValueNode> = new Map();
767
+ for (const { name, value } of args) {
768
+ values.set(name.value, value);
769
+ }
770
+ return { nodes: args, values };
771
+ }
772
+
645
773
  function sameArguments(
646
- arguments1: $ReadOnlyArray<ArgumentNode>,
647
- arguments2: $ReadOnlyArray<ArgumentNode>,
774
+ ruleContext: RuleContext,
775
+ argumentInfo1: ArgumentInfo | void,
776
+ argumentInfo2: ArgumentInfo | void,
648
777
  ): boolean {
649
- if (arguments1.length !== arguments2.length) {
778
+ if (argumentInfo1 === undefined) {
779
+ return argumentInfo2 === undefined;
780
+ }
781
+ if (
782
+ argumentInfo2 === undefined ||
783
+ argumentInfo1.nodes.length !== argumentInfo2.nodes.length
784
+ ) {
650
785
  return false;
651
786
  }
652
- return arguments1.every((argument1) => {
653
- const argument2 = find(
654
- arguments2,
655
- (argument) => argument.name.value === argument1.name.value,
656
- );
657
- if (!argument2) {
787
+ const values2 = argumentInfo2.values;
788
+ return argumentInfo1.nodes.every((arg1) => {
789
+ // A prepared argument list can participate in many field-pair comparisons.
790
+ spendComplexityBudget(ruleContext, 1);
791
+ const value2 = values2.get(arg1.name.value);
792
+ if (value2 === undefined) {
658
793
  return false;
659
794
  }
660
- return sameValue(argument1.value, argument2.value);
795
+ return (
796
+ stringifyValue(ruleContext, arg1.value) ===
797
+ stringifyValue(ruleContext, value2)
798
+ );
661
799
  });
662
800
  }
663
801
 
664
- function sameValue(value1: ValueNode, value2: ValueNode): boolean {
665
- return print(value1) === print(value2);
802
+ function stringifyValue(ruleContext: RuleContext, value: ValueNode): string {
803
+ const cached = ruleContext.stringifiedValues.get(value);
804
+ if (cached !== undefined) {
805
+ return cached;
806
+ }
807
+ const result = JSON.stringify(value, (_key, node) => {
808
+ if (!isNode(node)) {
809
+ return node;
810
+ }
811
+ switch (node.kind) {
812
+ case Kind.VARIABLE:
813
+ return [node.kind, node.name.value];
814
+ case Kind.OBJECT:
815
+ return [
816
+ node.kind,
817
+ node.fields
818
+ .slice()
819
+ .sort((first, second) =>
820
+ first.name.value < second.name.value
821
+ ? -1
822
+ : first.name.value > second.name.value
823
+ ? 1
824
+ : 0,
825
+ ),
826
+ ];
827
+ case Kind.OBJECT_FIELD:
828
+ return [node.name.value, node.value];
829
+ case Kind.LIST:
830
+ return [node.kind, node.values];
831
+ case Kind.STRING:
832
+ return [node.kind, node.value, node.block === true];
833
+ default:
834
+ return [node.kind, 'value' in node ? node.value : null];
835
+ }
836
+ });
837
+ ruleContext.stringifiedValues.set(value, result);
838
+ return result;
666
839
  }
667
840
 
668
841
  // Two types conflict if both types could not apply to a value simultaneously.
669
842
  // Composite types are ignored as their individual field types will be compared
670
843
  // later recursively. However List and Non-Null types must match.
671
844
  function doTypesConflict(
845
+ ruleContext: RuleContext,
672
846
  type1: GraphQLOutputType,
673
847
  type2: GraphQLOutputType,
674
848
  ): boolean {
849
+ if (type1 === type2) {
850
+ return false;
851
+ }
852
+ spendComplexityBudget(ruleContext, 1);
675
853
  if (isListType(type1)) {
676
854
  return isListType(type2)
677
- ? doTypesConflict(type1.ofType, type2.ofType)
855
+ ? doTypesConflict(ruleContext, type1.ofType, type2.ofType)
678
856
  : true;
679
857
  }
680
858
  if (isListType(type2)) {
@@ -682,7 +860,7 @@ function doTypesConflict(
682
860
  }
683
861
  if (isNonNullType(type1)) {
684
862
  return isNonNullType(type2)
685
- ? doTypesConflict(type1.ofType, type2.ofType)
863
+ ? doTypesConflict(ruleContext, type1.ofType, type2.ofType)
686
864
  : true;
687
865
  }
688
866
  if (isNonNullType(type2)) {
@@ -697,57 +875,67 @@ function doTypesConflict(
697
875
  // Given a selection set, return the collection of fields (a mapping of response
698
876
  // name to field nodes and definitions) as well as a list of fragment names
699
877
  // referenced via fragment spreads.
700
- function getFieldsAndFragmentNames(
701
- context: ValidationContext,
702
- cachedFieldsAndFragmentNames,
878
+ function collectFields(
879
+ validationContext: ValidationContext,
880
+ ruleContext: RuleContext,
703
881
  parentType: ?GraphQLNamedType,
704
882
  selectionSet: SelectionSetNode,
705
- ): [NodeAndDefCollection, Array<string>] {
706
- let cached = cachedFieldsAndFragmentNames.get(selectionSet);
707
- if (!cached) {
708
- const nodeAndDefs = Object.create(null);
709
- const fragmentNames = Object.create(null);
710
- _collectFieldsAndFragmentNames(
711
- context,
712
- parentType,
713
- selectionSet,
714
- nodeAndDefs,
715
- fragmentNames,
716
- );
717
- cached = [nodeAndDefs, Object.keys(fragmentNames)];
718
- cachedFieldsAndFragmentNames.set(selectionSet, cached);
883
+ ): CollectFieldsResult {
884
+ const { cachedCollectFieldsResults } = ruleContext;
885
+ // A programmatically built document can share a selection-set object between
886
+ // different parent types; their field definitions must not share a cache entry.
887
+ let bySelectionSet = cachedCollectFieldsResults.get(parentType);
888
+ if (bySelectionSet === undefined) {
889
+ bySelectionSet = new Map();
890
+ cachedCollectFieldsResults.set(parentType, bySelectionSet);
891
+ }
892
+ const cached = bySelectionSet.get(selectionSet);
893
+ if (cached) {
894
+ return cached;
719
895
  }
720
- return cached;
896
+ const fieldDetails: GroupedFieldSet = Object.create(null);
897
+ const fragmentNames: ObjMap<boolean> = Object.create(null);
898
+ collectFieldsImpl(
899
+ validationContext,
900
+ parentType,
901
+ selectionSet,
902
+ fieldDetails,
903
+ fragmentNames,
904
+ );
905
+ const result: CollectFieldsResult = {
906
+ groupedFieldSet: fieldDetails,
907
+ responseNames: Object.keys(fieldDetails),
908
+ fragmentNames: Object.keys(fragmentNames),
909
+ };
910
+ bySelectionSet.set(selectionSet, result);
911
+ return result;
721
912
  }
722
913
 
723
914
  // Given a reference to a fragment, return the represented collection of fields
724
915
  // as well as a list of nested fragment names referenced via fragment spreads.
725
- function getReferencedFieldsAndFragmentNames(
726
- context: ValidationContext,
727
- cachedFieldsAndFragmentNames,
916
+ function collectFragmentFields(
917
+ validationContext: ValidationContext,
918
+ ruleContext: RuleContext,
728
919
  fragment: FragmentDefinitionNode,
729
920
  ) {
730
- // Short-circuit building a type from the node if possible.
731
- const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);
732
- if (cached) {
733
- return cached;
734
- }
735
-
736
- const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition);
737
- return getFieldsAndFragmentNames(
738
- context,
739
- cachedFieldsAndFragmentNames,
921
+ const fragmentType = typeFromAST(
922
+ validationContext.getSchema(),
923
+ fragment.typeCondition,
924
+ );
925
+ return collectFields(
926
+ validationContext,
927
+ ruleContext,
740
928
  fragmentType,
741
929
  fragment.selectionSet,
742
930
  );
743
931
  }
744
932
 
745
- function _collectFieldsAndFragmentNames(
746
- context: ValidationContext,
933
+ function collectFieldsImpl(
934
+ validationContext: ValidationContext,
747
935
  parentType: ?GraphQLNamedType,
748
936
  selectionSet: SelectionSetNode,
749
- nodeAndDefs,
750
- fragmentNames,
937
+ fieldDetails: GroupedFieldSet,
938
+ fragmentNames: ObjMap<boolean>,
751
939
  ): void {
752
940
  for (const selection of selectionSet.selections) {
753
941
  switch (selection.kind) {
@@ -760,10 +948,16 @@ function _collectFieldsAndFragmentNames(
760
948
  const responseName = selection.alias
761
949
  ? selection.alias.value
762
950
  : fieldName;
763
- if (!nodeAndDefs[responseName]) {
764
- nodeAndDefs[responseName] = [];
951
+ if (!fieldDetails[responseName]) {
952
+ fieldDetails[responseName] = [];
765
953
  }
766
- nodeAndDefs[responseName].push([parentType, selection, fieldDef]);
954
+ fieldDetails[responseName].push({
955
+ parentType,
956
+ node: selection,
957
+ definition: fieldDef,
958
+ isSimpleLeaf:
959
+ (selection.arguments?.length ?? 0) === 0 && !selection.selectionSet,
960
+ });
767
961
  break;
768
962
  }
769
963
  case Kind.FRAGMENT_SPREAD:
@@ -772,13 +966,13 @@ function _collectFieldsAndFragmentNames(
772
966
  case Kind.INLINE_FRAGMENT: {
773
967
  const typeCondition = selection.typeCondition;
774
968
  const inlineFragmentType = typeCondition
775
- ? typeFromAST(context.getSchema(), typeCondition)
969
+ ? typeFromAST(validationContext.getSchema(), typeCondition)
776
970
  : parentType;
777
- _collectFieldsAndFragmentNames(
778
- context,
971
+ collectFieldsImpl(
972
+ validationContext,
779
973
  inlineFragmentType,
780
974
  selection.selectionSet,
781
- nodeAndDefs,
975
+ fieldDetails,
782
976
  fragmentNames,
783
977
  );
784
978
  break;
@@ -796,16 +990,57 @@ function subfieldConflicts(
796
990
  node2: FieldNode,
797
991
  ): ?Conflict {
798
992
  if (conflicts.length > 0) {
799
- return [
800
- [responseName, conflicts.map(([reason]) => reason)],
801
- conflicts.reduce((allFields, [, fields1]) => allFields.concat(fields1), [
802
- node1,
803
- ]),
804
- conflicts.reduce(
805
- (allFields, [, , fields2]) => allFields.concat(fields2),
806
- [node2],
807
- ),
808
- ];
993
+ let message = '';
994
+ for (const { responseName: name, reason } of conflicts) {
995
+ message +=
996
+ (message === '' ? '' : ' and ') +
997
+ `subfields "${maybeAbbreviate(name)}" conflict because ${reason}`;
998
+ if (message.length > MAX_CONFLICT_DETAIL_LENGTH) {
999
+ break;
1000
+ }
1001
+ }
1002
+ return {
1003
+ responseName,
1004
+ reason: maybeAbbreviate(message),
1005
+ fields1: collectConflictNodes(node1, conflicts, 'fields1'),
1006
+ fields2: collectConflictNodes(node2, conflicts, 'fields2'),
1007
+ };
1008
+ }
1009
+ }
1010
+
1011
+ function collectConflictNodes(
1012
+ node: FieldNode,
1013
+ conflicts: $ReadOnlyArray<Conflict>,
1014
+ side: 'fields1' | 'fields2',
1015
+ ): Array<FieldNode> {
1016
+ const nodes = [node];
1017
+ for (const conflict of conflicts) {
1018
+ const remaining = MAX_CONFLICT_NODES - nodes.length;
1019
+ // Locations start with the enclosing field. Take from the end so that
1020
+ // truncation favors the deeper fields involved in the conflict.
1021
+ const retainedNodes = (side === 'fields1'
1022
+ ? conflict.fields1
1023
+ : conflict.fields2
1024
+ ).slice(-remaining);
1025
+ nodes.push(...retainedNodes);
1026
+ if (nodes.length === MAX_CONFLICT_NODES) {
1027
+ break;
1028
+ }
1029
+ }
1030
+ return nodes;
1031
+ }
1032
+
1033
+ function maybeAbbreviate(text: string): string {
1034
+ return text.length > MAX_CONFLICT_DETAIL_LENGTH
1035
+ ? text.slice(0, MAX_CONFLICT_DETAIL_LENGTH) + '...'
1036
+ : text;
1037
+ }
1038
+
1039
+ function spendComplexityBudget(ruleContext: RuleContext, cost: number): void {
1040
+ ruleContext.remainingComplexityBudget -= cost;
1041
+ /* istanbul ignore if -- exercised by private complexity calibration */
1042
+ if (ruleContext.remainingComplexityBudget < 0) {
1043
+ throw validationAbortedError;
809
1044
  }
810
1045
  }
811
1046
 
@@ -826,6 +1061,7 @@ class PairSet {
826
1061
  if (result === undefined) {
827
1062
  return false;
828
1063
  }
1064
+
829
1065
  // areMutuallyExclusive being false is a superset of being true,
830
1066
  // hence if we want to know if this PairSet "has" these two with no
831
1067
  // exclusivity, we have to ensure it was added as such.