forked from niieani/graphql-code-generator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathselection-set-to-object.ts
987 lines (881 loc) · 38 KB
/
selection-set-to-object.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
import { createHash } from 'crypto';
import { getBaseType } from '@graphql-codegen/plugin-helpers';
import { getRootTypes } from '@graphql-tools/utils';
import autoBind from 'auto-bind';
import {
DirectiveNode,
FieldNode,
FragmentSpreadNode,
GraphQLField,
GraphQLNamedType,
GraphQLObjectType,
GraphQLOutputType,
GraphQLSchema,
InlineFragmentNode,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
isTypeSubTypeOf,
isUnionType,
Kind,
SchemaMetaFieldDef,
SelectionNode,
SelectionSetNode,
TypeMetaFieldDef,
} from 'graphql';
import { DependentType, ParsedDocumentsConfig } from './base-documents-visitor.js';
import { BaseVisitorConvertOptions } from './base-visitor.js';
import {
BaseSelectionSetProcessor,
LinkField,
PrimitiveAliasedFields,
PrimitiveField,
ProcessResult,
TSSelectionSet,
} from './selection-set-processor/base.js';
import {
ConvertNameFn,
FragmentDirectives,
GetFragmentSuffixFn,
LoadedFragment,
NormalizedScalarsMap,
} from './types.js';
import {
DeclarationBlockConfig,
getFieldNames,
getFieldNodeNameValue,
getPossibleTypes,
hasConditionalDirectives,
hasIncrementalDeliveryDirectives,
mergeSelectionSets,
separateSelectionSet,
} from './utils.js';
import {
TypeNameProperty,
TypeScriptIntersection,
TypeScriptObject,
TypeScriptObjectProperty,
TypeScriptPrimitiveNever,
TypeScriptRawTypeReference,
TypeScriptStringLiteral,
TypeScriptTypeAlias,
TypeScriptTypeUsage,
TypeScriptUnion,
TypeScriptValue,
TypeScriptValueWithModifiers,
} from './ts-printer.js';
type FragmentSpreadUsage = {
fragmentName: string;
typeName: string;
onType: string;
selectionNodes: Array<SelectionNode>;
fragmentDirectives?: DirectiveNode[];
};
type CollectedFragmentNode = (SelectionNode | FragmentSpreadUsage | DirectiveNode) & FragmentDirectives;
type GroupedTypeScriptTypes = Record<
string,
Array<DependentType | TypeScriptIntersection | TypeScriptUnion | TypeScriptTypeUsage>
>;
// all values of OperationTypeNode (cannot use the import because it would break compatibility with older versions of 'graphql' package)
const operationTypes: string[] = ['Query', 'Mutation', 'Subscription'];
function isMetadataFieldName(name: string) {
return ['__schema', '__type'].includes(name);
}
const metadataFieldMap: Record<string, GraphQLField<any, any>> = {
__schema: SchemaMetaFieldDef,
__type: TypeMetaFieldDef,
};
// TODO: not a global
// const typeCache = new Map<Location, string>();
export class SelectionSetToObject<Config extends ParsedDocumentsConfig = ParsedDocumentsConfig> {
protected _primitiveFields: PrimitiveField[] = [];
protected _primitiveAliasedFields: PrimitiveAliasedFields[] = [];
protected _linksFields: LinkField[] = [];
protected _queriedForTypename = false;
constructor(
protected _processor: BaseSelectionSetProcessor,
protected _scalars: NormalizedScalarsMap,
protected _schema: GraphQLSchema,
protected _convertName: ConvertNameFn<BaseVisitorConvertOptions>,
protected _getFragmentSuffix: GetFragmentSuffixFn,
protected _loadedFragments: LoadedFragment[],
protected _config: Config,
protected _parentSchemaType?: GraphQLNamedType,
protected _selectionSet?: SelectionSetNode
) {
autoBind(this);
}
public createNext(parentSchemaType: GraphQLNamedType, selectionSet: SelectionSetNode): SelectionSetToObject {
return new SelectionSetToObject(
this._processor,
this._scalars,
this._schema,
this._convertName.bind(this),
this._getFragmentSuffix.bind(this),
this._loadedFragments,
this._config,
parentSchemaType,
selectionSet
);
}
/**
* traverse the inline fragment nodes recursively for collecting the selectionSets on each type
*/
_collectInlineFragments(
parentType: GraphQLNamedType,
nodes: Array<InlineFragmentNode & FragmentDirectives>,
types: Map<string, Array<CollectedFragmentNode>>
) {
if (isListType(parentType) || isNonNullType(parentType)) {
return this._collectInlineFragments(parentType.ofType as GraphQLNamedType, nodes, types);
}
if (isObjectType(parentType)) {
for (const node of nodes) {
const typeOnSchema = node.typeCondition ? this._schema.getType(node.typeCondition.name.value) : parentType;
const { fields, inlines, spreads } = separateSelectionSet(node.selectionSet.selections);
const spreadsUsage = this.buildFragmentSpreadsUsage(spreads);
const directives = (node.directives as DirectiveNode[]) || undefined;
// When we collect the selection sets of inline fragments we need to
// make sure directives on the inline fragments are stored in a way
// that can be associated back to the fields in the fragment, to
// support things like making those fields optional when deferring a
// fragment (using @defer).
const fieldsWithFragmentDirectives: CollectedFragmentNode[] = fields.map(field => ({
...field,
fragmentDirectives: field.fragmentDirectives || directives,
}));
if (isObjectType(typeOnSchema)) {
this._appendToTypeMap(types, typeOnSchema.name, fieldsWithFragmentDirectives);
this._appendToTypeMap(types, typeOnSchema.name, spreadsUsage[typeOnSchema.name]);
this._appendToTypeMap(types, typeOnSchema.name, directives);
this._collectInlineFragments(typeOnSchema, inlines, types);
} else if (isInterfaceType(typeOnSchema) && parentType.getInterfaces().includes(typeOnSchema)) {
this._appendToTypeMap(types, parentType.name, fields);
this._appendToTypeMap(types, parentType.name, spreadsUsage[parentType.name]);
this._collectInlineFragments(typeOnSchema, inlines, types);
}
}
} else if (isInterfaceType(parentType)) {
const possibleTypes = getPossibleTypes(this._schema, parentType);
for (const node of nodes) {
const schemaType = node.typeCondition ? this._schema.getType(node.typeCondition.name.value) : parentType;
const { fields, inlines, spreads } = separateSelectionSet(node.selectionSet.selections);
const spreadsUsage = this.buildFragmentSpreadsUsage(spreads);
if (isObjectType(schemaType) && possibleTypes.find(possibleType => possibleType.name === schemaType.name)) {
this._appendToTypeMap(types, schemaType.name, fields);
this._appendToTypeMap(types, schemaType.name, spreadsUsage[schemaType.name]);
this._collectInlineFragments(schemaType, inlines, types);
} else if (isInterfaceType(schemaType) && schemaType.name === parentType.name) {
for (const possibleType of possibleTypes) {
this._appendToTypeMap(types, possibleType.name, fields);
this._appendToTypeMap(types, possibleType.name, spreadsUsage[possibleType.name]);
this._collectInlineFragments(schemaType, inlines, types);
}
} else {
// it must be an interface type that is spread on an interface field
for (const possibleType of possibleTypes) {
if (!node.typeCondition) {
throw new Error('Invalid state. Expected type condition for interface spread on a interface field.');
}
const fragmentSpreadType = this._schema.getType(node.typeCondition.name.value);
// the field should only be added to the valid selections
// in case the possible type actually implements the given interface
if (isTypeSubTypeOf(this._schema, possibleType, fragmentSpreadType)) {
this._appendToTypeMap(types, possibleType.name, fields);
this._appendToTypeMap(types, possibleType.name, spreadsUsage[possibleType.name]);
}
}
}
}
} else if (isUnionType(parentType)) {
const possibleTypes = parentType.getTypes();
for (const node of nodes) {
const schemaType = node.typeCondition ? this._schema.getType(node.typeCondition.name.value) : parentType;
const { fields, inlines, spreads } = separateSelectionSet(node.selectionSet.selections);
const spreadsUsage = this.buildFragmentSpreadsUsage(spreads);
if (isObjectType(schemaType) && possibleTypes.find(possibleType => possibleType.name === schemaType.name)) {
this._appendToTypeMap(types, schemaType.name, fields);
this._appendToTypeMap(types, schemaType.name, spreadsUsage[schemaType.name]);
this._collectInlineFragments(schemaType, inlines, types);
} else if (isInterfaceType(schemaType)) {
const possibleInterfaceTypes = getPossibleTypes(this._schema, schemaType);
for (const possibleType of possibleTypes) {
if (
possibleInterfaceTypes.find(possibleInterfaceType => possibleInterfaceType.name === possibleType.name)
) {
this._appendToTypeMap(types, possibleType.name, fields);
this._appendToTypeMap(types, possibleType.name, spreadsUsage[possibleType.name]);
this._collectInlineFragments(schemaType, inlines, types);
}
}
} else {
for (const possibleType of possibleTypes) {
this._appendToTypeMap(types, possibleType.name, fields);
this._appendToTypeMap(types, possibleType.name, spreadsUsage[possibleType.name]);
}
}
}
}
}
protected _createInlineFragmentForFieldNodes(
parentType: GraphQLNamedType,
fieldNodes: FieldNode[]
): InlineFragmentNode {
return {
kind: Kind.INLINE_FRAGMENT,
typeCondition: {
kind: Kind.NAMED_TYPE,
name: {
kind: Kind.NAME,
value: parentType.name,
},
},
directives: [],
selectionSet: {
kind: Kind.SELECTION_SET,
selections: fieldNodes,
},
};
}
/**
* The `buildFragmentSpreadsUsage` method is used to collect fields from fragment spreads in the selection set.
* It creates a record of fragment spread usages, which includes the fragment name, type name, and the selection nodes
* inside the fragment.
*/
protected buildFragmentSpreadsUsage(spreads: FragmentSpreadNode[]): Record<string, FragmentSpreadUsage[]> {
const selectionNodesByTypeName: Record<string, FragmentSpreadUsage[]> = {};
for (const spread of spreads) {
const fragmentSpreadObject = this._loadedFragments.find(lf => lf.name === spread.name.value);
if (fragmentSpreadObject) {
const schemaType = this._schema.getType(fragmentSpreadObject.onType);
const possibleTypesForFragment = getPossibleTypes(this._schema, schemaType);
for (const possibleType of possibleTypesForFragment) {
const fragmentSuffix = this._getFragmentSuffix(spread.name.value);
const usage = this.buildFragmentTypeName(
spread.name.value,
fragmentSuffix,
possibleTypesForFragment.length === 1 ? null : possibleType.name
);
selectionNodesByTypeName[possibleType.name] ||= [];
selectionNodesByTypeName[possibleType.name].push({
fragmentName: spread.name.value,
typeName: usage,
onType: fragmentSpreadObject.onType,
selectionNodes: [...fragmentSpreadObject.node.selectionSet.selections],
fragmentDirectives: [...spread.directives],
});
}
}
}
return selectionNodesByTypeName;
}
/**
* The `flattenSelectionSet` method is used to flatten the selection set into a map where each key is a type name and
* the value is an array of selection nodes that apply to that type. It handles inline fragments and fragment spreads.
*/
protected flattenSelectionSet(
selections: ReadonlyArray<SelectionNode>,
parentSchemaType?: GraphQLObjectType<any, any>
): Map<string, Array<SelectionNode | FragmentSpreadUsage>> {
const selectionNodesByTypeName = new Map<string, Array<SelectionNode | FragmentSpreadUsage>>();
const inlineFragmentSelections: InlineFragmentNode[] = [];
const fieldNodes: FieldNode[] = [];
const fragmentSpreads: FragmentSpreadNode[] = [];
for (const selection of selections) {
switch (selection.kind) {
case Kind.FIELD:
fieldNodes.push(selection);
break;
case Kind.INLINE_FRAGMENT:
inlineFragmentSelections.push(selection);
break;
case Kind.FRAGMENT_SPREAD:
fragmentSpreads.push(selection);
break;
}
}
if (fieldNodes.length) {
inlineFragmentSelections.push(
this._createInlineFragmentForFieldNodes(parentSchemaType ?? this._parentSchemaType, fieldNodes)
);
}
this._collectInlineFragments(
parentSchemaType ?? this._parentSchemaType,
inlineFragmentSelections,
selectionNodesByTypeName
);
const fragmentsUsage = this.buildFragmentSpreadsUsage(fragmentSpreads);
for (const [typeName, records] of Object.entries(fragmentsUsage)) {
this._appendToTypeMap(selectionNodesByTypeName, typeName, records);
}
return selectionNodesByTypeName;
}
private _appendToTypeMap<T = CollectedFragmentNode>(
types: Map<string, Array<T>>,
typeName: string,
nodes: Array<T>
): void {
if (!types.has(typeName)) {
types.set(typeName, []);
}
if (nodes && nodes.length > 0) {
types.get(typeName).push(...nodes);
}
}
/**
* The `_buildGroupedSelections` method is used to group selection sets by the type they apply to.
* It handles different scenarios such as fields, inline fragments, and fragment spreads. It also takes into account
* directives such as @defer.
*
* mustAddEmptyObject indicates that not all possible types on a union or interface field are covered.
*/
protected _buildGroupedSelections(parentName: string): {
grouped: GroupedTypeScriptTypes;
dependentTypes: DependentType[];
mustAddEmptyObject: boolean;
} {
if (!this._selectionSet?.selections || this._selectionSet.selections.length === 0) {
return { grouped: {}, mustAddEmptyObject: true, dependentTypes: [] };
}
const selectionNodesByTypeName = this.flattenSelectionSet(this._selectionSet.selections);
// in case there is not a selection for each type, we need to add a empty type.
let mustAddEmptyObject = false;
const possibleTypes = getPossibleTypes(this._schema, this._parentSchemaType);
const dependentTypes: DependentType[] = [];
if (!this._config.mergeFragmentTypes || this._config.inlineFragmentTypes === 'mask') {
const grouped = possibleTypes.reduce<GroupedTypeScriptTypes>((prev, type) => {
const typeName = type.name;
const schemaType = this._schema.getType(typeName);
if (!isObjectType(schemaType)) {
throw new TypeError(`Invalid state! Schema type ${typeName} is not a valid GraphQL object!`);
}
const allNodes = selectionNodesByTypeName.get(typeName) || [];
prev[typeName] ||= [];
// incrementalNodes are the ones flagged with @defer, meaning they become nullable I guess?
const { incrementalNodes, selectionNodes, fragmentSpreads } = allNodes.reduce<{
selectionNodes: (SelectionNode | FragmentSpreadUsage)[];
incrementalNodes: FragmentSpreadUsage[];
fragmentSpreads: string[];
}>(
(acc, node) => {
if ('fragmentDirectives' in node && hasIncrementalDeliveryDirectives(node.fragmentDirectives)) {
acc.incrementalNodes.push(node);
} else {
acc.selectionNodes.push(node);
}
return acc;
},
{ selectionNodes: [], incrementalNodes: [], fragmentSpreads: [] }
);
const { fields, dependentTypes: subDependentTypes } = this.buildSelectionSet(schemaType, selectionNodes, {
parentFieldName: operationTypes.includes(typeName.toLowerCase()) ? parentName : `${parentName}_${typeName}`,
});
const transformedSet = this.selectionSetFromFields(fields);
if (transformedSet) {
prev[typeName].push(transformedSet);
}
dependentTypes.push(...subDependentTypes);
if (!transformedSet && !fragmentSpreads.length) {
mustAddEmptyObject = true;
}
for (const incrementalNode of incrementalNodes) {
if (this._config.inlineFragmentTypes === 'mask' && 'fragmentName' in incrementalNode) {
const { fields: incrementalFields, dependentTypes: incrementalDependentTypes } = this.buildSelectionSet(
schemaType,
[incrementalNode],
{
unsetTypes: true,
parentFieldName: parentName,
}
);
const incrementalSet = this.selectionSetFromFields(incrementalFields);
prev[typeName].push(incrementalSet);
dependentTypes.push(...incrementalDependentTypes);
continue;
}
const { fields: initialFields, dependentTypes: initialDependentTypes } = this.buildSelectionSet(
schemaType,
[incrementalNode],
{ parentFieldName: parentName }
);
const { fields: subsequentFields, dependentTypes: subsequentDependentTypes } = this.buildSelectionSet(
schemaType,
[incrementalNode],
{ unsetTypes: true, parentFieldName: parentName }
);
const initialSet = this.selectionSetFromFields(initialFields);
const subsequentSet = this.selectionSetFromFields(subsequentFields);
dependentTypes.push(...initialDependentTypes, ...subsequentDependentTypes);
prev[typeName].push(new TypeScriptUnion({ members: [initialSet, subsequentSet] }));
}
return prev;
}, {});
return { grouped, mustAddEmptyObject, dependentTypes };
}
// Accumulate a map of selected fields to the typenames that
// share the exact same selected fields. When we find multiple
// typenames with the same set of fields, we can collapse the
// generated type to the selected fields and a string literal
// union of the typenames.
//
// E.g. {
// __typename: "foo" | "bar";
// shared: string;
// }
const grouped = possibleTypes.reduce<
Record<string, { fields: (TSSelectionSet | TypeScriptObjectProperty)[]; types: TypeNameProperty[] }>
>((prev, type) => {
const typeName = type.name;
const schemaType = this._schema.getType(typeName);
if (!isObjectType(schemaType)) {
throw new TypeError(`Invalid state! Schema type ${typeName} is not a valid GraphQL object!`);
}
const selectionNodes = selectionNodesByTypeName.get(typeName) || [];
const {
typeInfo,
fields,
dependentTypes: subDependentTypes,
} = this.buildSelectionSet(schemaType, selectionNodes, {
parentFieldName: operationTypes.includes(typeName.toLowerCase()) ? parentName : `${parentName}_${typeName}`,
});
dependentTypes.push(...subDependentTypes);
const selectionSet = this.selectionSetFromFields(fields);
// TODO: is there a better way to group these than by printing it?
const key = selectionSet?.print() ?? 'null';
prev[key] = {
fields,
types: [
...(prev[key]?.types ?? []),
typeInfo || new TypeNameProperty({ value: new TypeScriptRawTypeReference(type.name) }),
].filter(Boolean),
};
return prev;
}, {});
// For every distinct set of fields, create the corresponding
// string literal union of typenames.
const compacted = Object.keys(grouped).reduce<GroupedTypeScriptTypes>((acc, key) => {
const types = grouped[key].types;
// Don't create very large string literal unions. TypeScript
// will stop comparing some nested union types types when
// they contain props with more than some number of string
// literal union members (testing with TS 4.5 stops working
// at 25 for a naive test case:
// https://www.typescriptlang.org/play?ts=4.5.4&ssl=29&ssc=10&pln=29&pc=1#code/C4TwDgpgBAKg9nAMgQwE4HNoF4BQV9QA+UA3ngRQJYB21EqAXDsQEQCMLzULATJ6wGZ+3ACzCWAVnEA2cQHZxADnEBOcWwAM6jl3Z9dbIQbEGpB2QYUHlBtbp5b7O1j30ujLky7Os4wABb0nAC+ODigkFAAQlBYUOT4xGQUVLT0TKzO3G7cHqLiPtwWrFasNqx2mY6ZWXrqeexe3GyF7MXNpc3lzZXZ1dm1ruI8DTxNvGahFEkJKTR0jLMpRNx+gaicy6E4APQ7AALAAM4AtJTo1HCoEDgANhDAUMgMsAgoGNikwQDcdw9QACMXjE4shfmEItAAGI0bCzGbLfDzdIGYbiBrjVrtFidFjdFi9dj9di1Ng5dgNNjjFrqbFsXFsfFsQkOYaDckjYbjNZBHDbPaHU7nS7XP6PZBsF4wuixL6-e6PAGS6KyiXfIA
const max_types = 20;
for (let i = 0; i < types.length; i += max_types) {
const selectedTypes = types.slice(i, i + max_types);
const firstPropertyConfig = grouped[key].types[0];
const typenameUnion = firstPropertyConfig
? this._processor.transformTypenameField(
new TypeScriptUnion({ members: selectedTypes.map(p => p.value) }),
firstPropertyConfig
)
: [];
const transformedSet = this.selectionSetFromFields([...typenameUnion, ...grouped[key].fields]);
// The keys here will be used to generate intermediary
// fragment names. To avoid blowing up the type name on large
// unions, calculate a stable hash here instead.
//
// Also use fragment hashing if skipTypename is true, since we
// then don't have a typename for naming the fragment.
acc[
selectedTypes.length <= 3
? // Remove quote marks to produce a valid type name
selectedTypes.map(t => t.typename.replace(/'/g, '')).join('_')
: createHash('sha256')
.update(selectedTypes.map(t => t.typename).join() || transformedSet.print() || '')
// Remove invalid characters to produce a valid type name
.digest('base64')
.replace(/[=+/]/g, '')
] = [transformedSet];
}
return acc;
}, {});
return { grouped: compacted, mustAddEmptyObject, dependentTypes };
}
protected selectionSetFromFields(
fields: (TSSelectionSet | TypeScriptObjectProperty)[]
): TypeScriptIntersection | TSSelectionSet | null {
const allTypes = fields.filter(
(f): f is TypeScriptObject | TypeScriptTypeUsage =>
f instanceof TypeScriptObject || f instanceof TypeScriptTypeUsage
);
const allObjectProperties = fields.filter(
(f): f is TypeScriptObjectProperty => f instanceof TypeScriptObjectProperty
);
const mergedObjects = allObjectProperties.length
? [this._processor.buildFieldsIntoObject(allObjectProperties)]
: [];
return this._processor.buildSelectionSetFromPieces([...allTypes, ...mergedObjects]);
}
protected buildSelectionSet(
parentSchemaType: GraphQLObjectType,
selectionNodes: Array<SelectionNode | FragmentSpreadUsage | DirectiveNode>,
options: { unsetTypes?: boolean; parentFieldName?: string }
) {
const primitiveFields = new Map<string, FieldNode>();
const primitiveAliasFields = new Map<string, FieldNode>();
const linkFieldSelectionSets = new Map<
string,
{
selectedFieldType: GraphQLOutputType;
field: FieldNode;
}
>();
let requireTypename = false;
// usages via fragment typescript type
const fragmentsSpreadUsages: string[] = [];
// ensure we mutate no function params
selectionNodes = [...selectionNodes];
let inlineFragmentConditional = false;
for (const selectionNode of selectionNodes) {
if ('kind' in selectionNode) {
if (selectionNode.kind === 'Field') {
if (selectionNode.selectionSet) {
let selectedField: GraphQLField<any, any, any> = null;
const fields = parentSchemaType.getFields();
selectedField = fields[selectionNode.name.value];
if (isMetadataFieldName(selectionNode.name.value)) {
selectedField = metadataFieldMap[selectionNode.name.value];
}
if (!selectedField) {
continue;
}
const fieldName = getFieldNodeNameValue(selectionNode);
let linkFieldNode = linkFieldSelectionSets.get(fieldName);
if (linkFieldNode) {
linkFieldNode = {
...linkFieldNode,
field: {
...linkFieldNode.field,
selectionSet: mergeSelectionSets(linkFieldNode.field.selectionSet, selectionNode.selectionSet),
},
};
} else {
linkFieldNode = {
selectedFieldType: selectedField.type,
field: selectionNode,
};
}
linkFieldSelectionSets.set(fieldName, linkFieldNode);
} else if (selectionNode.alias) {
primitiveAliasFields.set(selectionNode.alias.value, selectionNode);
} else if (selectionNode.name.value === '__typename') {
requireTypename = true;
} else {
primitiveFields.set(selectionNode.name.value, selectionNode);
}
} else if (selectionNode.kind === 'Directive') {
if (['skip', 'include'].includes(selectionNode?.name?.value)) {
inlineFragmentConditional = true;
}
} else {
throw new TypeError('Unexpected type.');
}
continue;
}
if (this._config.inlineFragmentTypes === 'combine' || this._config.inlineFragmentTypes === 'mask') {
fragmentsSpreadUsages.push(selectionNode.typeName);
continue;
}
// Handle Fragment Spreads by generating inline types.
const fragmentType = this._schema.getType(selectionNode.onType);
if (fragmentType == null) {
throw new TypeError(`Unexpected error: Type ${selectionNode.onType} does not exist within schema.`);
}
if (
parentSchemaType.name === selectionNode.onType ||
parentSchemaType.getInterfaces().find(iinterface => iinterface.name === selectionNode.onType) != null ||
(isUnionType(fragmentType) &&
fragmentType.getTypes().find(objectType => objectType.name === parentSchemaType.name))
) {
// also process fields from fragment that apply for this parentType
const flatten = this.flattenSelectionSet(selectionNode.selectionNodes, parentSchemaType);
const typeNodes = flatten.get(parentSchemaType.name) ?? [];
selectionNodes.push(...typeNodes);
for (const iinterface of parentSchemaType.getInterfaces()) {
const typeNodes = flatten.get(iinterface.name) ?? [];
selectionNodes.push(...typeNodes);
}
}
}
const linkFields: LinkField[] = [];
const linkFieldsInterfaces: DependentType[] = [];
for (const { field, selectedFieldType } of linkFieldSelectionSets.values()) {
const realSelectedFieldType = getBaseType(selectedFieldType as any);
const selectionSet = this.createNext(realSelectedFieldType, field.selectionSet);
const fieldName = field.alias?.value ?? field.name.value;
const selectionSetObjects = selectionSet.transformSelectionSet(
options.parentFieldName ? `${options.parentFieldName}_${fieldName}` : fieldName
);
linkFieldsInterfaces.push(...selectionSetObjects.dependentTypes);
const isConditional = hasConditionalDirectives(field) || inlineFragmentConditional;
const isOptional = options.unsetTypes;
linkFields.push({
alias: field.alias ? this._processor.config.formatNamedField(field.alias.value, selectedFieldType) : undefined,
name: this._processor.config.formatNamedField(field.name.value, selectedFieldType, isConditional, isOptional),
type: realSelectedFieldType.name,
selectionSet: new TypeScriptValueWithModifiers({
value: selectionSetObjects.tsType,
modify: innerType => this._processor.config.wrapTypeWithModifiers(innerType, selectedFieldType),
}),
});
}
const typeInfoField = this.buildTypeNameField(
parentSchemaType,
this._config.nonOptionalTypename,
this._config.addTypename,
requireTypename,
this._config.skipTypeNameForRoot
);
const fields: ProcessResult = [
// Only add the typename field if we're not merging fragment
// types. If we are merging, we need to wait until we know all
// the involved typenames.
...(typeInfoField && (!this._config.mergeFragmentTypes || this._config.inlineFragmentTypes === 'mask')
? this._processor.transformTypenameField(typeInfoField.value, typeInfoField)
: []),
...this._processor.transformPrimitiveFields(
parentSchemaType,
Array.from(primitiveFields.values()).map(field => ({
isConditional: hasConditionalDirectives(field),
fieldName: field.name.value,
})),
options.unsetTypes
),
...this._processor.transformAliasesPrimitiveFields(
parentSchemaType,
Array.from(primitiveAliasFields.values()).map(field => ({
alias: field.alias.value,
fieldName: field.name.value,
})),
options.unsetTypes
),
...this._processor.transformLinkFields(linkFields, options.unsetTypes),
].filter(Boolean);
// const allProperties = transformed.filter((t): t is TypeScriptObjectProperty => t instanceof TypeScriptObjectProperty)
// const rest = transformed.filter((t): t is TypeScriptObject | TypeScriptTypeUsage => !(t instanceof TypeScriptObjectProperty))
// let mergedPropertiesIntoObject: TypeScriptObject | null = null;
// if (allProperties.length > 0) {
// mergedPropertiesIntoObject = this._processor.buildFieldsIntoObject(allProperties);
// }
// const fields = [...rest, mergedPropertiesIntoObject].filter(Boolean);
if (fragmentsSpreadUsages.length) {
if (this._config.inlineFragmentTypes === 'combine') {
fields.push(
...fragmentsSpreadUsages.map(
fragmentName => new TypeScriptTypeUsage({ typeReference: new TypeScriptRawTypeReference(fragmentName) })
)
);
} else if (this._config.inlineFragmentTypes === 'mask') {
fields.push(
new TypeScriptObjectProperty({
propertyName: ' $fragmentRefs',
optional: true,
value: new TypeScriptObject({
properties: fragmentsSpreadUsages.map(
fragmentName =>
new TypeScriptObjectProperty({
propertyName: fragmentName,
value: options.unsetTypes
? new TypeScriptTypeUsage({
typeReference: new TypeScriptRawTypeReference('Incremental'),
typeArguments: [new TypeScriptRawTypeReference(fragmentName)],
})
: new TypeScriptTypeUsage({ typeReference: new TypeScriptRawTypeReference(fragmentName) }),
})
),
}),
})
);
}
}
return { typeInfo: typeInfoField, fields, dependentTypes: linkFieldsInterfaces };
}
protected buildTypeNameField(
type: GraphQLObjectType,
nonOptionalTypename: boolean = this._config.nonOptionalTypename,
addTypename: boolean = this._config.addTypename,
queriedForTypename: boolean = this._queriedForTypename,
skipTypeNameForRoot: boolean = this._config.skipTypeNameForRoot
): TypeNameProperty | null {
const rootTypes = getRootTypes(this._schema);
if (rootTypes.has(type) && skipTypeNameForRoot && !queriedForTypename) {
return null;
}
if (nonOptionalTypename || addTypename || queriedForTypename) {
const optionalTypename = !queriedForTypename && !nonOptionalTypename;
return new TypeNameProperty({
...this._processor.config.formatNamedField('__typename'),
value: new TypeScriptStringLiteral({ literal: type.name }),
optional: optionalTypename,
});
}
return null;
}
protected getUnknownType() {
return TypeScriptPrimitiveNever;
}
protected getEmptyObjectType() {
return new TypeScriptObject({ properties: [] });
}
private getEmptyObjectTypeIfTrue(mustAddEmptyObject: boolean) {
return mustAddEmptyObject ? this.getEmptyObjectType() : undefined;
}
public transformSelectionSet(fieldName: string): {
tsType: TypeScriptValue;
dependentTypes: DependentType[];
} {
const possibleTypesList = getPossibleTypes(this._schema, this._parentSchemaType);
const possibleTypes = possibleTypesList.map(v => v.name).sort();
const fieldSelections = [
...getFieldNames({ selections: this._selectionSet.selections, loadedFragments: this._loadedFragments }),
].sort();
const cacheHashKey = `${fieldSelections.join(',')} @ ${possibleTypes.join('|')}`;
// LOC => Type => cachedTypeName
// Optimization: Do not create new dependentTypes if fragment typename exists in cache
const objMap = this._processor.typeCache.get(this._selectionSet.loc) ?? new Map<string, TypeScriptTypeAlias>();
this._processor.typeCache.set(this._selectionSet.loc, objMap);
const cachedType = objMap.get(cacheHashKey);
if (cachedType) {
return {
tsType: cachedType,
dependentTypes: [],
};
}
const result = this.transformSelectionSetUncached(fieldName);
objMap.set(cacheHashKey, result.tsType);
if (this._selectionSet.loc) {
this._processor.typeCache.set(this._selectionSet.loc, objMap);
}
return result;
}
private transformSelectionSetUncached(fieldName: string): {
tsType: TypeScriptTypeAlias;
dependentTypes: DependentType[];
} {
const { grouped, mustAddEmptyObject, dependentTypes: subDependentTypes } = this._buildGroupedSelections(fieldName);
const dependentTypes = Object.keys(grouped)
.map(typeName => {
const relevant = grouped[typeName].filter(Boolean);
return relevant.map(objDefinition => {
const name = fieldName ? `${fieldName}_${typeName}` : typeName;
return new TypeScriptTypeAlias({
typeName: name,
definition: objDefinition,
// exporting to avoid Exported variable 'xyz' has or is using name '...' from external module "..." but cannot be named.
export: this._config.extractAllTypes,
});
});
})
.filter(pairs => pairs.length > 0);
const typeParts = [
...dependentTypes.map(pair => {
if (pair.length === 1) {
return this._config.extractAllTypes ? pair[0] : pair[0].definition;
}
return new TypeScriptIntersection({
members: this._config.extractAllTypes ? pair : pair.map(p => ('definition' in p ? p.definition : p)),
});
}),
this.getEmptyObjectTypeIfTrue(mustAddEmptyObject),
].filter(Boolean);
// dependentTypes.length === 0 might happen in case we have an interface, that is being queries, without any GraphQL
// "type" that implements it. It will lead to a runtime error, but we aim to try to reflect that in
// build time as well.
const content = dependentTypes.length === 0 ? this.getUnknownType() : new TypeScriptUnion({ members: typeParts });
const tsType = new TypeScriptTypeAlias({
export: this._config.extractAllTypes,
typeName: fieldName,
definition: content,
});
return {
tsType,
dependentTypes: [
...subDependentTypes,
...dependentTypes.flat(1),
...(this._config.extractAllTypes ? [tsType] : []),
],
};
}
private makeFragmentNameMaskObject(name: string) {
return this._config.inlineFragmentTypes === 'mask'
? new TypeScriptObject({
properties: [
new TypeScriptObjectProperty({
propertyName: ' $fragmentName',
optional: true,
value: new TypeScriptStringLiteral({ literal: name }),
}),
],
})
: undefined;
}
public transformFragmentSelectionSetToTypes(
fragmentName: string,
fragmentSuffix: string,
_declarationBlockConfig: DeclarationBlockConfig
): DependentType[] {
const fragmentTypeName = this.buildFragmentTypeName(fragmentName, fragmentSuffix);
const { grouped, dependentTypes } = this._buildGroupedSelections(fragmentTypeName);
const subTypes: TypeScriptTypeAlias[] = Object.keys(grouped).flatMap(typeName => {
const possibleFields = grouped[typeName].filter(Boolean);
const declarationName = this.buildFragmentTypeName(fragmentName, fragmentSuffix, typeName);
if (possibleFields.length === 0) {
if (this._config.addTypename) {
return [];
}
possibleFields.push(this.getEmptyObjectType());
}
const content = new TypeScriptIntersection({
members: [...possibleFields, this.makeFragmentNameMaskObject(declarationName)].filter(Boolean),
});
return [
new TypeScriptTypeAlias({
typeName: declarationName,
definition: content,
// exporting to avoid Exported variable 'xyz' has or is using name '...' from external module "..." but cannot be named.
export: this._config.extractAllTypes,
}),
];
});
const fragmentMaskPartial = this.makeFragmentNameMaskObject(fragmentName);
// TODO: unify with line 308 from base-documents-visitor
if (subTypes.length === 1) {
return [
...dependentTypes,
new TypeScriptTypeAlias({
typeName: fragmentTypeName,
definition: fragmentMaskPartial
? new TypeScriptIntersection({ members: [subTypes[0].definition, fragmentMaskPartial] })
: subTypes[0].definition,
export: this._config.extractAllTypes,
}),
];
}
if (this._config.exportFragmentSpreadSubTypes) {
for (const type of subTypes) {
type.export = true;
}
}
return [
...dependentTypes,
// TODO: respect declarationBlockConfig
...(this._config.extractAllTypes ? subTypes : []),
new TypeScriptTypeAlias({
typeName: fragmentTypeName,
definition: new TypeScriptUnion({
members: this._config.extractAllTypes ? subTypes : subTypes.map(t => t.definition),
}),
export: true,
}),
];
}
protected buildFragmentTypeName(name: string, suffix: string, typeName = ''): string {
return this._convertName(name, {
useTypesPrefix: true,
suffix: typeName && suffix ? `_${typeName}_${suffix}` : typeName ? `_${typeName}` : suffix,
});
}
}