-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathExtractor.ts
2001 lines (1751 loc) · 59.4 KB
/
Extractor.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
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
FieldDefinitionNode,
InputValueDefinitionNode,
Kind,
NamedTypeNode,
NameNode,
TypeNode,
StringValueNode,
ConstValueNode,
ConstDirectiveNode,
ConstArgumentNode,
EnumValueDefinitionNode,
ConstObjectFieldNode,
ConstObjectValueNode,
ConstListValueNode,
assertName,
DefinitionNode,
} from "graphql";
import {
tsErr,
tsRelated,
DiagnosticsResult,
gqlErr,
} from "./utils/DiagnosticError";
import { err, ok } from "./utils/Result";
import * as ts from "typescript";
import { NameDefinition, UNRESOLVED_REFERENCE_NAME } from "./TypeContext";
import * as E from "./Errors";
import { traverseJSDocTags } from "./utils/JSDoc";
import { GraphQLConstructor } from "./GraphQLConstructor";
import { relativePath } from "./gratsRoot";
import { ISSUE_URL } from "./Errors";
import { detectInvalidComments } from "./comments";
import { extend, loc } from "./utils/helpers";
import * as Act from "./CodeActions";
export const LIBRARY_IMPORT_NAME = "grats";
export const LIBRARY_NAME = "Grats";
export const TYPE_TAG = "gqlType";
export const FIELD_TAG = "gqlField";
export const SCALAR_TAG = "gqlScalar";
export const INTERFACE_TAG = "gqlInterface";
export const ENUM_TAG = "gqlEnum";
export const UNION_TAG = "gqlUnion";
export const INPUT_TAG = "gqlInput";
export const IMPLEMENTS_TAG_DEPRECATED = "gqlImplements";
export const KILLS_PARENT_ON_EXCEPTION_TAG = "killsParentOnException";
// All the tags that start with gql
export const ALL_TAGS = [
TYPE_TAG,
FIELD_TAG,
SCALAR_TAG,
INTERFACE_TAG,
ENUM_TAG,
UNION_TAG,
INPUT_TAG,
];
const DEPRECATED_TAG = "deprecated";
export const SPECIFIED_BY_TAG = "specifiedBy";
const OPERATION_TYPES = new Set(["Query", "Mutation", "Subscription"]);
type ArgDefaults = Map<string, ts.Expression>;
export type ExtractionSnapshot = {
readonly definitions: DefinitionNode[];
readonly unresolvedNames: Map<ts.EntityName, NameNode>;
readonly nameDefinitions: Map<ts.DeclarationStatement, NameDefinition>;
readonly contextReferences: Array<ts.Node>;
readonly typesWithTypename: Set<string>;
readonly interfaceDeclarations: Array<ts.InterfaceDeclaration>;
};
type FieldTypeContext = {
kind: "OUTPUT" | "INPUT";
};
/**
* Extracts GraphQL definitions from TypeScript source code.
*
* Note that we extract a GraphQL AST with the AST nodes' location information
* populated with references to the TypeScript code from which the types were
* derived.
*
* This ensures that we can apply GraphQL schema validation rules, and any reported
* errors will point to the correct location in the TypeScript source code.
*/
export function extract(
sourceFile: ts.SourceFile,
): DiagnosticsResult<ExtractionSnapshot> {
const extractor = new Extractor();
return extractor.extract(sourceFile);
}
class Extractor {
definitions: DefinitionNode[] = [];
// Snapshot data
unresolvedNames: Map<ts.EntityName, NameNode> = new Map();
nameDefinitions: Map<ts.DeclarationStatement, NameDefinition> = new Map();
contextReferences: Array<ts.Node> = [];
typesWithTypename: Set<string> = new Set();
interfaceDeclarations: Array<ts.InterfaceDeclaration> = [];
errors: ts.DiagnosticWithLocation[] = [];
gql: GraphQLConstructor;
constructor() {
this.gql = new GraphQLConstructor();
}
markUnresolvedType(node: ts.EntityName, name: NameNode) {
this.unresolvedNames.set(node, name);
}
recordTypeName(
node: ts.DeclarationStatement,
name: NameNode,
kind: NameDefinition["kind"],
): void {
this.nameDefinitions.set(node, { name, kind });
}
// Traverse all nodes, checking each one for its JSDoc tags.
// If we find a tag we recognize, we extract the relevant information,
// reporting an error if it is attached to a node where that tag is not
// supported.
extract(sourceFile: ts.SourceFile): DiagnosticsResult<ExtractionSnapshot> {
const seenCommentPositions: Set<number> = new Set();
traverseJSDocTags(sourceFile, (node, tag) => {
seenCommentPositions.add(tag.parent.pos);
switch (tag.tagName.text) {
case TYPE_TAG:
this.extractType(node, tag);
break;
case SCALAR_TAG:
this.extractScalar(node, tag);
break;
case INTERFACE_TAG:
this.extractInterface(node, tag);
break;
case ENUM_TAG:
this.extractEnum(node, tag);
break;
case INPUT_TAG:
this.extractInput(node, tag);
break;
case UNION_TAG:
this.extractUnion(node, tag);
break;
case FIELD_TAG:
if (ts.isFunctionDeclaration(node)) {
this.functionDeclarationExtendType(node, tag);
} else if (isStaticMethod(node)) {
this.staticMethodExtendType(node, tag);
} else {
// Non-function fields must be defined as a decent of something that
// is annotated with @gqlType or @gqlInterface.
//
// The actual field will get extracted when we traverse the parent, but
// we need to report an error if the parent is not a valid type or is not
// annotated with @gqlType or @gqlInterface. Otherwise, the user may get
// confused as to why the field is not showing up in the schema.
const parent = getFieldParent(node);
// If there was no valid parent, report an error.
if (parent === null) {
this.reportUnhandled(node, "field", E.fieldTagOnWrongNode());
} else if (this.hasTag(parent, INPUT_TAG)) {
// You don't need to add `@gqlField` to input types, but it's an
// easy mistake to think you might need to. We report a helpful
// error in this case.
this.report(tag, E.gqlFieldTagOnInputType());
} else if (
!this.hasTag(parent, TYPE_TAG) &&
!this.hasTag(parent, INTERFACE_TAG)
) {
this.report(tag, E.gqlFieldParentMissingTag());
}
}
break;
case KILLS_PARENT_ON_EXCEPTION_TAG: {
if (!this.hasTag(node, FIELD_TAG)) {
this.report(
tag.tagName,
E.killsParentOnExceptionOnWrongNode(),
[],
{
fixName: "remove-kills-parent-on-exception",
description: "Remove @killsParentOnException tag",
changes: [Act.removeNode(tag)],
},
);
}
// TODO: Report invalid location as well
break;
}
case SPECIFIED_BY_TAG: {
if (!this.hasTag(node, SCALAR_TAG)) {
this.report(tag.tagName, E.specifiedByOnWrongNode());
}
break;
}
default:
{
const lowerCaseTag = tag.tagName.text.toLowerCase();
if (lowerCaseTag.startsWith("gql")) {
let reported = false;
for (const t of ALL_TAGS) {
if (t.toLowerCase() === lowerCaseTag) {
this.report(
tag.tagName,
E.wrongCasingForGratsTag(tag.tagName.text, t),
[],
{
fixName: "fix-grats-tag-casing",
description: `Change to @${t}`,
changes: [Act.replaceNode(tag.tagName, t)],
},
);
reported = true;
break;
}
}
if (!reported) {
this.report(tag.tagName, E.invalidGratsTag(tag.tagName.text));
}
}
}
break;
}
});
const errors = detectInvalidComments(sourceFile, seenCommentPositions);
extend(this.errors, errors);
if (this.errors.length > 0) {
return err(this.errors);
}
return ok({
definitions: this.definitions,
unresolvedNames: this.unresolvedNames,
nameDefinitions: this.nameDefinitions,
contextReferences: this.contextReferences,
typesWithTypename: this.typesWithTypename,
interfaceDeclarations: this.interfaceDeclarations,
});
}
extractType(node: ts.Node, tag: ts.JSDocTag) {
if (ts.isClassDeclaration(node)) {
this.typeClassDeclaration(node, tag);
} else if (ts.isInterfaceDeclaration(node)) {
this.typeInterfaceDeclaration(node, tag);
} else if (ts.isTypeAliasDeclaration(node)) {
this.typeTypeAliasDeclaration(node, tag);
} else {
this.report(tag, E.invalidTypeTagUsage());
}
}
extractScalar(node: ts.Node, tag: ts.JSDocTag) {
if (ts.isTypeAliasDeclaration(node)) {
this.scalarTypeAliasDeclaration(node, tag);
} else {
this.report(tag, E.invalidScalarTagUsage());
}
}
extractInterface(node: ts.Node, tag: ts.JSDocTag) {
if (ts.isInterfaceDeclaration(node)) {
this.interfaceInterfaceDeclaration(node, tag);
} else {
this.report(tag, E.invalidInterfaceTagUsage());
}
}
extractEnum(node: ts.Node, tag: ts.JSDocTag) {
if (ts.isEnumDeclaration(node)) {
this.enumEnumDeclaration(node, tag);
} else if (ts.isTypeAliasDeclaration(node)) {
this.enumTypeAliasDeclaration(node, tag);
} else {
this.report(tag, E.invalidEnumTagUsage());
}
}
extractInput(node: ts.Node, tag: ts.JSDocTag) {
if (ts.isTypeAliasDeclaration(node)) {
this.inputTypeAliasDeclaration(node, tag);
} else if (ts.isInterfaceDeclaration(node)) {
this.inputInterfaceDeclaration(node, tag);
} else {
this.report(tag, E.invalidInputTagUsage());
}
}
extractUnion(node: ts.Node, tag: ts.JSDocTag) {
if (ts.isTypeAliasDeclaration(node)) {
this.unionTypeAliasDeclaration(node, tag);
} else {
this.report(tag, E.invalidUnionTagUsage());
}
}
/** Error handling and location juggling */
report(
node: ts.Node,
message: string,
relatedInformation?: ts.DiagnosticRelatedInformation[],
fix?: ts.CodeFixAction,
): null {
this.errors.push(tsErr(node, message, relatedInformation, fix));
return null;
}
// Report an error that we don't know how to infer a type, but it's possible that we should.
// Gives the user a path forward if they think we should be able to infer this type.
reportUnhandled(
node: ts.Node,
positionKind:
| "type"
| "field"
| "field type"
| "input"
| "input field"
| "union member"
| "constant value"
| "union"
| "enum value",
message: string,
relatedInformation?: ts.DiagnosticRelatedInformation[],
): null {
const suggestion = `If you think ${LIBRARY_NAME} should be able to infer this ${positionKind}, please report an issue at ${ISSUE_URL}.`;
const completedMessage = `${message}\n\n${suggestion}`;
return this.report(node, completedMessage, relatedInformation);
}
/** TypeScript traversals */
unionTypeAliasDeclaration(node: ts.TypeAliasDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null) return null;
if (!ts.isUnionTypeNode(node.type)) {
return this.report(node, E.expectedUnionTypeNode());
}
const description = this.collectDescription(node);
const types: NamedTypeNode[] = [];
for (const member of node.type.types) {
if (!ts.isTypeReferenceNode(member)) {
return this.reportUnhandled(
member,
"union member",
E.expectedUnionTypeReference(),
);
}
const namedType = this.gql.namedType(
member.typeName,
UNRESOLVED_REFERENCE_NAME,
);
this.markUnresolvedType(member.typeName, namedType.name);
types.push(namedType);
}
this.recordTypeName(node, name, "UNION");
this.definitions.push(
this.gql.unionTypeDefinition(node, name, types, description),
);
}
functionDeclarationExtendType(
node: ts.FunctionDeclaration,
tag: ts.JSDocTag,
) {
const funcName = this.namedFunctionExportName(node);
const name = this.entityName(node, tag);
if (name == null) return null;
if (!ts.isSourceFile(node.parent)) {
return this.report(node, E.functionFieldNotTopLevel());
}
const tsModulePath = relativePath(node.getSourceFile().fileName);
const metadataDirective = this.gql.fieldMetadataDirective(node, {
tsModulePath,
name: null,
exportName: funcName == null ? null : funcName.text,
argCount: node.parameters.length,
});
this.collectAbstractField(node, name, metadataDirective);
}
staticMethodExtendType(node: ts.MethodDeclaration, tag: ts.JSDocTag) {
const methodName = this.expectNameIdentifier(node.name);
if (methodName == null) return null;
const name = this.entityName(node, tag);
if (name == null) return null;
const classNode = node.parent;
if (!ts.isClassDeclaration(classNode)) {
return this.report(classNode, E.staticMethodOnNonClass());
}
let exportName: string | null = null;
const isExported = classNode.modifiers?.some((modifier) => {
return modifier.kind === ts.SyntaxKind.ExportKeyword;
});
if (!isExported) {
return this.report(classNode, E.staticMethodFieldClassNotExported(), [], {
fixName: "add-export-keyword-to-class",
description: "Add export keyword to class with static @gqlField",
changes: [Act.prefixNode(classNode, "export ")],
});
}
const isDefault = classNode.modifiers?.some((modifier) => {
return modifier.kind === ts.SyntaxKind.DefaultKeyword;
});
if (!isDefault) {
if (classNode.name == null) {
return this.report(
classNode,
E.staticMethodClassWithNamedExportNotNamed(),
);
}
const className = this.expectNameIdentifier(classNode.name);
if (className == null) return null;
exportName = className.text;
}
if (!ts.isSourceFile(classNode.parent)) {
return this.report(classNode, E.staticMethodClassNotTopLevel());
}
const tsModulePath = relativePath(node.getSourceFile().fileName);
const metadataDirective = this.gql.fieldMetadataDirective(methodName, {
tsModulePath,
name: methodName.text,
exportName,
argCount: node.parameters.length,
});
this.collectAbstractField(node, name, metadataDirective);
}
collectAbstractField(
node: ts.FunctionDeclaration | ts.MethodDeclaration,
name: NameNode,
metadataDirective: ConstDirectiveNode,
) {
let args: readonly InputValueDefinitionNode[] | null = null;
const argsParam = node.parameters[1];
if (argsParam != null) {
args = this.collectArgs(argsParam);
}
const context = node.parameters[2];
if (context != null) {
this.validateContextParameter(context);
}
const typeParam = node.parameters[0];
if (typeParam == null) {
// TODO: Make error generic
this.errors.push(gqlErr(loc(name), E.invalidParentArgForFunctionField()));
return;
}
const typeName = this.typeReferenceFromParam(typeParam);
if (typeName == null) return null;
if (node.type == null) {
// TODO: Make error generic
this.errors.push(
gqlErr(loc(name), E.invalidReturnTypeForFunctionField()),
);
return;
}
const type = this.collectType(node.type, { kind: "OUTPUT" });
if (type == null) return null;
const directives = [metadataDirective];
const description = this.collectDescription(node);
const deprecated = this.collectDeprecated(node);
if (deprecated != null) {
directives.push(deprecated);
}
const killsParentOnExceptionDirective =
this.killsParentOnExceptionDirective(node);
if (killsParentOnExceptionDirective != null) {
directives.push(killsParentOnExceptionDirective);
}
const field = this.gql.fieldDefinition(
node,
name,
type,
args,
directives,
description,
);
this.definitions.push(
this.gql.abstractFieldDefinition(node, typeName, field),
);
}
typeReferenceFromParam(typeParam: ts.ParameterDeclaration): NameNode | null {
if (typeParam.type == null) {
return this.report(typeParam, E.functionFieldParentTypeMissing());
}
if (!ts.isTypeReferenceNode(typeParam.type)) {
return this.report(typeParam.type, E.functionFieldParentTypeNotValid());
}
const typeName = this.gql.name(
typeParam.type.typeName,
UNRESOLVED_REFERENCE_NAME,
);
this.markUnresolvedType(typeParam.type.typeName, typeName);
return typeName;
}
// A little awkward that null here is both semantic or an indication of an error.
namedFunctionExportName(node: ts.FunctionDeclaration): ts.Identifier | null {
if (node.name == null) {
return this.report(node, E.functionFieldNotNamed());
}
const isExported = node.modifiers?.some((modifier) => {
return modifier.kind === ts.SyntaxKind.ExportKeyword;
});
if (!isExported) {
return this.report(node.name, E.functionFieldNotNamedExport(), [], {
fixName: "add-export-keyword-to-function",
description: "Add export keyword to function with @gqlField",
changes: [Act.prefixNode(node, "export ")],
});
}
const defaultKeyword = node.modifiers?.find((modifier) => {
return modifier.kind === ts.SyntaxKind.DefaultKeyword;
});
if (defaultKeyword != null) {
return null;
}
return node.name;
}
scalarTypeAliasDeclaration(node: ts.TypeAliasDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null) return null;
const description = this.collectDescription(node);
this.recordTypeName(node, name, "SCALAR");
// TODO: Can a scalar be deprecated?
const specifiedByDirective = this.collectSpecifiedBy(node);
this.definitions.push(
this.gql.scalarTypeDefinition(
node,
name,
specifiedByDirective == null ? null : [specifiedByDirective],
description,
),
);
}
inputTypeAliasDeclaration(node: ts.TypeAliasDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null) return null;
const description = this.collectDescription(node);
this.recordTypeName(node, name, "INPUT_OBJECT");
const fields = this.collectInputFields(node);
const deprecatedDirective = this.collectDeprecated(node);
this.definitions.push(
this.gql.inputObjectTypeDefinition(
node,
name,
fields,
deprecatedDirective == null ? null : [deprecatedDirective],
description,
),
);
}
inputInterfaceDeclaration(node: ts.InterfaceDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null) return null;
const description = this.collectDescription(node);
this.recordTypeName(node, name, "INPUT_OBJECT");
const fields: Array<InputValueDefinitionNode> = [];
for (const member of node.members) {
if (!ts.isPropertySignature(member)) {
this.reportUnhandled(
member,
"input field",
E.inputTypeFieldNotProperty(),
);
continue;
}
const field = this.collectInputField(member);
if (field != null) fields.push(field);
}
this.interfaceDeclarations.push(node);
const deprecatedDirective = this.collectDeprecated(node);
this.definitions.push(
this.gql.inputObjectTypeDefinition(
node,
name,
fields,
deprecatedDirective == null ? null : [deprecatedDirective],
description,
),
);
}
collectInputFields(
node: ts.TypeAliasDeclaration,
): Array<InputValueDefinitionNode> | null {
const fields: Array<InputValueDefinitionNode> = [];
if (!ts.isTypeLiteralNode(node.type)) {
return this.reportUnhandled(node, "input", E.inputTypeNotLiteral());
}
for (const member of node.type.members) {
if (!ts.isPropertySignature(member)) {
this.reportUnhandled(
member,
"input field",
E.inputTypeFieldNotProperty(),
);
continue;
}
const field = this.collectInputField(member);
if (field != null) fields.push(field);
}
return fields.length === 0 ? null : fields;
}
collectInputField(
node: ts.PropertySignature,
): InputValueDefinitionNode | null {
const id = this.expectNameIdentifier(node.name);
if (id == null) return null;
if (node.type == null) {
return this.report(node, E.inputFieldUntyped());
}
const inner = this.collectType(node.type, { kind: "INPUT" });
if (inner == null) return null;
const type =
node.questionToken == null ? inner : this.gql.nullableType(inner);
const description = this.collectDescription(node);
const deprecatedDirective = this.collectDeprecated(node);
return this.gql.inputValueDefinition(
node,
this.gql.name(id, id.text),
type,
deprecatedDirective == null ? null : [deprecatedDirective],
null,
description,
);
}
typeClassDeclaration(node: ts.ClassDeclaration, tag: ts.JSDocTag) {
if (node.name == null) {
return this.report(node, E.typeTagOnUnnamedClass());
}
const name = this.entityName(node, tag);
if (name == null) return null;
this.validateOperationTypes(node.name, name.value);
const description = this.collectDescription(node);
const fieldMembers = node.members.filter((member) => {
// Static methods are handled when we encounter the tag at our top-level
// traversal, similar to how functions are handled. We filter them out here to ensure
// we don't double-visit them.
return !isStaticMethod(member);
});
const fields = this.collectFields(fieldMembers);
const interfaces = this.collectInterfaces(node);
this.recordTypeName(node, name, "TYPE");
this.checkForTypenameProperty(node, name.value);
this.definitions.push(
this.gql.objectTypeDefinition(
node,
name,
fields,
interfaces,
description,
),
);
}
validateOperationTypes(node: ts.Node, name: string) {
// TODO: If we start supporting defining operation types using
// non-standard names, we will need to update this logic.
if (OPERATION_TYPES.has(name)) {
this.report(node, E.operationTypeNotUnknown());
}
}
typeInterfaceDeclaration(node: ts.InterfaceDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null) return null;
this.validateOperationTypes(node.name, name.value);
const description = this.collectDescription(node);
const fields = this.collectFields(node.members);
const interfaces = this.collectInterfaces(node);
this.recordTypeName(node, name, "TYPE");
this.checkForTypenameProperty(node, name.value);
this.definitions.push(
this.gql.objectTypeDefinition(
node,
name,
fields,
interfaces,
description,
),
);
}
typeTypeAliasDeclaration(node: ts.TypeAliasDeclaration, tag: ts.JSDocTag) {
const name = this.entityName(node, tag);
if (name == null) return null;
let fields: FieldDefinitionNode[] = [];
let interfaces: NamedTypeNode[] | null = null;
if (ts.isTypeLiteralNode(node.type)) {
this.validateOperationTypes(node.type, name.value);
fields = this.collectFields(node.type.members);
interfaces = this.collectInterfaces(node);
this.checkForTypenameProperty(node.type, name.value);
} else if (node.type.kind === ts.SyntaxKind.UnknownKeyword) {
// This is fine, we just don't know what it is. This should be the expected
// case for operation types such as `Query`, `Mutation`, and `Subscription`
// where there is not strong convention around.
} else {
return this.report(node.type, E.typeTagOnAliasOfNonObjectOrUnknown());
}
const description = this.collectDescription(node);
this.recordTypeName(node, name, "TYPE");
this.definitions.push(
this.gql.objectTypeDefinition(
node,
name,
fields,
interfaces,
description,
),
);
}
checkForTypenameProperty(
node: ts.ClassDeclaration | ts.InterfaceDeclaration | ts.TypeLiteralNode,
expectedName: string,
) {
const hasTypename = node.members.some((member) => {
return this.isValidTypeNameProperty(member, expectedName);
});
if (hasTypename) {
this.typesWithTypename.add(expectedName);
}
}
isValidTypeNameProperty(
member: ts.ClassElement | ts.TypeElement,
expectedName: string,
) {
if (
member.name == null ||
!ts.isIdentifier(member.name) ||
member.name.text !== "__typename"
) {
return false;
}
if (ts.isPropertyDeclaration(member)) {
return this.isValidTypenamePropertyDeclaration(member, expectedName);
}
if (ts.isPropertySignature(member)) {
return this.isValidTypenamePropertySignature(member, expectedName);
}
// TODO: Could show what kind we found, but TS AST does not have node names.
this.report(member.name, E.typeNameNotDeclaration());
return false;
}
isValidTypenamePropertyDeclaration(
node: ts.PropertyDeclaration,
expectedName: string,
) {
// If we have a type annotation, we ask that it be a string literal.
// That means, that if we have one, _and_ it's valid, we're done.
// Otherwise we fall through to the initializer check.
if (node.type != null) {
return this.isValidTypenamePropertyType(node.type, expectedName);
}
if (node.initializer == null) {
this.report(node.name, E.typeNameMissingInitializer());
return false;
}
if (!ts.isStringLiteral(node.initializer)) {
this.report(node.initializer, E.typeNameInitializeNotString());
return false;
}
if (node.initializer.text !== expectedName) {
this.report(
node.initializer,
E.typeNameInitializerWrong(expectedName, node.initializer.text),
);
return false;
}
return true;
}
isValidTypenamePropertySignature(
node: ts.PropertySignature,
expectedName: string,
) {
if (node.type == null) {
this.report(node, E.typeNameMissingTypeAnnotation(expectedName));
return false;
}
return this.isValidTypenamePropertyType(node.type, expectedName);
}
isValidTypenamePropertyType(node: ts.TypeNode, expectedName: string) {
if (!ts.isLiteralTypeNode(node) || !ts.isStringLiteral(node.literal)) {
this.report(node, E.typeNameTypeNotStringLiteral(expectedName));
return false;
}
if (node.literal.text !== expectedName) {
this.report(node, E.typeNameDoesNotMatchExpected(expectedName));
return false;
}
return true;
}
collectInterfaces(
node:
| ts.ClassDeclaration
| ts.InterfaceDeclaration
| ts.TypeAliasDeclaration,
): Array<NamedTypeNode> | null {
this.reportTagInterfaces(node);
return ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node)
? this.collectHeritageInterfaces(node)
: null;
}
reportTagInterfaces(
node:
| ts.TypeAliasDeclaration
| ts.ClassDeclaration
| ts.InterfaceDeclaration,
) {
const tag = this.findTag(node, IMPLEMENTS_TAG_DEPRECATED);
if (tag == null) return null;
if (node.kind === ts.SyntaxKind.ClassDeclaration) {
this.report(tag, E.implementsTagOnClass());
}
if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {
this.report(tag, E.implementsTagOnInterface());
}
if (node.kind === ts.SyntaxKind.TypeAliasDeclaration) {
this.report(tag, E.implementsTagOnTypeAlias());
}
}
collectHeritageInterfaces(
node: ts.ClassDeclaration | ts.InterfaceDeclaration,
): Array<NamedTypeNode> | null {
if (node.heritageClauses == null) return null;
const maybeInterfaces: Array<NamedTypeNode | null> = node.heritageClauses
.filter((clause) => {
if (node.kind === ts.SyntaxKind.ClassDeclaration) {
return clause.token === ts.SyntaxKind.ImplementsKeyword;
}
// Interfaces can only have extends clauses, and those are allowed.
return true;
})
.flatMap((clause): Array<NamedTypeNode | null> => {
return clause.types
.map((type) => type.expression)
.filter((expression): expression is ts.Identifier =>
ts.isIdentifier(expression),
)
.map((expression) => {
const namedType = this.gql.namedType(
expression,
UNRESOLVED_REFERENCE_NAME,
);
this.markUnresolvedType(expression, namedType.name);
return namedType;
});
});
const interfaces = maybeInterfaces.filter(
(i): i is NamedTypeNode => i != null,
);
if (interfaces.length === 0) {
return null;
}
return interfaces;
}
hasGqlTag(node: ts.Node): boolean {
return ts.getJSDocTags(node).some((tag) => {
return ALL_TAGS.includes(tag.tagName.text);
});
}
interfaceInterfaceDeclaration(
node: ts.InterfaceDeclaration,
tag: ts.JSDocTag,
) {
const name = this.entityName(node, tag);
if (name == null || name.value == null) {
return;
}
this.interfaceDeclarations.push(node);
const description = this.collectDescription(node);
const interfaces = this.collectInterfaces(node);
const fields = this.collectFields(node.members);
this.recordTypeName(node, name, "INTERFACE");
this.definitions.push(
this.gql.interfaceTypeDefinition(
node,
name,
fields,
interfaces,
description,
),
);
}
collectFields(
members: ReadonlyArray<ts.ClassElement | ts.TypeElement>,