@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/walk.ts ADDED
@@ -0,0 +1,696 @@
1
+ /**
2
+ * The traversal: types, variants, fields and fragments read into a plan's merge list. The entry
3
+ * points that drive it are the statics of `Plan` in plan.ts, which imports this module; the
4
+ * `Plan` import below is a type import, so nothing here runs at import time and the pair is not a
5
+ * runtime cycle.
6
+ */
7
+ import {
8
+ getMappedArgumentValues,
9
+ isThenable,
10
+ type MaybePromise,
11
+ PothosValidationError,
12
+ } from '@pothos/core';
13
+ import {
14
+ type FieldNode,
15
+ type FragmentDefinitionNode,
16
+ type FragmentSpreadNode,
17
+ type GraphQLNamedType,
18
+ getNamedType,
19
+ type InlineFragmentNode,
20
+ isInterfaceType,
21
+ isObjectType,
22
+ Kind,
23
+ type SelectionNode,
24
+ } from 'graphql';
25
+ import type { NodeBase } from './adapter.js';
26
+ import { EMPTY_MAPPING, type Mapping, unionMappings } from './loader-map.js';
27
+ import {
28
+ collectSelectedFieldNames,
29
+ findMatches,
30
+ firstMatch,
31
+ includeOf,
32
+ isDeferred,
33
+ isSkipped,
34
+ matchesForModel,
35
+ modelOf,
36
+ normalizeInclude,
37
+ resolveType,
38
+ } from './matches.js';
39
+ import type { Plan } from './plan.js';
40
+ import type { NestedSelection, Position, SelectFn, WalkedType } from './types.js';
41
+
42
+ /**
43
+ * One select invocation's mapping record while the invocation runs: `pending` counts the nested
44
+ * selections it started whose plan is async and has not resolved. Removed once every one has,
45
+ * so a recorded `Mapping` never carries it and a synchronous invocation never touches it.
46
+ */
47
+ interface Invocation extends Mapping {
48
+ pending?: number;
49
+ }
50
+
51
+ /** Collects a type's type-level selection, once, before its fields are walked. */
52
+ function enter<Model, Query, NodeType extends NodeBase<Model>>(
53
+ plan: Plan<Model, Query, NodeType>,
54
+ type: GraphQLNamedType,
55
+ ) {
56
+ const selection = plan.adapter.typeSelection(type);
57
+
58
+ if (selection) {
59
+ plan.collect({ kind: 'type', query: selection });
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Collects the type-level selection of `variant` when a fragment moves the plan from `type` to
65
+ * another type of the same model, so the variant's resolvers find what its selection promises.
66
+ * Whether the two selections can live in one node is decided when the plan is played.
67
+ */
68
+ function enterVariant<Model, Query, NodeType extends NodeBase<Model>>(
69
+ plan: Plan<Model, Query, NodeType>,
70
+ type: WalkedType,
71
+ variant: WalkedType,
72
+ ) {
73
+ const selection = plan.adapter.typeSelection(variant);
74
+
75
+ if (selection) {
76
+ plan.collect({ kind: 'variant', type, variant, query: selection });
77
+ }
78
+ }
79
+
80
+ /**
81
+ * One selection to walk into a plan, before any indirect include on `type` is followed: the
82
+ * selection sets of `fieldNodes` (every node selecting one field), walked as `type`.
83
+ */
84
+ export interface Branch {
85
+ type: GraphQLNamedType;
86
+ fieldNodes: readonly FieldNode[];
87
+ indirectPath: string[];
88
+ deferred: boolean;
89
+ }
90
+
91
+ /**
92
+ * The same selection after `resolveBranch` followed the include: the type whose fields are
93
+ * walked, and the selection sets to walk on it (none when a deferred fragment is skipped).
94
+ */
95
+ interface ResolvedBranch {
96
+ type: WalkedType;
97
+ selectionSets: (readonly SelectionNode[])[];
98
+ indirectPath: string[];
99
+ }
100
+
101
+ /**
102
+ * Walks every branch into `plan`. The types the selections are walked as, and the variants their
103
+ * fragments move to, are all collected before any field is, so type-level selections come first
104
+ * in the merge list and the plan does not depend on which occurrence of a field, or which path
105
+ * match, came first in the document.
106
+ */
107
+ export function walkBranches<Model, Query, NodeType extends NodeBase<Model>>(
108
+ plan: Plan<Model, Query, NodeType>,
109
+ branches: Branch[],
110
+ ) {
111
+ const resolved = branches.flatMap((branch) => resolveBranch(plan, branch));
112
+ const enteredTypes = new Set<WalkedType>();
113
+ let firstType: WalkedType | undefined;
114
+
115
+ for (const { type, selectionSets } of resolved) {
116
+ // The plan is entered as the first type a match landed on, and every other one as a
117
+ // same-model variant of it, so two type-level selections that conflict are reported here
118
+ // exactly as they are when a fragment moves the plan between the same two types. A type two
119
+ // matches share is entered once.
120
+ if (!enteredTypes.has(type)) {
121
+ enteredTypes.add(type);
122
+
123
+ if (firstType) {
124
+ enterVariant(plan, firstType, type);
125
+ } else {
126
+ firstType = type;
127
+ enter(plan, type);
128
+ }
129
+ }
130
+
131
+ const entered = new Set<string>();
132
+
133
+ for (const selections of selectionSets) {
134
+ enterVariants(plan, type, selections, entered);
135
+ }
136
+ }
137
+
138
+ for (const { type, selectionSets, indirectPath } of resolved) {
139
+ const walked = new Set<string>();
140
+
141
+ for (const selections of selectionSets) {
142
+ walkSelections(plan, type, selections, indirectPath, true, walked);
143
+ }
144
+ }
145
+ }
146
+
147
+ /**
148
+ * The selections `branch` stands for once its type's indirect include is followed, in the order
149
+ * they are walked. A type-level path yields one per match beneath the wrapper; a plain include
150
+ * re-types the plan; anything but an object or interface type yields nothing.
151
+ */
152
+ function resolveBranch<Model, Query, NodeType extends NodeBase<Model>>(
153
+ plan: Plan<Model, Query, NodeType>,
154
+ { type, fieldNodes, indirectPath, deferred }: Branch,
155
+ ): ResolvedBranch[] {
156
+ // Every node selects the same field.
157
+ if (fieldNodes.length === 0 || fieldNodes[0].name.value.startsWith('__')) {
158
+ return [];
159
+ }
160
+
161
+ const { info, adapter } = plan;
162
+ const include = includeOf(type);
163
+ const beneath: ResolvedBranch[] = [];
164
+
165
+ if (include?.paths?.length || include?.path?.length) {
166
+ for (const fieldNode of fieldNodes) {
167
+ const matches = findMatches(info, type, fieldNode, include.paths ?? [include.path!], {
168
+ path: indirectPath,
169
+ deferred,
170
+ });
171
+
172
+ for (const match of matches) {
173
+ beneath.push(
174
+ ...resolveBranch(plan, {
175
+ type: match.type,
176
+ fieldNodes: [match.field],
177
+ indirectPath: match.path,
178
+ deferred: match.deferred,
179
+ }),
180
+ );
181
+ }
182
+ }
183
+
184
+ // The wrapper's own selection is planned only when the wrapper itself is backed by the model
185
+ // being queried (a variant that also points at a nested field). A plain wrapper, or one backed
186
+ // by another model, has nothing of its own to add to this query.
187
+ if (adapter.modelFor(type) !== plan.model) {
188
+ return beneath;
189
+ }
190
+ } else if (include) {
191
+ return resolveBranch(plan, {
192
+ type: info.schema.getType(include.getType())!,
193
+ fieldNodes,
194
+ indirectPath,
195
+ deferred,
196
+ });
197
+ }
198
+
199
+ if (!(isObjectType(type) || isInterfaceType(type))) {
200
+ return beneath;
201
+ }
202
+
203
+ // A deferred selection is entered but, when deferred fragments are skipped, not walked.
204
+ const selectionSets =
205
+ deferred && plan.skipDeferredFragments
206
+ ? []
207
+ : fieldNodes.flatMap((fieldNode) =>
208
+ fieldNode.selectionSet ? [fieldNode.selectionSet.selections] : [],
209
+ );
210
+
211
+ return [...beneath, { type, selectionSets, indirectPath }];
212
+ }
213
+
214
+ type Fragment = FragmentDefinitionNode | InlineFragmentNode;
215
+
216
+ /**
217
+ * Whether `fragment` was already expanded under `key` in the pass `visited` belongs to, recording
218
+ * it if not. A valid fragment DAG can spread the same fragment at every level, so expanding every
219
+ * spread is exponential in its depth. Inline fragments cannot repeat.
220
+ */
221
+ function expandedBefore(visited: Set<string>, key: string, fragment: Fragment): boolean {
222
+ if (fragment.kind !== Kind.FRAGMENT_DEFINITION) {
223
+ return false;
224
+ }
225
+
226
+ const id = `${key}:${fragment.name.value}`;
227
+
228
+ if (visited.has(id)) {
229
+ return true;
230
+ }
231
+
232
+ visited.add(id);
233
+
234
+ return false;
235
+ }
236
+
237
+ /**
238
+ * First pass: enters every same-model variant a fragment under `selections` moves the plan to,
239
+ * before any field is merged, so a conflict between two type-level selections is reported
240
+ * whichever order the fragments appear in and never depends on a field-level select.
241
+ */
242
+ function enterVariants<Model, Query, NodeType extends NodeBase<Model>>(
243
+ plan: Plan<Model, Query, NodeType>,
244
+ type: WalkedType,
245
+ selections: readonly SelectionNode[],
246
+ visited: Set<string>,
247
+ ) {
248
+ for (const selection of selections) {
249
+ if (selection.kind === Kind.FIELD) {
250
+ continue;
251
+ }
252
+
253
+ const fragment = applicableFragment(plan, selection);
254
+
255
+ if (!fragment || expandedBefore(visited, type.name, fragment)) {
256
+ continue;
257
+ }
258
+
259
+ const as = fragmentTypeOf(plan, type, fragment);
260
+
261
+ if (as && as !== type) {
262
+ enterVariant(plan, type, as);
263
+ }
264
+
265
+ enterVariants(plan, as ?? type, fragment.selectionSet.selections, visited);
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Second pass: walks `selections` in document order, a fragment's fields where the fragment
271
+ * appears. Fields apply unless the enclosing fragment cannot apply to `type`; nested fragments
272
+ * are always classified against `type`, so one may narrow back to it.
273
+ */
274
+ function walkSelections<Model, Query, NodeType extends NodeBase<Model>>(
275
+ plan: Plan<Model, Query, NodeType>,
276
+ type: WalkedType,
277
+ selections: readonly SelectionNode[],
278
+ indirectPath: string[],
279
+ fieldsApply: boolean,
280
+ visited: Set<string>,
281
+ ) {
282
+ for (const selection of selections) {
283
+ if (selection.kind === Kind.FIELD) {
284
+ if (fieldsApply) {
285
+ walkField(plan, type, selection, indirectPath);
286
+ }
287
+
288
+ continue;
289
+ }
290
+
291
+ const fragment = applicableFragment(plan, selection);
292
+
293
+ if (!fragment || expandedBefore(visited, `${type.name}:${fieldsApply}`, fragment)) {
294
+ continue;
295
+ }
296
+
297
+ const as = fragmentTypeOf(plan, type, fragment);
298
+
299
+ walkSelections(
300
+ plan,
301
+ as ?? type,
302
+ fragment.selectionSet.selections,
303
+ indirectPath,
304
+ // An untyped fragment inherits; a typed one applies iff it can apply to `type`.
305
+ fragment.typeCondition ? as !== undefined : fieldsApply,
306
+ visited,
307
+ );
308
+ }
309
+ }
310
+
311
+ /**
312
+ * The fragment a non-field selection stands for, or undefined when it does not apply: skipped by
313
+ * a directive, or deferred while the plan skips deferred fragments.
314
+ */
315
+ function applicableFragment<Model, Query, NodeType extends NodeBase<Model>>(
316
+ { info, skipDeferredFragments }: Plan<Model, Query, NodeType>,
317
+ selection: FragmentSpreadNode | InlineFragmentNode,
318
+ ): Fragment | undefined {
319
+ if (isSkipped(info, selection) || (skipDeferredFragments && isDeferred(info, selection))) {
320
+ return undefined;
321
+ }
322
+
323
+ return selection.kind === Kind.FRAGMENT_SPREAD ? info.fragments[selection.name.value] : selection;
324
+ }
325
+
326
+ /**
327
+ * The type to walk `fragment` as while walking `type`, or undefined when the fragment cannot
328
+ * apply to `type` (its fields are suppressed; nested fragments are still classified against
329
+ * `type`). An untyped fragment inherits `type`. An object type accepts a fragment on itself or on
330
+ * an interface it implements, walked as itself: a plan on an object type is a plan on rows of that
331
+ * type, so a fragment on any other object type cannot apply to them. An interface accepts a
332
+ * fragment on another type of the same model, walked as that type, so that type's own selection
333
+ * is planned for the rows that resolve to it.
334
+ */
335
+ function fragmentTypeOf<Model, Query, NodeType extends NodeBase<Model>>(
336
+ plan: Plan<Model, Query, NodeType>,
337
+ type: WalkedType,
338
+ fragment: Fragment,
339
+ ): WalkedType | undefined {
340
+ if (!fragment.typeCondition) {
341
+ return type;
342
+ }
343
+
344
+ const condition = plan.info.schema.getType(fragment.typeCondition.name.value)!;
345
+
346
+ if (condition === type) {
347
+ return type;
348
+ }
349
+
350
+ if (isInterfaceType(condition) && type.getInterfaces().includes(condition)) {
351
+ return type;
352
+ }
353
+
354
+ if (
355
+ isInterfaceType(type) &&
356
+ (isObjectType(condition) || isInterfaceType(condition)) &&
357
+ plan.adapter.modelFor(condition) === plan.adapter.modelFor(type)
358
+ ) {
359
+ return condition;
360
+ }
361
+
362
+ return undefined;
363
+ }
364
+
365
+ /** Collects what `fieldNode` (a field of `type`) selects. */
366
+ export function walkField<Model, Query, NodeType extends NodeBase<Model>>(
367
+ plan: Plan<Model, Query, NodeType>,
368
+ type: WalkedType,
369
+ fieldNode: FieldNode,
370
+ indirectPath: string[],
371
+ ) {
372
+ const { info, context, adapter } = plan;
373
+ const name = fieldNode.name.value;
374
+
375
+ if (name.startsWith('__') || isSkipped(info, fieldNode)) {
376
+ return;
377
+ }
378
+
379
+ const field = type.getFields()[name];
380
+
381
+ if (!field) {
382
+ throw new PothosValidationError(`Unknown field ${name} on ${type.name}`);
383
+ }
384
+
385
+ const selection = adapter.fieldSelection(field, type);
386
+
387
+ if (!selection) {
388
+ return;
389
+ }
390
+
391
+ const alias = fieldNode.alias?.value ?? name;
392
+ const key = `${type.name}@${indirectPath.length > 0 ? `${indirectPath.join('.')}.` : ''}${alias}`;
393
+
394
+ if (typeof selection !== 'function') {
395
+ collectField(plan, key, alias, selection, EMPTY_MAPPING);
396
+
397
+ return;
398
+ }
399
+
400
+ // Where this field is, linked to where the plan it was found in hangs. One link, built once per
401
+ // select invocation; nothing walks it unless the adapter's callback asks.
402
+ const position: Position = { parent: plan.position, type, field, node: fieldNode };
403
+ // This invocation's mapping; every nested plan it makes records into `mapping.nested`, which
404
+ // stays invisible to the plan until the invocation's query is accepted.
405
+ const mapping: Invocation = { nested: {}, position };
406
+ const args = getMappedArgumentValues(field, fieldNode, context, info);
407
+ const select = selection as SelectFn<Query>;
408
+
409
+ // The select runs as soon as its own arguments are known; only its merge waits.
410
+ const query = isThenable(args)
411
+ ? args.then((mapped) => runSelect(plan, select, mapped, position, mapping))
412
+ : runSelect(plan, select, args, position, mapping);
413
+
414
+ if (isThenable(query)) {
415
+ plan.chain(query as PromiseLike<Query | false | null | undefined>, (resolved) =>
416
+ collectField(plan, key, alias, resolved, mapping),
417
+ );
418
+ } else {
419
+ collectField(plan, key, alias, query, mapping);
420
+ }
421
+ }
422
+
423
+ function runSelect<Model, Query, NodeType extends NodeBase<Model>>(
424
+ plan: Plan<Model, Query, NodeType>,
425
+ select: SelectFn<Query>,
426
+ args: object,
427
+ position: Position,
428
+ mapping: Invocation,
429
+ ) {
430
+ return select(
431
+ args,
432
+ plan.context,
433
+ nestedSelectionFor(plan, args, position, mapping),
434
+ selectedFieldNodeFor(plan, position),
435
+ position,
436
+ );
437
+ }
438
+
439
+ /**
440
+ * A field the way the document names it, for an error message. The mapping key cannot say this:
441
+ * it holds the alias in place of the name, under the alias path of any indirect include above it.
442
+ */
443
+ function fieldName({ type, node }: Position) {
444
+ const name = `${type.name}.${node.name.value}`;
445
+
446
+ return node.alias ? `${name} (selected as "${node.alias.value}")` : name;
447
+ }
448
+
449
+ /**
450
+ * Collects a field's query with the mapping to record if a play takes it. A falsy query is
451
+ * collected as nothing, so the resolver loads its own data; whether the query fits, and so
452
+ * whether the mapping is ever recorded, is `play`'s decision.
453
+ *
454
+ * An invocation whose nested selection is still pending returned without awaiting it, so its
455
+ * query cannot hold what the nested plan will select and recording its mapping would claim data
456
+ * the query never loads. It is refused instead, and the pending plans (already handled, see
457
+ * `awaitNested`) are left to settle unobserved.
458
+ */
459
+ function collectField<Model, Query, NodeType extends NodeBase<Model>>(
460
+ plan: Plan<Model, Query, NodeType>,
461
+ key: string,
462
+ alias: string,
463
+ query: Query | false | null | undefined,
464
+ mapping: Invocation,
465
+ ) {
466
+ if (!query) {
467
+ return;
468
+ }
469
+
470
+ if (mapping.pending) {
471
+ // Only a select invocation can be pending, and every one of those has a position.
472
+ throw new PothosValidationError(
473
+ `The selection function of ${fieldName(mapping.position!)} returned while a nested selection it started was still pending. Await nestedSelection() (or a helper built on it, such as getQuery) inside an async selection function.`,
474
+ );
475
+ }
476
+
477
+ plan.collect({ kind: 'field', key, alias, query, mapping });
478
+ }
479
+
480
+ /** The nested selection callback of one select invocation. */
481
+ function nestedSelectionFor<Model, Query, NodeType extends NodeBase<Model>>(
482
+ plan: Plan<Model, Query, NodeType>,
483
+ args: object,
484
+ position: Position,
485
+ mapping: Invocation,
486
+ ): NestedSelection<Query> {
487
+ const { adapter, context, info } = plan;
488
+ const { node: fieldNode } = position;
489
+
490
+ return (rawQuery, pathOrInclude, typeName) => {
491
+ // A caller may already have started this promise before path/type validation runs.
492
+ let query: MaybePromise<Query | null | undefined> =
493
+ typeof rawQuery === 'function' || rawQuery === true ? undefined : rawQuery;
494
+
495
+ try {
496
+ const returnType = getNamedType(position.field.type);
497
+ const include = Array.isArray(pathOrInclude)
498
+ ? normalizeInclude(
499
+ pathOrInclude,
500
+ resolveType(info.schema, returnType),
501
+ typeName ? info.schema.getType(typeName) : undefined,
502
+ info.schema,
503
+ )
504
+ : pathOrInclude;
505
+ const target = include ? info.schema.getType(include.getType())! : returnType;
506
+ // `true` is the public "no query"; it never reaches an adapter.
507
+ query =
508
+ rawQuery === true
509
+ ? undefined
510
+ : typeof rawQuery === 'function'
511
+ ? (
512
+ rawQuery as (
513
+ args: object,
514
+ ctx: object,
515
+ position: Position,
516
+ ) => MaybePromise<Query | null | undefined>
517
+ )(args, context, position)
518
+ : rawQuery;
519
+
520
+ if (!modelOf(adapter, info.schema, target)) {
521
+ // A model-less field (a scalar, a type without a model) has nothing beneath it to plan:
522
+ // the nested selection is the query alone, and nothing is recorded for it.
523
+ return (query ?? ({} as Query)) as Query;
524
+ }
525
+
526
+ const child = plan.nested(target, position);
527
+
528
+ try {
529
+ if (isThenable(query)) {
530
+ child.chain(query as PromiseLike<Query | null | undefined>, (resolved) =>
531
+ mergeQuery(child, resolved),
532
+ );
533
+ } else {
534
+ mergeQuery(child, query);
535
+ }
536
+
537
+ const paths = include?.paths?.length
538
+ ? include.paths
539
+ : include?.path?.length
540
+ ? [include.path]
541
+ : undefined;
542
+
543
+ if (paths) {
544
+ // Each match is walked as its own type; the wrapper's selection set is not walked.
545
+ const matches = matchesForModel(
546
+ adapter,
547
+ info.schema,
548
+ findMatches(info, returnType, fieldNode, paths, {
549
+ prefix: includeOf(returnType)?.path,
550
+ }),
551
+ target,
552
+ );
553
+
554
+ walkBranches(
555
+ child,
556
+ matches.map((match) => ({
557
+ // As `Plan.fromInfo` does for its own paths: a matched type with a model is walked
558
+ // with it, and one without (an interface, a wrapper) as the type asked for, so its
559
+ // fields are found and a fragment narrowing to it applies.
560
+ type: modelOf(adapter, info.schema, match.type) ? match.type : target,
561
+ fieldNodes: [match.field],
562
+ indirectPath: match.path,
563
+ deferred: match.deferred,
564
+ })),
565
+ );
566
+ } else {
567
+ const asType = (type: GraphQLNamedType): Branch => ({
568
+ type,
569
+ fieldNodes: [fieldNode],
570
+ indirectPath: [],
571
+ deferred: false,
572
+ });
573
+
574
+ walkBranches(child, [
575
+ ...(target === returnType ? [] : [asType(target)]),
576
+ asType(returnType),
577
+ ]);
578
+ }
579
+ } catch (error) {
580
+ child.abandon();
581
+ throw error;
582
+ }
583
+
584
+ // A promise behind the declared synchronous type, as `finish` returns one.
585
+ return child.pending ? (awaitNested(child, mapping) as Query) : queryNested(child, mapping);
586
+ } catch (error) {
587
+ if (isThenable(query)) {
588
+ query.then(
589
+ () => {},
590
+ () => {},
591
+ );
592
+ }
593
+ throw error;
594
+ }
595
+ };
596
+ }
597
+
598
+ /**
599
+ * The promise of a nested selection whose plan is async, counted against its invocation until it
600
+ * settles. Both outcomes clear the count, so an invocation can catch a failure and retry.
601
+ * Rejections are handled here so a discarded selection does not create an unhandled rejection.
602
+ * A failed child publishes no mappings; fields it did not load can fall back independently.
603
+ */
604
+ function awaitNested<Model, Query, NodeType extends NodeBase<Model>>(
605
+ child: Plan<Model, Query, NodeType>,
606
+ mapping: Invocation,
607
+ ) {
608
+ mapping.pending = (mapping.pending ?? 0) + 1;
609
+
610
+ const result = child.pending!.then(() => queryNested(child, mapping));
611
+
612
+ const settled = () => {
613
+ if (mapping.pending === 1) {
614
+ delete mapping.pending;
615
+ } else {
616
+ mapping.pending! -= 1;
617
+ }
618
+ };
619
+ result.then(settled, settled);
620
+
621
+ return result;
622
+ }
623
+
624
+ /**
625
+ * The nested plan played where the callback needs it serialized, with the mappings it recorded
626
+ * folded into the invocation that started it. Every nested plan of one invocation records into
627
+ * the same `mapping.nested`, so two that map the same key union.
628
+ */
629
+ function queryNested<Model, Query, NodeType extends NodeBase<Model>>(
630
+ child: Plan<Model, Query, NodeType>,
631
+ mapping: Invocation,
632
+ ) {
633
+ const played = child.play();
634
+ // Serialization can throw. Publish mappings only once the caller can use the query.
635
+ const query = child.adapter.toQuery(played.root);
636
+
637
+ for (const key of Object.keys(played.mappings)) {
638
+ mapping.nested[key] = unionMappings(mapping.nested[key], played.mappings[key]);
639
+ }
640
+
641
+ return query;
642
+ }
643
+
644
+ /**
645
+ * The relation query of a nested selection, merged before the walk beneath it whether the
646
+ * callback answered at once or resolved after that walk had already collected its fields — see
647
+ * `collectQuery`. A field of the document that conflicts with the query therefore loses to it
648
+ * either way, and is never mapped to a relation the query loaded with other arguments.
649
+ */
650
+ function mergeQuery<Model, Query, NodeType extends NodeBase<Model>>(
651
+ child: Plan<Model, Query, NodeType>,
652
+ query: Query | null | undefined,
653
+ ) {
654
+ if (query) {
655
+ child.collectQuery(query);
656
+ }
657
+ }
658
+
659
+ /**
660
+ * The first field node selected at `path` beneath the field, seen through any wrapper on the
661
+ * field's return type (an errors plugin result, for instance), whose own path leads to the type
662
+ * the caller's path starts from. An empty path yields the field node itself, or the wrapper's
663
+ * inner node.
664
+ *
665
+ * A node selected only under a `@defer` is returned like any other, whatever the plan's deferred
666
+ * setting says — an adapter gating a computed value on this over-reports rather than under-;
667
+ * `eachSelectedField` in matches.ts says why that direction is the safe one.
668
+ */
669
+ function selectedFieldNodeFor<Model, Query, NodeType extends NodeBase<Model>>(
670
+ plan: Plan<Model, Query, NodeType>,
671
+ { field, node: fieldNode }: Position,
672
+ ) {
673
+ const { info } = plan;
674
+ let names: ReadonlySet<string> | undefined;
675
+
676
+ function getSelection(): ReadonlySet<string>;
677
+ function getSelection(path: string[]): FieldNode | null;
678
+ function getSelection(path?: string[]): ReadonlySet<string> | FieldNode | null {
679
+ if (path === undefined) {
680
+ names ??= collectSelectedFieldNames(info, getNamedType(field.type), [fieldNode]);
681
+ return names;
682
+ }
683
+ const returnType = getNamedType(field.type);
684
+ const match = firstMatch(
685
+ info,
686
+ returnType,
687
+ fieldNode,
688
+ path.map((name) => ({ name })),
689
+ { prefix: includeOf(returnType)?.path },
690
+ );
691
+
692
+ return match?.field ?? null;
693
+ }
694
+
695
+ return getSelection;
696
+ }