-
Notifications
You must be signed in to change notification settings - Fork 72
/
index.js
1702 lines (1529 loc) · 57.1 KB
/
index.js
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
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable new-cap */
const fs = require('fs');
const path = require('path');
const babelTemplate = require('@babel/template').default;
const babelCore = require('@babel/core');
const importedDefinitionsCache = new Map();
// react-docgen does not understand typescript annotations
function stripTypeScript(filename, ast) {
return babelCore.transform(babelCore.transformFromAst(ast).code, {
filename: filename,
babelrc: false,
presets: ['@babel/typescript'],
plugins: ['@babel/plugin-syntax-dynamic-import'],
}).code;
}
// determine is a node is a TS*, or if it is a proptype that came from one
function isTSType(node) {
if (node == null) return false;
if (node.isAlreadyResolved) {
return node.isTSType;
}
return node.type.startsWith('TS');
}
/**
* Converts an Array<X> type to PropTypes.arrayOf(X)
* @param node
* @param state
* @returns AST node representing matching proptypes
*/
function resolveArrayToPropTypes(node, state) {
const types = state.get('types');
const { typeParameters } = node;
if (typeParameters == null) {
// Array without any type information
// PropTypes.array
return buildPropTypePrimitiveExpression(types, 'array');
} else {
// Array with typed elements
// PropTypes.arrayOf()
// Array type only has one type argument
const {
params: [arrayType],
} = typeParameters;
return types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('arrayOf')
),
[getPropTypesForNode(arrayType, false, state)]
);
}
}
function stripDoubleQuotes(value) {
return value.replace(/^"?(.*?)"?$/, '$1');
}
/**
* Converts an Omit<X, Y> type to resolveIdentifierToPropTypes(X) with Y removed
* @param node
* @param state
* @returns AST node representing matching proptypes
*/
function resolveOmitToPropTypes(node, state) {
const types = state.get('types');
const { typeParameters } = node;
if (typeParameters == null) return null;
const {
params: [sourceType, toRemove],
} = typeParameters;
const sourcePropTypes = getPropTypesForNode(sourceType, true, state);
// validate that this resulted in a shape, otherwise we don't know how to extract/merge the values
if (
!types.isCallExpression(sourcePropTypes) ||
!types.isMemberExpression(sourcePropTypes.callee) ||
sourcePropTypes.callee.object.name !== 'PropTypes' ||
sourcePropTypes.callee.property.name !== 'shape'
) {
return null;
}
const toRemovePropTypes = getPropTypesForNode(toRemove, true, state);
// validate that this resulted in a oneOf, otherwise we don't know how to use the values
if (
!types.isCallExpression(toRemovePropTypes) ||
!types.isMemberExpression(toRemovePropTypes.callee) ||
toRemovePropTypes.callee.object.name !== 'PropTypes' ||
toRemovePropTypes.callee.property.name !== 'oneOf'
) {
return null;
}
// extract the string values of keys to remove
const keysToRemove = new Set(
toRemovePropTypes.arguments[0].elements
.map((keyToRemove) =>
types.isStringLiteral(keyToRemove) ? keyToRemove.value : null
)
.filter((x) => x !== null)
);
// filter out omitted properties
sourcePropTypes.arguments[0].properties = sourcePropTypes.arguments[0].properties.filter(
({ key: { name } }) => keysToRemove.has(stripDoubleQuotes(name)) === false
);
return sourcePropTypes;
}
/**
* Converts an X[] type to PropTypes.arrayOf(X)
* @param node
* @param state
* @returns AST node representing matching proptypes
*/
function resolveArrayTypeToPropTypes(node, state) {
const types = state.get('types');
const { elementType } = node;
if (elementType == null) {
// Array without any type information
// PropTypes.array
return buildPropTypePrimitiveExpression(types, 'array');
} else {
// Array with typed elements
// PropTypes.arrayOf()
// Array type only has one type argument
return types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('arrayOf')
),
[getPropTypesForNode(elementType, false, state)]
);
}
}
/**
* Resolves the node's identifier to its proptypes.
* Responsible for resolving
* - React.* (SFC, ReactNode, etc)
* - Arrays
* - MouseEventHandler is interpretted as functions
* - ExclusiveUnion custom type
* - OneOf custom type
* - defined types/interfaces (found during initial program body parsing)
* Returns `null` for unresolvable types
* @param node
* @param state
* @returns AST | null
*/
function resolveIdentifierToPropTypes(node, state) {
const typeDefinitions = state.get('typeDefinitions');
const types = state.get('types');
const inflightResolves = state.get('inflightResolves') || new Set();
// Used to inject `href` and `onClick` props for `PropsForAnchor` and `PropsForButton` utility types
const hrefPropertySignature = types.tsPropertySignature(
types.Identifier('href'),
types.TSTypeAnnotation(types.tsStringKeyword())
);
const onClickPropertySignature = types.tsPropertySignature(
types.Identifier('onClick'),
types.tsTypeAnnotation(
types.tsTypeReference(
types.Identifier('MouseEventHandler'),
types.tsTypeParameterInstantiation([
types.tsTypeReference(types.Identifier('HTMLAnchorElement')),
])
)
)
);
hrefPropertySignature.optional = onClickPropertySignature.optional = true;
let identifier;
switch (node.type) {
case 'TSTypeReference':
identifier = node.typeName;
break;
case 'Identifier':
identifier = node;
break;
}
// resolve React.* identifiers
if (
identifier.type === 'TSQualifiedName' &&
identifier.left.name === 'React'
) {
return resolveIdentifierToPropTypes(identifier.right, state);
}
// React Component
switch (identifier.name) {
// PropTypes.element
case 'Component':
case 'ReactElement':
case 'ComponentClass':
case 'SFC':
case 'StatelessComponent':
return types.memberExpression(
types.identifier('PropTypes'),
types.identifier('element')
);
// PropTypes.node
case 'ReactChild':
case 'ReactNode':
return types.memberExpression(
types.identifier('PropTypes'),
types.identifier('node')
);
case 'ComponentType':
return types.memberExpression(
types.identifier('PropTypes'),
types.identifier('elementType')
);
case 'JSXElementConstructor':
return types.memberExpression(
types.identifier('PropTypes'),
types.identifier('func') // this is more accurately `elementType` but our peerDependency version of prop-types doesn't have it
);
}
if (identifier.name === 'Array') return resolveArrayToPropTypes(node, state);
if (identifier.name === 'Omit') return resolveOmitToPropTypes(node, state);
if (identifier.name === 'MouseEventHandler')
return buildPropTypePrimitiveExpression(types, 'func');
if (identifier.name === 'Function')
return buildPropTypePrimitiveExpression(types, 'func');
if (identifier.name === 'PropsForAnchor' && node.typeParameters != null) {
return getPropTypesForNode(
{
type: 'TSIntersectionType',
types: [
types.tsTypeLiteral([
hrefPropertySignature,
onClickPropertySignature,
]),
...node.typeParameters.params,
],
},
true,
state
);
}
if (identifier.name === 'PropsForButton' && node.typeParameters != null) {
return getPropTypesForNode(
{
type: 'TSIntersectionType',
types: [
types.tsTypeLiteral([onClickPropertySignature]),
...node.typeParameters.params,
],
},
true,
state
);
}
if (identifier.name === 'ExclusiveUnion') {
// We use ExclusiveUnion at the top level to exclusively discriminate between types
// propTypes itself must be an object so merge the union sets together as an intersection
// Any types that are optional or non-existant on one side must be optional after the union
const aPropType = getPropTypesForNode(
node.typeParameters.params[0],
true,
state
);
const bPropType = getPropTypesForNode(
node.typeParameters.params[1],
true,
state
);
const propsOnA = types.isCallExpression(aPropType)
? aPropType.arguments[0].properties
: [];
const propsOnB = types.isCallExpression(bPropType)
? bPropType.arguments[0].properties
: [];
// optional props is any prop that is optional or non-existant on one side
const optionalProps = new Set();
for (let i = 0; i < propsOnA.length; i++) {
const property = propsOnA[i];
const propertyName = property.key.name;
const isOptional = !isPropTypeRequired(types, property.value);
const existsOnB =
propsOnB.find((property) => property.key.name === propertyName) != null;
if (isOptional || !existsOnB) {
optionalProps.add(propertyName);
}
}
for (let i = 0; i < propsOnB.length; i++) {
const property = propsOnB[i];
const propertyName = property.key.name;
const isOptional = !isPropTypeRequired(types, property.value);
const existsOnA =
propsOnA.find((property) => property.key.name === propertyName) != null;
if (isOptional || !existsOnA) {
optionalProps.add(propertyName);
}
}
const propTypes = getPropTypesForNode(
{
type: 'TSIntersectionType',
types: node.typeParameters.params,
},
true,
state
);
if (types.isCallExpression(propTypes)) {
// apply the optionals
const properties = propTypes.arguments[0].properties;
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
if (optionalProps.has(property.key.name)) {
property.value = makePropTypeOptional(types, property.value);
}
}
}
return propTypes;
}
if (identifier.name === 'OneOf') {
// the second type parameter is ignorable as it is a subset of the first,
// and the OneOf operation cannot be well-described by proptypes
const [sourceTypes] = node.typeParameters.params;
return getPropTypesForNode(sourceTypes, true, state);
}
// Lookup this identifier from types/interfaces defined in code
const identifierDefinition = typeDefinitions[identifier.name];
if (identifierDefinition) {
if (inflightResolves.has(identifier.name)) {
return types.memberExpression(
types.identifier('PropTypes'),
types.identifier('any')
);
}
inflightResolves.add(identifier.name);
state.set('inflightResolves', inflightResolves);
const propType = getPropTypesForNode(identifierDefinition, true, state);
inflightResolves.delete(identifier.name);
state.set('inflightResolves', inflightResolves);
return propType;
} else {
return null;
}
}
/**
* Small DRY abstraction to return the AST of PropTypes.${typeName}
* @param types
* @param typeName
* @returns AST
*/
function buildPropTypePrimitiveExpression(types, typeName) {
return types.memberExpression(
types.identifier('PropTypes'),
types.identifier(typeName)
);
}
function isPropTypeRequired(types, propType) {
return (
types.isMemberExpression(propType) &&
types.isIdentifier(propType.property) &&
propType.property.name === 'isRequired'
);
}
function makePropTypeRequired(types, propType) {
// can't make literals required no matter how hard we try
if (types.isLiteral(propType) === true) return propType;
return types.memberExpression(propType, types.identifier('isRequired'));
}
function makePropTypeOptional(types, propType) {
if (isPropTypeRequired(types, propType)) {
// strip the .isRequired member expression
return propType.object;
}
return propType;
}
function areExpressionsIdentical(a, b) {
const aCode = babelCore.transformFromAst(
babelCore.types.program([
babelCore.types.expressionStatement(
babelCore.types.removeComments(babelCore.types.cloneDeep(a))
),
])
).code;
const bCode = babelCore.transformFromAst(
babelCore.types.program([
babelCore.types.expressionStatement(
babelCore.types.removeComments(babelCore.types.cloneDeep(b))
),
])
).code;
return aCode === bCode;
}
/**
* Converts any literal node (StringLiteral, etc) into a PropTypes.oneOF([ literalNode ])
* so it can be used in any proptype expression
*/
function convertLiteralToOneOf(types, literalNode) {
return types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('oneOf')
),
[types.arrayExpression([literalNode])]
);
}
/**
* Heavy lifter to generate the proptype AST for a node. Initially called by `processComponentDeclaration`,
* its return value is set as the component's `propTypes` value. This function calls itself recursively to translate
* the whole type/interface AST into prop types.
* @param node
* @param optional
* @param state
* @returns AST | null
*/
function getPropTypesForNode(node, optional, state) {
const types = state.get('types');
if (node.isAlreadyResolved === true) return node;
let propType;
switch (node.type) {
// a type value by identifier
case 'TSTypeReference':
propType = resolveIdentifierToPropTypes(node, state);
break;
// a type annotation on a node
// Array<Foo>
// ^^^ Foo
case 'TSTypeAnnotation':
propType = getPropTypesForNode(node.typeAnnotation, true, state);
if (
types.isLiteral(propType) ||
(types.isIdentifier(propType) && propType.name === 'undefined')
) {
// can't use a literal straight, wrap it with PropTypes.oneOf([ the_literal ])
propType = convertLiteralToOneOf(types, propType);
}
break;
// Foo['bar']
case 'TSIndexedAccessType':
// verify the type of index access
if (types.isTSLiteralType(node.indexType) === false) break;
const indexedName = node.indexType.literal.value;
const objectPropType = getPropTypesForNode(node.objectType, true, state);
// verify this came out as a PropTypes.shape(), which we can pick the indexed property off of
if (
types.isCallExpression(objectPropType) &&
types.isMemberExpression(objectPropType.callee) &&
types.isIdentifier(objectPropType.callee.object) &&
objectPropType.callee.object.name === 'PropTypes' &&
types.isIdentifier(objectPropType.callee.property) &&
objectPropType.callee.property.name === 'shape'
) {
const shapeProps = objectPropType.arguments[0].properties;
for (let i = 0; i < shapeProps.length; i++) {
const prop = shapeProps[i];
if (prop.key.name === indexedName) {
propType = makePropTypeOptional(types, prop.value);
break;
}
}
}
break;
// translates intersections (Foo & Bar & Baz) to a shape with the types' members (Foo, Bar, Baz) merged together
case 'TSIntersectionType':
const usableNodes = [...node.types].filter((node) => {
const nodePropTypes = getPropTypesForNode(node, true, state);
if (
types.isMemberExpression(nodePropTypes) &&
nodePropTypes.object.name === 'PropTypes' &&
nodePropTypes.property.name === 'any'
) {
return false;
}
// validate that this resulted in a shape or oneOfType, otherwise we don't know how to extract/merge the values
if (
!types.isCallExpression(nodePropTypes) ||
!types.isMemberExpression(nodePropTypes.callee) ||
nodePropTypes.callee.object.name !== 'PropTypes' ||
(nodePropTypes.callee.property.name !== 'shape' &&
nodePropTypes.callee.property.name !== 'oneOfType')
) {
return false;
}
return true;
});
// merge the resolved proptypes for each intersection member into one object, mergedProperties
const mergedProperties = usableNodes.reduce((mergedProperties, node) => {
let nodePropTypes = getPropTypesForNode(node, true, state);
// if this is a `oneOfType` extract those properties into a `shape`
if (
types.isCallExpression(nodePropTypes) &&
types.isMemberExpression(nodePropTypes.callee) &&
nodePropTypes.callee.object.name === 'PropTypes' &&
nodePropTypes.callee.property.name === 'oneOfType'
) {
const properties = nodePropTypes.arguments[0].elements
.map((propType) => {
// This exists on a oneOfType which must be expressed as an optional proptype
propType = makePropTypeOptional(types, propType);
// validate we're working with a shape, otherwise we can't merge properties
if (
!types.isCallExpression(propType) ||
!types.isMemberExpression(propType.callee) ||
propType.callee.object.name !== 'PropTypes' ||
propType.callee.property.name !== 'shape'
) {
return null;
}
// extract all of the properties from this group and make them optional
return propType.arguments[0].properties.map((property) => {
property.value = makePropTypeOptional(types, property.value);
return property;
});
})
.filter((x) => x !== null)
.reduce((allProperties, properties) => {
return [...allProperties, ...properties];
}, []);
nodePropTypes = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('shape')
),
[types.objectExpression(properties)]
);
}
// iterate over this type's members, adding them (and their comments) to `mergedProperties`
const typeProperties = nodePropTypes.arguments[0].properties; // properties on the ObjectExpression passed to PropTypes.shape()
for (let i = 0; i < typeProperties.length; i++) {
const typeProperty = typeProperties[i];
// this member may be duplicated between two shapes, e.g. Foo = { buzz: string } & Bar = { buzz: string }
// either or both may have leading comments and we want to forward all comments to the generated prop type
const leadingComments = [
...(typeProperty.leadingComments || []),
...((mergedProperties[typeProperty.key.name]
? mergedProperties[typeProperty.key.name].leadingComments
: null) || []),
];
let propTypeValue = typeProperty.value;
if (
types.isLiteral(propTypeValue) ||
(types.isIdentifier(propTypeValue) &&
propTypeValue.name === 'undefined')
) {
// can't use a literal straight, wrap it with PropTypes.oneOf([ the_literal ])
propTypeValue = convertLiteralToOneOf(types, propTypeValue);
}
// if this property has already been found, the only action is to potentially change it to optional
if (mergedProperties.hasOwnProperty(typeProperty.key.name)) {
const existing = mergedProperties[typeProperty.key.name];
if (!areExpressionsIdentical(existing, typeProperty.value)) {
mergedProperties[
typeProperty.key.name
] = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('oneOfType')
),
[types.arrayExpression([existing, propTypeValue])]
);
if (
isPropTypeRequired(types, existing) &&
isPropTypeRequired(types, typeProperty.value)
) {
mergedProperties[typeProperty.key.name] = makePropTypeRequired(
types,
mergedProperties[typeProperty.key.name]
);
}
}
} else {
// property hasn't been seen yet, add it
mergedProperties[typeProperty.key.name] = propTypeValue;
}
mergedProperties[
typeProperty.key.name
].leadingComments = leadingComments;
}
return mergedProperties;
}, {});
const propertyKeys = Object.keys(mergedProperties);
// if there is one or more members on `mergedProperties` then use PropTypes.shape,
// otherwise none of the types were resolvable and fallback to PropTypes.any
if (propertyKeys.length > 0) {
// At least one type/interface was resolved to proptypes
propType = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('shape')
),
[
types.objectExpression(
propertyKeys.map((propKey) => {
const objectProperty = types.objectProperty(
types.identifier(propKey),
mergedProperties[propKey]
);
objectProperty.leadingComments =
mergedProperties[propKey].leadingComments;
mergedProperties[propKey].leadingComments = null;
return objectProperty;
})
),
]
);
} else {
// None of the types were resolveable, return with PropTypes.any
propType = types.memberExpression(
types.identifier('PropTypes'),
types.identifier('any')
);
}
break;
// translate an interface definition into a PropTypes.shape
case 'TSInterfaceBody':
propType = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('shape')
),
[
types.objectExpression(
node.body
// This helps filter out index signatures from interfaces,
// which don't translate to prop types.
.filter(
(property) =>
property.key != null &&
!types.isTSNeverKeyword(
property.typeAnnotation.typeAnnotation
)
)
.map((property) => {
let propertyPropType =
property.type === 'TSMethodSignature'
? getPropTypesForNode(
{ type: 'TSFunctionType' },
property.optional,
state
)
: getPropTypesForNode(
property.typeAnnotation,
property.optional,
state
);
if (
types.isLiteral(propertyPropType) ||
(types.isIdentifier(propertyPropType) &&
propertyPropType.name === 'undefined')
) {
propertyPropType = convertLiteralToOneOf(
types,
propertyPropType
);
if (!property.optional) {
propertyPropType = makePropTypeRequired(
types,
propertyPropType
);
}
}
const objectProperty = types.objectProperty(
types.identifier(
property.key.name || `"${property.key.value}"`
),
propertyPropType
);
if (property.leadingComments != null) {
objectProperty.leadingComments = property.leadingComments.map(
({ type, value }) => ({ type, value })
);
}
return objectProperty;
})
),
]
);
break;
// resolve a type operator (keyword) that operates on a value
// currently only supporting `keyof typeof [object variable]`
case 'TSTypeOperator':
if (
node.operator === 'keyof' &&
node.typeAnnotation.type === 'TSTypeQuery'
) {
const typeDefinitions = state.get('typeDefinitions');
const typeDefinition =
typeDefinitions[node.typeAnnotation.exprName.name];
if (typeDefinition != null) {
propType = getPropTypesForNode(typeDefinition, true, state);
}
}
break;
// invoked only by `keyof typeof` TSTypeOperator, safe to form PropTypes.oneOf(Object.keys(variable))
case 'ObjectExpression':
propType = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('oneOf')
),
[
types.arrayExpression(
node.properties.map((property) =>
types.stringLiteral(
property.key.name || property.key.name || property.key.value
)
)
),
]
);
break;
// translate a type definition into a PropTypes.shape
case 'TSTypeLiteral':
propType = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('shape')
),
[
types.objectExpression(
node.members
.map((property) => {
// skip never keyword
if (
types.isTSNeverKeyword(property.typeAnnotation.typeAnnotation)
)
return null;
// skip TS index signatures
if (types.isTSIndexSignature(property)) return null;
const propertyPropType =
property.type === 'TSMethodSignature'
? getPropTypesForNode(
{ type: 'TSFunctionType' },
property.optional,
state
)
: getPropTypesForNode(
property.typeAnnotation,
property.optional,
state
);
const objectProperty = types.objectProperty(
types.identifier(
property.key.name || `"${property.key.value}"`
),
propertyPropType
);
if (property.leadingComments != null) {
objectProperty.leadingComments = property.leadingComments.map(
({ type, value }) => ({ type, value })
);
}
return objectProperty;
})
.filter((x) => x != null)
),
]
);
break;
// translate a union (Foo | Bar | Baz) into PropTypes.oneOf or PropTypes.oneOfType, depending on
// the kind of members in the union (no literal values, all literals, or mixed)
// literal values are extracted into a `oneOf`, if all members are literals this oneOf is used
// otherwise `oneOfType` is used - if there are any literal values it contains the literals' `oneOf`
case 'TSUnionType':
const tsUnionTypes = node.types.map((node) =>
getPropTypesForNode(node, false, state)
);
// `tsUnionTypes` could be:
// 1. all non-literal values (string | number)
// 2. all literal values ("foo" | "bar")
// 3. a mix of value types ("foo" | number)
// this reduce finds any literal values and groups them into a oneOf node
const reducedUnionTypes = tsUnionTypes.reduce(
(foundTypes, tsUnionType) => {
if (
types.isLiteral(tsUnionType) ||
(types.isIdentifier(tsUnionType) &&
tsUnionType.name === 'undefined')
) {
if (foundTypes.oneOfPropType == null) {
foundTypes.oneOfPropType = types.arrayExpression([]);
foundTypes.unionTypes.push(
types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('oneOf')
),
[foundTypes.oneOfPropType]
)
);
}
// this is a literal value, move to the oneOfPropType argument
foundTypes.oneOfPropType.elements.push(tsUnionType);
} else {
// this is a non-literal type
foundTypes.unionTypes.push(tsUnionType);
}
return foundTypes;
},
{
unionTypes: [],
oneOfPropType: null,
}
);
// if there is only one member on the reduced union types, _and_a oneOf proptype was created,
// then that oneOf proptype is the one member on union types, and can be be extracted out
// e.g.
// PropTypes.oneOf([PropTypes.oneOf(['red', 'blue'])])
// ->
// PropTypes.oneOf(['red', 'blue'])
if (
reducedUnionTypes.unionTypes.length === 1 &&
reducedUnionTypes.oneOfPropType != null
) {
// the only proptype is a `oneOf`, use only that
propType = reducedUnionTypes.unionTypes[0];
} else {
propType = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('oneOfType')
),
[types.arrayExpression(reducedUnionTypes.unionTypes)]
);
}
break;
// translate enum to PropTypes.oneOf
case 'TSEnumDeclaration':
const memberTypes = node.members.map((member) =>
getPropTypesForNode(member, true, state)
);
propType = types.callExpression(
types.memberExpression(
types.identifier('PropTypes'),
types.identifier('oneOf')
),
[types.arrayExpression(memberTypes)]
);
break;
// translate an interface to PropTypes
case 'TSInterfaceDeclaration':
const { body, extends: extensions } = node;
// if the interface doesn't extend anything use just the interface body
if (extensions == null) {
propType = getPropTypesForNode(body, true, state);
} else {
// fake a TSIntersectionType to merge everything together
propType = getPropTypesForNode(
{
type: 'TSIntersectionType',
types: [body, ...extensions],
},
true,
state
);
}
break;
// simple pass-through wrapper
case 'TSExpressionWithTypeArguments':
propType = resolveIdentifierToPropTypes(node.expression, state);
break;
// an enum member is a simple wrapper around a type definition
case 'TSEnumMember':
propType = getPropTypesForNode(node.initializer, optional, state);
break;
// translate `string` to `PropTypes.string`
case 'TSStringKeyword':
propType = buildPropTypePrimitiveExpression(types, 'string');
break;
// translate `number` to `PropTypes.number`
case 'TSNumberKeyword':
propType = buildPropTypePrimitiveExpression(types, 'number');
break;
// translate `boolean` to `PropTypes.bool`
case 'TSBooleanKeyword':
propType = buildPropTypePrimitiveExpression(types, 'bool');
break;
// translate any function type to `PropTypes.func`
case 'TSFunctionType':
propType = buildPropTypePrimitiveExpression(types, 'func');
break;