forked from jsx-eslint/eslint-plugin-react
/
default-props-match-prop-types.js
507 lines (432 loc) · 16 KB
/
default-props-match-prop-types.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
/**
* @fileOverview Enforce all defaultProps are defined in propTypes
* @author Vitor Balocco
* @author Roy Sutton
*/
'use strict';
const Components = require('../util/Components');
const variableUtil = require('../util/variable');
const annotations = require('../util/annotations');
const astUtil = require('../util/ast');
const propsUtil = require('../util/props');
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Enforce all defaultProps are defined and not "required" in propTypes.',
category: 'Best Practices',
url: docsUrl('default-props-match-prop-types')
},
schema: [{
type: 'object',
properties: {
allowRequiredDefaults: {
default: false,
type: 'boolean'
}
},
additionalProperties: false
}]
},
create: Components.detect((context, components, utils) => {
const configuration = context.options[0] || {};
const allowRequiredDefaults = configuration.allowRequiredDefaults || false;
const propWrapperFunctions = new Set(context.settings.propWrapperFunctions || []);
// Used to track the type annotations in scope.
// Necessary because babel's scopes do not track type annotations.
let stack = null;
/**
* Try to resolve the node passed in to a variable in the current scope. If the node passed in is not
* an Identifier, then the node is simply returned.
* @param {ASTNode} node The node to resolve.
* @returns {ASTNode|null} Return null if the value could not be resolved, ASTNode otherwise.
*/
function resolveNodeValue(node) {
if (node.type === 'Identifier') {
return variableUtil.findVariableByName(context, node.name);
}
if (
node.type === 'CallExpression' &&
propWrapperFunctions.has(node.callee.name) &&
node.arguments && node.arguments[0]
) {
return resolveNodeValue(node.arguments[0]);
}
return node;
}
/**
* Helper for accessing the current scope in the stack.
* @param {string} key The name of the identifier to access. If omitted, returns the full scope.
* @param {ASTNode} value If provided sets the new value for the identifier.
* @returns {Object|ASTNode} Either the whole scope or the ASTNode associated with the given identifier.
*/
function typeScope(key, value) {
if (arguments.length === 0) {
return stack[stack.length - 1];
} else if (arguments.length === 1) {
return stack[stack.length - 1][key];
}
stack[stack.length - 1][key] = value;
return value;
}
/**
* Tries to find the definition of a GenericTypeAnnotation in the current scope.
* @param {ASTNode} node The node GenericTypeAnnotation node to resolve.
* @return {ASTNode|null} Return null if definition cannot be found, ASTNode otherwise.
*/
function resolveGenericTypeAnnotation(node) {
if (node.type !== 'GenericTypeAnnotation' || node.id.type !== 'Identifier') {
return null;
}
return variableUtil.findVariableByName(context, node.id.name) || typeScope(node.id.name);
}
function resolveUnionTypeAnnotation(node) {
// Go through all the union and resolve any generic types.
return node.types.map(annotation => {
if (annotation.type === 'GenericTypeAnnotation') {
return resolveGenericTypeAnnotation(annotation);
}
return annotation;
});
}
/**
* Extracts a PropType from an ObjectExpression node.
* @param {ASTNode} objectExpression ObjectExpression node.
* @returns {Object[]} Array of PropType object representations, to be consumed by `addPropTypesToComponent`.
*/
function getPropTypesFromObjectExpression(objectExpression) {
const props = objectExpression.properties.filter(property => property.type !== 'ExperimentalSpreadProperty' && property.type !== 'SpreadElement');
return props.map(property => ({
name: property.key.name,
isRequired: propsUtil.isRequiredPropType(property.value),
node: property
}));
}
/**
* Handles Props defined in IntersectionTypeAnnotation nodes
* e.g. type Props = PropsA & PropsB
* @param {ASTNode} intersectionTypeAnnotation ObjectExpression node.
* @returns {Object[]}
*/
function getPropertiesFromIntersectionTypeAnnotationNode(annotation) {
return annotation.types.reduce((properties, type) => {
annotation = resolveGenericTypeAnnotation(type);
if (annotation && annotation.id) {
annotation = variableUtil.findVariableByName(context, annotation.id.name);
}
if (!annotation || !annotation.properties) {
return properties;
}
return properties.concat(annotation.properties);
}, []);
}
/**
* Extracts a PropType from a TypeAnnotation node.
* @param {ASTNode} node TypeAnnotation node.
* @returns {Object[]} Array of PropType object representations, to be consumed by `addPropTypesToComponent`.
*/
function getPropTypesFromTypeAnnotation(node) {
let properties = [];
switch (node.typeAnnotation.type) {
case 'GenericTypeAnnotation':
let annotation = resolveGenericTypeAnnotation(node.typeAnnotation);
if (annotation && annotation.type === 'IntersectionTypeAnnotation') {
properties = getPropertiesFromIntersectionTypeAnnotationNode(annotation);
} else {
if (annotation && annotation.id) {
annotation = variableUtil.findVariableByName(context, annotation.id.name);
}
properties = annotation ? (annotation.properties || []) : [];
}
break;
case 'UnionTypeAnnotation':
const union = resolveUnionTypeAnnotation(node.typeAnnotation);
properties = union.reduce((acc, curr) => {
if (!curr) {
return acc;
}
return acc.concat(curr.properties);
}, []);
break;
case 'ObjectTypeAnnotation':
properties = node.typeAnnotation.properties;
break;
default:
properties = [];
break;
}
const props = properties.filter(property => property.type === 'ObjectTypeProperty');
return props.map(property => {
// the `key` property is not present in ObjectTypeProperty nodes, so we need to get the key name manually.
const tokens = context.getFirstTokens(property, 1);
const name = tokens[0].value;
return {
name: name,
isRequired: !property.optional,
node: property
};
});
}
/**
* Adds propTypes to the component passed in.
* @param {ASTNode} component The component to add the propTypes to.
* @param {Object[]} propTypes propTypes to add to the component.
* @returns {void}
*/
function addPropTypesToComponent(component, propTypes) {
const props = component.propTypes || [];
components.set(component.node, {
propTypes: props.concat(propTypes)
});
}
/**
* Tries to find a props type annotation in a stateless component.
* @param {ASTNode} node The AST node to look for a props type annotation.
* @return {void}
*/
function handleStatelessComponent(node) {
if (!node.params || !node.params.length || !annotations.isAnnotatedFunctionPropsDeclaration(node, context)) {
return;
}
// find component this props annotation belongs to
const component = components.get(utils.getParentStatelessComponent());
if (!component) {
return;
}
addPropTypesToComponent(component, getPropTypesFromTypeAnnotation(node.params[0].typeAnnotation, context));
}
function handlePropTypeAnnotationClassProperty(node) {
// find component this props annotation belongs to
const component = components.get(utils.getParentES6Component());
if (!component) {
return;
}
addPropTypesToComponent(component, getPropTypesFromTypeAnnotation(node.typeAnnotation, context));
}
function isPropTypeAnnotation(node) {
return (astUtil.getPropertyName(node) === 'props' && !!node.typeAnnotation);
}
function propFromName(propTypes, name) {
return propTypes.find(prop => prop.name === name);
}
/**
* Reports all defaultProps passed in that don't have an appropriate propTypes counterpart.
* @param {Object[]} propTypes Array of propTypes to check.
* @param {Object} defaultProps Object of defaultProps to check. Keys are the props names.
* @return {void}
*/
function reportInvalidDefaultProps(propTypes, defaultProps) {
// If this defaultProps is "unresolved" or the propTypes is undefined, then we should ignore
// this component and not report any errors for it, to avoid false-positives with e.g.
// external defaultProps/propTypes declarations or spread operators.
if (defaultProps === 'unresolved' || !propTypes) {
return;
}
Object.keys(defaultProps).forEach(defaultPropName => {
const defaultProp = defaultProps[defaultPropName];
const prop = propFromName(propTypes, defaultPropName);
if (prop && (allowRequiredDefaults || !prop.isRequired)) {
return;
}
if (prop) {
context.report(
defaultProp.node,
'defaultProp "{{name}}" defined for isRequired propType.',
{name: defaultPropName}
);
} else {
context.report(
defaultProp.node,
'defaultProp "{{name}}" has no corresponding propTypes declaration.',
{name: defaultPropName}
);
}
});
}
// --------------------------------------------------------------------------
// Public API
// --------------------------------------------------------------------------
return {
MemberExpression: function(node) {
const isPropType = propsUtil.isPropTypesDeclaration(node);
if (!isPropType) {
return;
}
// find component this propTypes/defaultProps belongs to
const component = utils.getRelatedComponent(node);
if (!component) {
return;
}
// e.g.:
// MyComponent.propTypes = {
// foo: React.PropTypes.string.isRequired,
// bar: React.PropTypes.string
// };
//
// or:
//
// MyComponent.propTypes = myPropTypes;
if (node.parent.type === 'AssignmentExpression') {
const expression = resolveNodeValue(node.parent.right);
if (expression && expression.type === 'ObjectExpression') {
addPropTypesToComponent(component, getPropTypesFromObjectExpression(expression));
}
return;
}
// e.g.:
// MyComponent.propTypes.baz = React.PropTypes.string;
if (node.parent.type === 'MemberExpression' && node.parent.parent &&
node.parent.parent.type === 'AssignmentExpression') {
addPropTypesToComponent(component, [{
name: node.parent.property.name,
isRequired: propsUtil.isRequiredPropType(node.parent.parent.right),
node: node.parent.parent
}]);
}
},
// e.g.:
// class Hello extends React.Component {
// static get propTypes() {
// return {
// name: React.PropTypes.string
// };
// }
// static get defaultProps() {
// return {
// name: 'Dean'
// };
// }
// render() {
// return <div>Hello {this.props.name}</div>;
// }
// }
MethodDefinition: function(node) {
if (!node.static || node.kind !== 'get') {
return;
}
const isPropType = propsUtil.isPropTypesDeclaration(node);
if (!isPropType) {
return;
}
// find component this propTypes/defaultProps belongs to
const component = components.get(utils.getParentES6Component());
if (!component) {
return;
}
const returnStatement = utils.findReturnStatement(node);
if (!returnStatement) {
return;
}
const expression = resolveNodeValue(returnStatement.argument);
if (!expression || expression.type !== 'ObjectExpression') {
return;
}
addPropTypesToComponent(component, getPropTypesFromObjectExpression(expression));
},
// e.g.:
// class Greeting extends React.Component {
// render() {
// return (
// <h1>Hello, {this.props.foo} {this.props.bar}</h1>
// );
// }
// static propTypes = {
// foo: React.PropTypes.string,
// bar: React.PropTypes.string.isRequired
// };
// }
ClassProperty: function(node) {
if (isPropTypeAnnotation(node)) {
handlePropTypeAnnotationClassProperty(node);
return;
}
if (!node.static) {
return;
}
if (!node.value) {
return;
}
const propName = astUtil.getPropertyName(node);
const isPropType = propName === 'propTypes';
if (!isPropType) {
return;
}
// find component this propTypes/defaultProps belongs to
const component = components.get(utils.getParentES6Component());
if (!component) {
return;
}
const expression = resolveNodeValue(node.value);
if (!expression || expression.type !== 'ObjectExpression') {
return;
}
addPropTypesToComponent(component, getPropTypesFromObjectExpression(expression));
},
// e.g.:
// React.createClass({
// render: function() {
// return <div>{this.props.foo}</div>;
// },
// propTypes: {
// foo: React.PropTypes.string.isRequired,
// },
// getDefaultProps: function() {
// return {
// foo: 'default'
// };
// }
// });
ObjectExpression: function(node) {
// find component this propTypes/defaultProps belongs to
const component = utils.isES5Component(node) && components.get(node);
if (!component) {
return;
}
// Search for the proptypes declaration
node.properties.forEach(property => {
if (property.type === 'ExperimentalSpreadProperty' || property.type === 'SpreadElement') {
return;
}
const isPropType = propsUtil.isPropTypesDeclaration(property);
if (isPropType && property.value.type === 'ObjectExpression') {
addPropTypesToComponent(component, getPropTypesFromObjectExpression(property.value));
return;
}
});
},
TypeAlias: function(node) {
typeScope(node.id.name, node.right);
},
Program: function() {
stack = [{}];
},
BlockStatement: function () {
stack.push(Object.create(typeScope()));
},
'BlockStatement:exit': function () {
stack.pop();
},
// Check for type annotations in stateless components
FunctionDeclaration: handleStatelessComponent,
ArrowFunctionExpression: handleStatelessComponent,
FunctionExpression: handleStatelessComponent,
'Program:exit': function() {
stack = null;
const list = components.list();
Object.keys(list).forEach(component => {
// If no defaultProps could be found, we don't report anything.
if (!list[component].defaultProps) {
return;
}
reportInvalidDefaultProps(
list[component].propTypes,
list[component].defaultProps || {}
);
});
}
};
})
};