@pothos/selection-mapper 0.1.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 (86) hide show
  1. package/.swcrc +10 -0
  2. package/LICENSE +6 -0
  3. package/README.md +92 -0
  4. package/dts/adapter.d.ts +74 -0
  5. package/dts/adapter.d.ts.map +1 -0
  6. package/dts/deep-equal.d.ts +7 -0
  7. package/dts/deep-equal.d.ts.map +1 -0
  8. package/dts/index.d.ts +13 -0
  9. package/dts/index.d.ts.map +1 -0
  10. package/dts/loader-map.d.ts +63 -0
  11. package/dts/loader-map.d.ts.map +1 -0
  12. package/dts/matches.d.ts +113 -0
  13. package/dts/matches.d.ts.map +1 -0
  14. package/dts/node.d.ts +85 -0
  15. package/dts/node.d.ts.map +1 -0
  16. package/dts/plan.d.ts +176 -0
  17. package/dts/plan.d.ts.map +1 -0
  18. package/dts/types.d.ts +97 -0
  19. package/dts/types.d.ts.map +1 -0
  20. package/dts/walk.d.ts +24 -0
  21. package/dts/walk.d.ts.map +1 -0
  22. package/esm/adapter.d.ts +74 -0
  23. package/esm/adapter.d.ts.map +1 -0
  24. package/esm/adapter.js +47 -0
  25. package/esm/adapter.js.map +1 -0
  26. package/esm/deep-equal.d.ts +7 -0
  27. package/esm/deep-equal.d.ts.map +1 -0
  28. package/esm/deep-equal.js +50 -0
  29. package/esm/deep-equal.js.map +1 -0
  30. package/esm/index.d.ts +13 -0
  31. package/esm/index.d.ts.map +1 -0
  32. package/esm/index.js +12 -0
  33. package/esm/index.js.map +1 -0
  34. package/esm/loader-map.d.ts +63 -0
  35. package/esm/loader-map.d.ts.map +1 -0
  36. package/esm/loader-map.js +197 -0
  37. package/esm/loader-map.js.map +1 -0
  38. package/esm/matches.d.ts +113 -0
  39. package/esm/matches.d.ts.map +1 -0
  40. package/esm/matches.js +419 -0
  41. package/esm/matches.js.map +1 -0
  42. package/esm/node.d.ts +85 -0
  43. package/esm/node.d.ts.map +1 -0
  44. package/esm/node.js +232 -0
  45. package/esm/node.js.map +1 -0
  46. package/esm/package.json +3 -0
  47. package/esm/plan.d.ts +176 -0
  48. package/esm/plan.d.ts.map +1 -0
  49. package/esm/plan.js +339 -0
  50. package/esm/plan.js.map +1 -0
  51. package/esm/types.d.ts +97 -0
  52. package/esm/types.d.ts.map +1 -0
  53. package/esm/types.js +10 -0
  54. package/esm/types.js.map +1 -0
  55. package/esm/walk.d.ts +24 -0
  56. package/esm/walk.d.ts.map +1 -0
  57. package/esm/walk.js +442 -0
  58. package/esm/walk.js.map +1 -0
  59. package/lib/adapter.js +43 -0
  60. package/lib/adapter.js.map +1 -0
  61. package/lib/deep-equal.js +60 -0
  62. package/lib/deep-equal.js.map +1 -0
  63. package/lib/index.js +57 -0
  64. package/lib/index.js.map +1 -0
  65. package/lib/loader-map.js +209 -0
  66. package/lib/loader-map.js.map +1 -0
  67. package/lib/matches.js +427 -0
  68. package/lib/matches.js.map +1 -0
  69. package/lib/node.js +245 -0
  70. package/lib/node.js.map +1 -0
  71. package/lib/plan.js +349 -0
  72. package/lib/plan.js.map +1 -0
  73. package/lib/types.js +9 -0
  74. package/lib/types.js.map +1 -0
  75. package/lib/walk.js +455 -0
  76. package/lib/walk.js.map +1 -0
  77. package/package.json +55 -0
  78. package/src/adapter.ts +96 -0
  79. package/src/deep-equal.ts +67 -0
  80. package/src/index.ts +32 -0
  81. package/src/loader-map.ts +287 -0
  82. package/src/matches.ts +681 -0
  83. package/src/node.ts +327 -0
  84. package/src/plan.ts +454 -0
  85. package/src/types.ts +123 -0
  86. package/src/walk.ts +696 -0
package/src/matches.ts ADDED
@@ -0,0 +1,681 @@
1
+ import { createContextCache, PothosValidationError } from '@pothos/core';
2
+ import {
3
+ doTypesOverlap,
4
+ type FieldNode,
5
+ type FragmentDefinitionNode,
6
+ type FragmentSpreadNode,
7
+ type GraphQLField,
8
+ GraphQLIncludeDirective,
9
+ type GraphQLNamedType,
10
+ type GraphQLResolveInfo,
11
+ type GraphQLSchema,
12
+ GraphQLSkipDirective,
13
+ getDirectiveValues,
14
+ getNamedType,
15
+ type InlineFragmentNode,
16
+ isAbstractType,
17
+ isInterfaceType,
18
+ isObjectType,
19
+ Kind,
20
+ } from 'graphql';
21
+
22
+ export interface IndirectPathSegment {
23
+ type?: string;
24
+ name: string;
25
+ }
26
+
27
+ export type PathSegment = string | IndirectPathSegment;
28
+
29
+ /**
30
+ * Set on a type's extensions (by the errors plugin, or by hand) to say that a selection on the
31
+ * type is really a selection on `getType()`, found under `path` (or any of `paths`).
32
+ */
33
+ export interface IndirectInclude {
34
+ getType: () => string;
35
+ path?: IndirectPathSegment[];
36
+ paths?: IndirectPathSegment[][];
37
+ }
38
+
39
+ export interface Match {
40
+ /** The GraphQL type of the matched field's return type */
41
+ type: GraphQLNamedType;
42
+ field: FieldNode;
43
+ /** Aliased field names from the starting selection to the matched field */
44
+ path: string[];
45
+ deferred: boolean;
46
+ }
47
+
48
+ export interface MatchOptions {
49
+ /** A type-level path prepended to every path. */
50
+ prefix?: IndirectPathSegment[];
51
+ /** The alias path the returned matches' paths start with. */
52
+ path?: string[];
53
+ deferred?: boolean;
54
+ }
55
+
56
+ /** Just enough of an `Adapter` to look a type's model up. */
57
+ export interface ModelLookup<Model> {
58
+ modelFor: (type: GraphQLNamedType) => Model | undefined;
59
+ }
60
+
61
+ /** The include a type carries, if any. */
62
+ export function includeOf(type: GraphQLNamedType): IndirectInclude | undefined {
63
+ return type.extensions?.pothosIndirectInclude as IndirectInclude | undefined;
64
+ }
65
+
66
+ /** Follows `pothosIndirectInclude.getType()` until a type without one. */
67
+ export function resolveType(schema: GraphQLSchema, type: GraphQLNamedType): GraphQLNamedType {
68
+ let target = type;
69
+ let include = includeOf(target);
70
+
71
+ while (include) {
72
+ target = schema.getType(include.getType())!;
73
+ include = includeOf(target);
74
+ }
75
+
76
+ return target;
77
+ }
78
+
79
+ /**
80
+ * The model of a type, following indirect includes, which `Adapter.modelFor` does not. Every
81
+ * model question the plan asks goes through here.
82
+ */
83
+ export function modelOf<Model>(
84
+ adapter: ModelLookup<Model>,
85
+ schema: GraphQLSchema,
86
+ type: GraphQLNamedType,
87
+ ): Model | undefined {
88
+ return adapter.modelFor(resolveType(schema, type));
89
+ }
90
+
91
+ /**
92
+ * `matches` without the ones whose field returns a model other than `targetType`'s. Several
93
+ * implementations of an interface may share a field name while returning different models, and
94
+ * their selections must never be merged into the same query. Types without a model always match,
95
+ * and a target without one filters nothing.
96
+ */
97
+ export function matchesForModel<Model>(
98
+ adapter: ModelLookup<Model>,
99
+ schema: GraphQLSchema,
100
+ matches: Match[],
101
+ targetType: GraphQLNamedType,
102
+ ): Match[] {
103
+ const targetModel = modelOf(adapter, schema, targetType);
104
+
105
+ if (!targetModel) {
106
+ return matches;
107
+ }
108
+
109
+ return matches.filter((match) => {
110
+ const model = modelOf(adapter, schema, match.type);
111
+
112
+ return !model || model === targetModel;
113
+ });
114
+ }
115
+
116
+ /**
117
+ * One selection set being read, as `eachSelectedField` hands it to a visitor.
118
+ *
119
+ * `type` is the type of the selection set. `expectedType` is the type a field must be selected on
120
+ * for it to count: a field applies only while the two are the same, which is what stops a
121
+ * same-named field under an unrelated fragment from being seen. `resolveFragmentTypes` moves both.
122
+ */
123
+ export interface SelectionLevel {
124
+ type: GraphQLNamedType;
125
+ expectedType: GraphQLNamedType;
126
+ /** Aliased field names from the starting selection down to this level. */
127
+ path: string[];
128
+ /** Whether a `@defer` was crossed on the way to this level. */
129
+ deferred: boolean;
130
+ }
131
+
132
+ /**
133
+ * What `eachSelectedField` calls at every field that applies. Returning `true` stops the
134
+ * traversal; anything else continues it.
135
+ */
136
+ export type FieldVisitor = (field: FieldNode, level: SelectionLevel) => boolean | void;
137
+
138
+ /**
139
+ * The one selection traversal this package owns. It reads the selections of `selection` at
140
+ * `level`: drops what `@skip`/`@include` removes, classifies every fragment
141
+ * (`resolveFragmentTypes`), notes whether a `@defer` was crossed, descends into the fragments
142
+ * that apply, expands a named fragment once per state (`memo`), and calls `visit` at every field
143
+ * that applies to `level.type`. What happens at a field is the caller's alone, which is the whole
144
+ * of the difference between its consumers: `matchPath` matches one path segment's name and
145
+ * descends with the rest of the path, `collectSelectedFieldNames` adds every name and descends no
146
+ * further, and `firstMatch` takes the first match and stops.
147
+ *
148
+ * `segment` is the indirect-include path segment the caller is looking for, when it has one; only
149
+ * its `type` is read, to pin the type a fragment is expected on.
150
+ *
151
+ * `memo` records the named fragments already expanded, keyed on the fragment, the two types, the
152
+ * deferred flag, and `memoKey` — whatever else the caller varies as it descends (`matchPath`
153
+ * passes its remaining path length and its alias path). A fragment spread more than once at one
154
+ * point of the traversal is expanded once: a valid fragment DAG can spread the same fragment at
155
+ * every level, which makes expanding every spread exponential in its depth. A caller that varies
156
+ * nothing passes no `memoKey`, leaving its memo finer than it needs to be by the deferred flag —
157
+ * a little time, never correctness, for a caller that accumulates.
158
+ *
159
+ * This traversal decides nothing about `@defer`: it reports `level.deferred` and the visitor
160
+ * chooses, and the consumers do not choose alike. `findMatches` reports the flag and
161
+ * `walkBranches` honours it, so a deferred branch is entered but its fields are not walked while
162
+ * `skipDeferredFragments` is set; `firstMatch` (the `selectedFieldNode` a select function is
163
+ * handed) and `selectedFieldNames` both discard it.
164
+ *
165
+ * The last two therefore over-report — they answer "yes, the document selects this" for a
166
+ * selection branch resolution will skip — and that direction is what makes the divergence safe.
167
+ * The plugins use both as gates, and a gate computed from an over-reporting source can only be
168
+ * wrongly true, which loads a column or a count nothing reads; it can never be wrongly false, so
169
+ * no row goes missing and anything under-fetched falls through to the model loader, which
170
+ * re-queries. Make either honour the flag and the gates start under-reporting, which loses data;
171
+ * `matches.test.ts` pins the direction.
172
+ */
173
+ function eachSelectedField(
174
+ info: GraphQLResolveInfo,
175
+ selection: FieldNode | FragmentDefinitionNode | InlineFragmentNode,
176
+ level: SelectionLevel,
177
+ segment: IndirectPathSegment | undefined,
178
+ visit: FieldVisitor,
179
+ memo: Set<string>,
180
+ memoKey = '',
181
+ ): boolean {
182
+ if (!selection.selectionSet) {
183
+ return false;
184
+ }
185
+
186
+ const { type, path, deferred } = level;
187
+ // A segment that pins a type condition pins it here too: its field must be found under a
188
+ // fragment on that type, never taken from a level that merely has a field of the same name.
189
+ const expectedType = pinnedType(info, segment) ?? level.expectedType;
190
+ const fieldsApply =
191
+ expectedType.name === type.name && (isObjectType(type) || isInterfaceType(type));
192
+
193
+ for (const sel of selection.selectionSet.selections) {
194
+ if (isSkipped(info, sel)) {
195
+ continue;
196
+ }
197
+
198
+ let fragment: FragmentDefinitionNode | InlineFragmentNode;
199
+
200
+ switch (sel.kind) {
201
+ case Kind.FIELD: {
202
+ if (fieldsApply && visit(sel, level) === true) {
203
+ return true;
204
+ }
205
+
206
+ continue;
207
+ }
208
+ case Kind.FRAGMENT_SPREAD:
209
+ fragment = info.fragments[sel.name.value];
210
+ break;
211
+ case Kind.INLINE_FRAGMENT:
212
+ fragment = sel;
213
+ break;
214
+ default: {
215
+ const unsupported: never = sel;
216
+
217
+ throw new PothosValidationError(
218
+ `Unsupported selection kind ${(unsupported as { kind: string }).kind}`,
219
+ );
220
+ }
221
+ }
222
+
223
+ const next = resolveFragmentTypes(
224
+ info,
225
+ fragment.typeCondition ? info.schema.getType(fragment.typeCondition.name.value)! : undefined,
226
+ type,
227
+ expectedType,
228
+ );
229
+ const deferredHere = deferred || isDeferred(info, sel);
230
+
231
+ if (fragment.kind === Kind.FRAGMENT_DEFINITION) {
232
+ const state = `${fragment.name.value}|${next.type.name}|${next.expectedType.name}|${deferredHere}|${memoKey}`;
233
+
234
+ if (memo.has(state)) {
235
+ continue;
236
+ }
237
+
238
+ memo.add(state);
239
+ }
240
+
241
+ const stopped = eachSelectedField(
242
+ info,
243
+ fragment,
244
+ { type: next.type, expectedType: next.expectedType, path, deferred: deferredHere },
245
+ segment,
246
+ visit,
247
+ memo,
248
+ memoKey,
249
+ );
250
+
251
+ if (stopped) {
252
+ return true;
253
+ }
254
+ }
255
+
256
+ return false;
257
+ }
258
+
259
+ /**
260
+ * The field `name` of `type`, or a validation error. A document naming a field the type does not
261
+ * have only reaches here when graphql validation was skipped; without this it would read a
262
+ * property of undefined.
263
+ */
264
+ function fieldOn(type: GraphQLNamedType, name: string): GraphQLField<unknown, unknown> {
265
+ const field = isObjectType(type) || isInterfaceType(type) ? type.getFields()[name] : undefined;
266
+
267
+ if (!field) {
268
+ throw new PothosValidationError(`Unknown field ${name} on ${type.name}`);
269
+ }
270
+
271
+ return field;
272
+ }
273
+
274
+ /**
275
+ * Follows `includePath` from `level`, starting at segment `at`, to the fields selected at its end,
276
+ * reporting each to `onMatch` in document order and stopping when `onMatch` says to. Every step is
277
+ * one `eachSelectedField` whose visitor matches that segment by name and follows the rest of the
278
+ * path beneath it. The path is walked by index, so a step allocates nothing but the alias path it
279
+ * grew.
280
+ */
281
+ function matchPath(
282
+ info: GraphQLResolveInfo,
283
+ selection: FieldNode | FragmentDefinitionNode | InlineFragmentNode,
284
+ level: SelectionLevel,
285
+ includePath: IndirectPathSegment[],
286
+ at: number,
287
+ onMatch: (match: Match) => boolean | void,
288
+ memo: Set<string>,
289
+ ): boolean {
290
+ const remaining = includePath.length - at;
291
+
292
+ if (remaining === 0) {
293
+ return (
294
+ onMatch({
295
+ type: level.type,
296
+ field: selection as FieldNode,
297
+ path: level.path,
298
+ deferred: level.deferred,
299
+ }) === true
300
+ );
301
+ }
302
+
303
+ const segment = includePath[at];
304
+
305
+ return eachSelectedField(
306
+ info,
307
+ selection,
308
+ level,
309
+ segment,
310
+ (field, on) => {
311
+ if (field.name.value !== segment.name) {
312
+ return false;
313
+ }
314
+
315
+ const returnType = getNamedType(fieldOn(on.type, field.name.value).type);
316
+
317
+ return matchPath(
318
+ info,
319
+ field,
320
+ {
321
+ type: returnType,
322
+ expectedType: returnType,
323
+ path: [...on.path, field.alias?.value ?? field.name.value],
324
+ deferred: on.deferred,
325
+ },
326
+ includePath,
327
+ at + 1,
328
+ onMatch,
329
+ memo,
330
+ );
331
+ },
332
+ memo,
333
+ `${remaining}|${level.path.join('.')}`,
334
+ );
335
+ }
336
+
337
+ /**
338
+ * Follows each of `paths`, prefixed by any type-level `prefix`, from `selection` (which is expected
339
+ * to be a selection on `type`), reporting the fields at their ends to `onMatch` in path order then
340
+ * document order, and stopping when `onMatch` says to. Paths are followed through fragments; see
341
+ * `resolveFragmentTypes` for the rules. Each path gets its own memo: what one path expanded says
342
+ * nothing about the next.
343
+ */
344
+ function eachMatch(
345
+ info: GraphQLResolveInfo,
346
+ type: GraphQLNamedType,
347
+ selection: FieldNode | FragmentDefinitionNode | InlineFragmentNode,
348
+ paths: IndirectPathSegment[][],
349
+ { prefix, path = [], deferred = false }: MatchOptions,
350
+ onMatch: (match: Match) => boolean | void,
351
+ ): void {
352
+ for (const includePath of paths) {
353
+ const stopped = matchPath(
354
+ info,
355
+ selection,
356
+ { type, expectedType: type, path, deferred },
357
+ prefix?.length ? [...prefix, ...includePath] : includePath,
358
+ 0,
359
+ onMatch,
360
+ new Set(),
361
+ );
362
+
363
+ if (stopped) {
364
+ return;
365
+ }
366
+ }
367
+ }
368
+
369
+ /**
370
+ * Every field selected at the end of one of `paths`, each with the `deferred` flag
371
+ * `eachSelectedField` computed for it.
372
+ */
373
+ export function findMatches(
374
+ info: GraphQLResolveInfo,
375
+ type: GraphQLNamedType,
376
+ selection: FieldNode | FragmentDefinitionNode | InlineFragmentNode,
377
+ paths: IndirectPathSegment[][],
378
+ options: MatchOptions = {},
379
+ ): Match[] {
380
+ const matches: Match[] = [];
381
+
382
+ eachMatch(info, type, selection, paths, options, (match) => {
383
+ matches.push(match);
384
+ });
385
+
386
+ return matches;
387
+ }
388
+
389
+ /**
390
+ * The first field selected at the end of `path`, in document order, or undefined. The traversal
391
+ * stops at it. The match's `deferred` flag is reported but this function's caller — the
392
+ * `selectedFieldNode` handed to a select function — discards it; see `eachSelectedField` for why
393
+ * over-reporting a deferred selection there is safe.
394
+ */
395
+ export function firstMatch(
396
+ info: GraphQLResolveInfo,
397
+ type: GraphQLNamedType,
398
+ selection: FieldNode,
399
+ path: IndirectPathSegment[],
400
+ { prefix }: Pick<MatchOptions, 'prefix'> = {},
401
+ ): Match | undefined {
402
+ let first: Match | undefined;
403
+
404
+ eachMatch(info, type, selection, [path], { prefix }, (match) => {
405
+ first = match;
406
+
407
+ return true;
408
+ });
409
+
410
+ return first;
411
+ }
412
+
413
+ /** One node of the memo trie: the names for the field nodes on the path to it, if computed. */
414
+ interface SelectedFieldNamesMemo {
415
+ names?: ReadonlySet<string>;
416
+ next: WeakMap<FieldNode, SelectedFieldNamesMemo>;
417
+ }
418
+
419
+ /**
420
+ * Per request context, per execution (`info.variableValues` is built once per execution, and the
421
+ * names depend on the variables through `@skip`/`@include`), per return type, then per field node.
422
+ */
423
+ const selectedFieldNamesCache = createContextCache(
424
+ () => new WeakMap<object, WeakMap<GraphQLNamedType, SelectedFieldNamesMemo>>(),
425
+ );
426
+
427
+ /**
428
+ * The names of the fields the document selects directly beneath the field being resolved, seen
429
+ * through any wrapper on its return type. Every row of a list resolves the field with the same
430
+ * field nodes, so the result is memoised on them for the execution — on the nodes rather than on
431
+ * `info.fieldNodes`, which graphql-js 17 builds anew for every resolve, and beneath that on
432
+ * `info.variableValues` (one object per execution) and the return type.
433
+ *
434
+ * `@skip` and `@include` are honoured, `@defer` is not: a name selected only under a deferred
435
+ * fragment is reported as selected even when the plan that loads the row will not walk it. This
436
+ * is the over-reporting side of the divergence `eachSelectedField` describes, which is the safe
437
+ * side to gate a column or a count on. A caller that needs to know what the plan will actually
438
+ * load must ask the plan.
439
+ */
440
+ export function selectedFieldNames(context: object, info: GraphQLResolveInfo): ReadonlySet<string> {
441
+ const byExecution = selectedFieldNamesCache(context);
442
+ let byType = byExecution.get(info.variableValues);
443
+
444
+ if (!byType) {
445
+ byType = new WeakMap();
446
+ byExecution.set(info.variableValues, byType);
447
+ }
448
+
449
+ let memo = memoIn(byType, getNamedType(info.returnType));
450
+
451
+ for (const node of info.fieldNodes) {
452
+ memo = memoIn(memo.next, node);
453
+ }
454
+
455
+ memo.names ??= collectSelectedFieldNames(info);
456
+
457
+ return memo.names;
458
+ }
459
+
460
+ function memoIn<K extends object>(
461
+ map: WeakMap<K, SelectedFieldNamesMemo>,
462
+ key: K,
463
+ ): SelectedFieldNamesMemo {
464
+ let memo = map.get(key);
465
+
466
+ if (!memo) {
467
+ memo = { next: new WeakMap() };
468
+ map.set(key, memo);
469
+ }
470
+
471
+ return memo;
472
+ }
473
+
474
+ export function collectSelectedFieldNames(
475
+ info: GraphQLResolveInfo,
476
+ returnType = getNamedType(info.returnType),
477
+ fieldNodes: readonly FieldNode[] = info.fieldNodes,
478
+ ): ReadonlySet<string> {
479
+ const prefix = includeOf(returnType)?.path;
480
+ const names = new Set<string>();
481
+ // Every name at one level: `eachSelectedField`'s last step for all of them at once. The level's
482
+ // `deferred` flag is never read, which is the asymmetry `eachSelectedField` documents.
483
+ const addName: FieldVisitor = (field) => {
484
+ names.add(field.name.value);
485
+ };
486
+
487
+ for (const node of fieldNodes) {
488
+ // Through a wrapper, the fields are those beneath its inner field.
489
+ const roots: { type: GraphQLNamedType; field: FieldNode; deferred: boolean }[] = prefix?.length
490
+ ? findMatches(info, returnType, node, [prefix])
491
+ : [{ type: returnType, field: node, deferred: false }];
492
+
493
+ for (const root of roots) {
494
+ eachSelectedField(
495
+ info,
496
+ root.field,
497
+ { type: root.type, expectedType: root.type, path: [], deferred: root.deferred },
498
+ undefined,
499
+ addName,
500
+ new Set(),
501
+ );
502
+ }
503
+ }
504
+
505
+ return names;
506
+ }
507
+
508
+ /**
509
+ * The type to walk and the type the next segment is expected on, when descending into a fragment.
510
+ * `expected` arrives pinned: `eachSelectedField` resolved any `type` on the segment before it
511
+ * classified a single selection.
512
+ *
513
+ * - A fragment on the expected type, or on an abstract type the expected type belongs to, walks as
514
+ * the expected type: every field selectable there also exists on it.
515
+ * - A fragment that narrows an abstract expected type to an implementation or member, or to an
516
+ * abstract type that overlaps it, advances the expected type so the segment's field can be found
517
+ * on the narrower type.
518
+ * - Fragments on unrelated types keep the expected type, so their fields are skipped until a nested
519
+ * fragment narrows back to it.
520
+ */
521
+ function resolveFragmentTypes(
522
+ info: GraphQLResolveInfo,
523
+ fragmentType: GraphQLNamedType | undefined,
524
+ type: GraphQLNamedType,
525
+ expected: GraphQLNamedType,
526
+ ) {
527
+ if (!fragmentType || fragmentType.name === expected.name) {
528
+ return { type: fragmentType ?? type, expectedType: expected };
529
+ }
530
+
531
+ if (
532
+ isAbstractType(fragmentType) &&
533
+ (isObjectType(expected) || isInterfaceType(expected)) &&
534
+ info.schema.isSubType(fragmentType, expected)
535
+ ) {
536
+ return { type: expected, expectedType: expected };
537
+ }
538
+
539
+ if (isAbstractType(expected)) {
540
+ const narrows =
541
+ isObjectType(fragmentType) || isInterfaceType(fragmentType)
542
+ ? info.schema.isSubType(expected, fragmentType)
543
+ : false;
544
+ const overlaps =
545
+ isAbstractType(fragmentType) && doTypesOverlap(info.schema, expected, fragmentType);
546
+
547
+ if (narrows || overlaps) {
548
+ return { type: fragmentType, expectedType: fragmentType };
549
+ }
550
+ }
551
+
552
+ return { type: fragmentType, expectedType: expected };
553
+ }
554
+
555
+ /**
556
+ * The type an indirect-include segment pins its field to, or undefined when it pins none. A
557
+ * pinned segment names the fragment type condition the field must be found under, so the pin
558
+ * decides both which fragments are descended into and whether a field selected directly at a
559
+ * level counts as the segment's.
560
+ */
561
+ function pinnedType(info: GraphQLResolveInfo, segment: IndirectPathSegment | undefined) {
562
+ if (!segment?.type) {
563
+ return undefined;
564
+ }
565
+
566
+ const pinned = info.schema.getType(segment.type);
567
+
568
+ if (!pinned) {
569
+ throw new PothosValidationError(
570
+ `Unknown type ${segment.type} in indirect include path segment ${segment.name}`,
571
+ );
572
+ }
573
+
574
+ return pinned;
575
+ }
576
+
577
+ /**
578
+ * Turns a path handed to `nestedSelection` into an include. A string segment is a field of the
579
+ * type the previous segment reached; the walker narrows through fragments on its own. A
580
+ * `{ name, type }` segment pins the fragment type condition the field must be found under, and
581
+ * is a field of that type.
582
+ */
583
+ export function normalizeInclude(
584
+ path: PathSegment[],
585
+ type: GraphQLNamedType,
586
+ expectedType: GraphQLNamedType | undefined,
587
+ schema: GraphQLSchema,
588
+ ): IndirectInclude {
589
+ let currentType = path.length > 0 ? type : (expectedType ?? type);
590
+
591
+ const normalized: IndirectPathSegment[] = [];
592
+
593
+ if (path.length === 0 && !(isObjectType(currentType) || isInterfaceType(currentType))) {
594
+ throw new PothosValidationError(`Expected ${currentType} to be an Object or Interface type`);
595
+ }
596
+
597
+ for (const segment of path) {
598
+ const { name, type: pinned } = typeof segment === 'string' ? { name: segment } : segment;
599
+
600
+ if (pinned) {
601
+ const pinnedType = schema.getType(pinned);
602
+
603
+ if (!pinnedType) {
604
+ throw new PothosValidationError(
605
+ `Unknown type ${pinned} in nested selection path segment ${name}`,
606
+ );
607
+ }
608
+
609
+ currentType = pinnedType;
610
+ }
611
+
612
+ if (!(isObjectType(currentType) || isInterfaceType(currentType))) {
613
+ throw new PothosValidationError(`Expected ${currentType} to be an Object or Interface type`);
614
+ }
615
+
616
+ const field: GraphQLField<unknown, unknown> = currentType.getFields()[name];
617
+
618
+ if (!field) {
619
+ throw new PothosValidationError(`Expected ${currentType} to have a field ${name}`);
620
+ }
621
+
622
+ currentType = getNamedType(field.type);
623
+
624
+ if (!(isObjectType(currentType) || isInterfaceType(currentType))) {
625
+ throw new PothosValidationError(`Expected ${currentType} to be an Object or Interface type`);
626
+ }
627
+
628
+ normalized.push(pinned ? { name, type: pinned } : { name });
629
+ }
630
+
631
+ const targetType = currentType;
632
+
633
+ return {
634
+ getType: () => expectedType?.name ?? targetType.name,
635
+ path: normalized,
636
+ };
637
+ }
638
+
639
+ /**
640
+ * Whether a field or fragment is under `@skip(if: true)` or `@include(if: false)`. Asked of every
641
+ * selection the traversal reads, so it answers a selection carrying no directive at all — nearly
642
+ * every one — without building a directive's argument values twice.
643
+ */
644
+ export function isSkipped(
645
+ info: GraphQLResolveInfo,
646
+ selection: FieldNode | FragmentSpreadNode | InlineFragmentNode,
647
+ ) {
648
+ if (!selection.directives?.length) {
649
+ return false;
650
+ }
651
+
652
+ const skip = getDirectiveValues(GraphQLSkipDirective, selection, info.variableValues);
653
+ if (skip?.if === true) {
654
+ return true;
655
+ }
656
+
657
+ const include = getDirectiveValues(GraphQLIncludeDirective, selection, info.variableValues);
658
+ if (include?.if === false) {
659
+ return true;
660
+ }
661
+
662
+ return false;
663
+ }
664
+
665
+ /** Whether a fragment is under `@defer` (when the schema declares the directive). */
666
+ export function isDeferred(
667
+ info: GraphQLResolveInfo,
668
+ node: FragmentSpreadNode | InlineFragmentNode,
669
+ ) {
670
+ if (!node.directives?.length) {
671
+ return false;
672
+ }
673
+
674
+ const deferDirective = info.schema.getDirective('defer');
675
+ if (!deferDirective) {
676
+ return false;
677
+ }
678
+
679
+ const defer = getDirectiveValues(deferDirective, node, info.variableValues);
680
+ return !!defer && defer.if !== false;
681
+ }