-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
prop-types.js
537 lines (493 loc) · 16 KB
/
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
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
/**
* @fileoverview Prevent missing props validation in a React component definition
* @author Yannick Croissant
*/
'use strict';
// As for exceptions for props.children or props.className (and alike) look at
// https://github.com/yannickcr/eslint-plugin-react/issues/7
var componentUtil = require('../util/component');
var ComponentList = componentUtil.List;
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = function(context) {
var configuration = context.options[0] || {};
var ignored = configuration.ignore || [];
var componentList = new ComponentList();
var MISSING_MESSAGE = '\'{{name}}\' is missing in props validation';
var MISSING_MESSAGE_NAMED_COMP = '\'{{name}}\' is missing in props validation for {{component}}';
/**
* Checks if we are using a prop
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if we are using a prop, false if not.
*/
function isPropTypesUsage(node) {
return Boolean(
node.object.type === 'ThisExpression' &&
node.property.name === 'props'
);
}
/**
* Checks if we are declaring a prop
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if we are declaring a prop, false if not.
*/
function isPropTypesDeclaration(node) {
// Special case for class properties
// (babel-eslint does not expose property name so we have to rely on tokens)
if (node.type === 'ClassProperty') {
var tokens = context.getFirstTokens(node, 2);
if (tokens[0].value === 'propTypes' || tokens[1].value === 'propTypes') {
return true;
}
return false;
}
return Boolean(
node &&
node.name === 'propTypes'
);
}
/**
* Checks if the prop is ignored
* @param {String} name Name of the prop to check.
* @returns {Boolean} True if the prop is ignored, false if not.
*/
function isIgnored(name) {
return ignored.indexOf(name) !== -1;
}
/**
* Checks if the component must be validated
* @param {Object} component The component to process
* @returns {Boolean} True if the component must be validated, false if not.
*/
function mustBeValidated(component) {
return (
component &&
component.isReactComponent &&
component.usedPropTypes &&
!component.ignorePropsValidation
);
}
/**
* Internal: Checks if the prop is declared
* @param {Object} declaredPropTypes Description of propTypes declared in the current component
* @param {String[]} keyList Dot separated name of the prop to check.
* @returns {Boolean} True if the prop is declared, false if not.
*/
function _isDeclaredInComponent(declaredPropTypes, keyList) {
for (var i = 0, j = keyList.length; i < j; i++) {
var key = keyList[i];
var propType = (
// Check if this key is declared
declaredPropTypes[key] ||
// If not, check if this type accepts any key
declaredPropTypes.__ANY_KEY__
);
if (!propType) {
// If it's a computed property, we can't make any further analysis, but is valid
return key === '__COMPUTED_PROP__';
}
if (propType === true) {
return true;
}
// Consider every children as declared
if (propType.children === true) {
return true;
}
if (propType.acceptedProperties) {
return key in propType.acceptedProperties;
}
if (propType.type === 'union') {
// If we fall in this case, we know there is at least one complex type in the union
if (i + 1 >= j) {
// this is the last key, accept everything
return true;
}
// non trivial, check all of them
var unionTypes = propType.children;
var unionPropType = {};
for (var k = 0, z = unionTypes.length; k < z; k++) {
unionPropType[key] = unionTypes[k];
var isValid = _isDeclaredInComponent(
unionPropType,
keyList.slice(i)
);
if (isValid) {
return true;
}
}
// every possible union were invalid
return false;
}
declaredPropTypes = propType.children;
}
return true;
}
/**
* Checks if the prop is declared
* @param {Object} component The component to process
* @param {String} name Dot separated name of the prop to check.
* @returns {Boolean} True if the prop is declared, false if not.
*/
function isDeclaredInComponent(component, name) {
return _isDeclaredInComponent(
component.declaredPropTypes || {},
name.split('.')
);
}
/**
* Checks if the prop has spread operator.
* @param {ASTNode} node The AST node being marked.
* @returns {Boolean} True if the prop has spread operator, false if not.
*/
function hasSpreadOperator(node) {
var tokens = context.getTokens(node);
return tokens.length && tokens[0].value === '...';
}
/**
* Iterates through a properties node, like a customized forEach.
* @param {Object[]} properties Array of properties to iterate.
* @param {Function} fn Function to call on each property, receives property key
and property value. (key, value) => void
*/
function iterateProperties(properties, fn) {
if (properties.length && typeof fn === 'function') {
for (var i = 0, j = properties.length; i < j; i++) {
var node = properties[i];
var key = node.key;
var keyName = key.type === 'Identifier' ? key.name : key.value;
var value = node.value;
fn(keyName, value);
}
}
}
/**
* Creates the representation of the React propTypes for the component.
* The representation is used to verify nested used properties.
* @param {ASTNode} value Node of the React.PropTypes for the desired propery
* @return {Object|Boolean} The representation of the declaration, true means
* the property is declared without the need for further analysis.
*/
function buildReactDeclarationTypes(value) {
if (
value.type === 'MemberExpression' &&
value.property &&
value.property.name &&
value.property.name === 'isRequired'
) {
value = value.object;
}
// Verify React.PropTypes that are functions
if (
value.type === 'CallExpression' &&
value.callee &&
value.callee.property &&
value.callee.property.name &&
value.arguments &&
value.arguments.length > 0
) {
var callName = value.callee.property.name;
var argument = value.arguments[0];
switch (callName) {
case 'shape':
if (argument.type !== 'ObjectExpression') {
// Invalid proptype or cannot analyse statically
return true;
}
var shapeTypeDefinition = {
type: 'shape',
children: {}
};
iterateProperties(argument.properties, function(childKey, childValue) {
shapeTypeDefinition.children[childKey] = buildReactDeclarationTypes(childValue);
});
return shapeTypeDefinition;
case 'arrayOf':
return {
type: 'array',
children: {
// Accept only array prototype and computed properties
__ANY_KEY__: {
acceptedProperties: Array.prototype
},
__COMPUTED_PROP__: buildReactDeclarationTypes(argument)
}
};
case 'objectOf':
return {
type: 'object',
children: {
__ANY_KEY__: buildReactDeclarationTypes(argument)
}
};
case 'oneOfType':
if (
!argument.elements ||
!argument.elements.length
) {
// Invalid proptype or cannot analyse statically
return true;
}
var unionTypeDefinition = {
type: 'union',
children: []
};
for (var i = 0, j = argument.elements.length; i < j; i++) {
var type = buildReactDeclarationTypes(argument.elements[i]);
// keep only complex type
if (type !== true) {
if (type.children === true) {
// every child is accepted for one type, abort type analysis
unionTypeDefinition.children = true;
return unionTypeDefinition;
}
unionTypeDefinition.children.push(type);
}
}
if (unionTypeDefinition.length === 0) {
// no complex type found, simply accept everything
return true;
}
return unionTypeDefinition;
case 'instanceOf':
return {
type: 'instance',
// Accept all children because we can't know what type they are
children: true
};
case 'oneOf':
default:
return true;
}
}
if (
value.type === 'MemberExpression' &&
value.property &&
value.property.name
) {
var name = value.property.name;
// React propTypes with limited possible properties
var propertiesMap = {
array: Array.prototype,
bool: Boolean.prototype,
func: Function.prototype,
number: Number.prototype,
string: String.prototype
};
if (name in propertiesMap) {
return {
type: name,
children: {
__ANY_KEY__: {
acceptedProperties: propertiesMap[name]
}
}
};
}
}
// Unknown property or accepts everything (any, object, ...)
return true;
}
/**
* Mark a prop type as used
* @param {ASTNode} node The AST node being marked.
*/
function markPropTypesAsUsed(node, parentName) {
var type;
var name = node.parent.computed ?
'__COMPUTED_PROP__'
: node.parent.property && node.parent.property.name;
var fullName = parentName ? parentName + '.' + name : name;
if (node.parent.type === 'MemberExpression') {
markPropTypesAsUsed(node.parent, fullName);
}
if (name && !node.parent.computed) {
type = 'direct';
} else if (
node.parent.parent.declarations &&
node.parent.parent.declarations[0].id.properties &&
node.parent.parent.declarations[0].id.properties[0].key.name
) {
type = 'destructuring';
}
var component = componentList.getByNode(context, node);
var usedPropTypes = component && component.usedPropTypes || [];
switch (type) {
case 'direct':
// Ignore Object methods
if (Object.prototype[name]) {
break;
}
usedPropTypes.push({
name: fullName,
node: node.parent.property
});
break;
case 'destructuring':
var properties = node.parent.parent.declarations[0].id.properties;
for (var i = 0, j = properties.length; i < j; i++) {
if (hasSpreadOperator(properties[i])) {
continue;
}
usedPropTypes.push({
name: properties[i].key.name,
node: properties[i]
});
}
break;
default:
break;
}
componentList.set(context, node, {
usedPropTypes: usedPropTypes
});
}
/**
* Mark a prop type as declared
* @param {ASTNode} node The AST node being checked.
* @param {propTypes} node The AST node containing the proptypes
*/
function markPropTypesAsDeclared(node, propTypes) {
var component = componentList.getByNode(context, node);
var declaredPropTypes = component && component.declaredPropTypes || {};
var ignorePropsValidation = false;
switch (propTypes && propTypes.type) {
case 'ObjectExpression':
iterateProperties(propTypes.properties, function(key, value) {
declaredPropTypes[key] = buildReactDeclarationTypes(value);
});
break;
case 'MemberExpression':
// throw new Error(require("util").inspect(propTypes));
var curPropTypes = declaredPropTypes;
// Walk the list of properties, until we reach the assignment
// ie: ClassX.propTypes.a.b.c = ...
while (
propTypes &&
propTypes.parent.type !== 'AssignmentExpression' &&
propTypes.property &&
curPropTypes
) {
var key = propTypes.property.name;
if (key in curPropTypes) {
curPropTypes = curPropTypes[key].children;
propTypes = propTypes.parent;
} else {
// This will crash at runtime because we haven't seen this key before
// stop this and do not declare it
propTypes = null;
}
}
// console.log(propTypes, propTypes.property.name, propTypes.parent.right)
if (propTypes) {
curPropTypes[propTypes.property.name] =
buildReactDeclarationTypes(propTypes.parent.right);
}
break;
case null:
break;
default:
ignorePropsValidation = true;
break;
}
componentList.set(context, node, {
declaredPropTypes: declaredPropTypes,
ignorePropsValidation: ignorePropsValidation
});
}
/**
* Reports undeclared proptypes for a given component
* @param {Object} component The component to process
*/
function reportUndeclaredPropTypes(component) {
var name;
for (var i = 0, j = component.usedPropTypes.length; i < j; i++) {
name = component.usedPropTypes[i].name;
if (
isIgnored(name.split('.').pop()) ||
isDeclaredInComponent(component, name)
) {
continue;
}
context.report(
component.usedPropTypes[i].node,
component.name === componentUtil.DEFAULT_COMPONENT_NAME ? MISSING_MESSAGE : MISSING_MESSAGE_NAMED_COMP, {
name: name.replace(/\.__COMPUTED_PROP__/g, '[]'),
component: component.name
}
);
}
}
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
return {
ClassProperty: function(node) {
if (!isPropTypesDeclaration(node)) {
return;
}
markPropTypesAsDeclared(node, node.value);
},
MemberExpression: function(node) {
var type;
if (isPropTypesUsage(node)) {
type = 'usage';
} else if (isPropTypesDeclaration(node.property)) {
type = 'declaration';
}
switch (type) {
case 'usage':
markPropTypesAsUsed(node);
break;
case 'declaration':
var component = componentList.getByName(node.object.name);
if (!component) {
return;
}
markPropTypesAsDeclared(component.node, node.parent.right || node.parent);
break;
default:
break;
}
},
MethodDefinition: function(node) {
if (!isPropTypesDeclaration(node.key)) {
return;
}
var i = node.value.body.body.length - 1;
for (; i >= 0; i--) {
if (node.value.body.body[i].type === 'ReturnStatement') {
break;
}
}
markPropTypesAsDeclared(node, node.value.body.body[i].argument);
},
ObjectExpression: function(node) {
// Search for the proptypes declaration
node.properties.forEach(function(property) {
if (!isPropTypesDeclaration(property.key)) {
return;
}
markPropTypesAsDeclared(node, property.value);
});
},
'Program:exit': function() {
var list = componentList.getList();
// Report undeclared proptypes for all classes
for (var component in list) {
if (!list.hasOwnProperty(component) || !mustBeValidated(list[component])) {
continue;
}
reportUndeclaredPropTypes(list[component]);
}
},
ReturnStatement: function(node) {
if (!componentUtil.isReactComponent(context, node)) {
return;
}
componentList.set(context, node, {
isReactComponent: true
});
}
};
};