-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathprop-types.js
More file actions
333 lines (302 loc) · 10.7 KB
/
prop-types.js
File metadata and controls
333 lines (302 loc) · 10.7 KB
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
/**
* @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/jsx-eslint/eslint-plugin-react/issues/7
const values = require('object.values');
const Components = require('../util/Components');
const docsUrl = require('../util/docsUrl');
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
missingPropType: '\'{{name}}\' is missing in props validation',
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: 'Disallow missing props validation in a React component definition',
category: 'Best Practices',
recommended: true,
url: docsUrl('prop-types'),
},
messages,
schema: [{
type: 'object',
properties: {
ignore: {
type: 'array',
items: {
type: 'string',
},
},
customValidators: {
type: 'array',
items: {
type: 'string',
},
},
skipUndeclared: {
type: 'boolean',
},
skipUnexported: {
type: 'boolean',
},
},
additionalProperties: false,
}],
},
create: Components.detect((context, components) => {
const configuration = context.options[0] || {};
const ignored = configuration.ignore || [];
const skipUndeclared = configuration.skipUndeclared || false;
const skipUnexported = configuration.skipUnexported || false;
/**
* 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;
}
const exportedIdentifiers = new Set();
/**
* Get the name of a component from its node
* @param {Object} component The component to get the name for
* @returns {string | null} The component name, or null if unnamed
*/
function getComponentName(component) {
const node = component.node;
if (node.id) {
return node.id.name;
}
if (node.parent && node.parent.type === 'VariableDeclarator' && node.parent.id) {
return node.parent.id.name;
}
return null;
}
/**
* Checks if a component node is directly in an export declaration
* @param {ASTNode} node The component AST node
* @returns {boolean} True if the component is directly exported
*/
function isDirectlyExported(node) {
let current = node;
while (current && current.parent) {
const parentType = current.parent.type;
if (parentType === 'ExportDefaultDeclaration' || parentType === 'ExportNamedDeclaration') {
return true;
}
if (parentType === 'AssignmentExpression' && current.parent.right === current) {
const left = current.parent.left;
if (
left.type === 'MemberExpression'
&& left.object.type === 'Identifier'
&& (
(left.object.name === 'module' && left.property.name === 'exports')
|| left.object.name === 'exports'
)
) {
return true;
}
}
if (parentType === 'VariableDeclarator' || parentType === 'VariableDeclaration') {
current = current.parent;
continue; // eslint-disable-line no-continue
}
break;
}
return false;
}
/**
* Checks if a component is exported from the module
* @param {Object} component The component to check
* @returns {boolean} True if the component is exported
*/
function isComponentExported(component) {
if (isDirectlyExported(component.node)) {
return true;
}
const name = getComponentName(component);
return name != null && exportedIdentifiers.has(name);
}
/**
* 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) {
const isSkippedByConfig = skipUndeclared && typeof component.declaredPropTypes === 'undefined';
const isSkippedAsUnexported = skipUnexported && !isComponentExported(component);
return !!(
component
&& component.usedPropTypes
&& !component.ignorePropsValidation
&& !isSkippedByConfig
&& !isSkippedAsUnexported
);
}
/**
* 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 internalIsDeclaredInComponent(declaredPropTypes, keyList) {
for (let i = 0, j = keyList.length; i < j; i++) {
const key = keyList[i];
const propType = (
declaredPropTypes && (
// Check if this key is declared
(declaredPropTypes[key] // If not, check if this type accepts any key
|| declaredPropTypes.__ANY_KEY__) // eslint-disable-line no-underscore-dangle
)
);
if (!propType) {
// If it's a computed property, we can't make any further analysis, but is valid
return key === '__COMPUTED_PROP__';
}
if (typeof propType === 'object' && !propType.type) {
return true;
}
// Consider every children as declared
if (propType.children === true || propType.containsUnresolvedSpread || propType.containsIndexers) {
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
const unionTypes = propType.children;
const unionPropType = {};
for (let k = 0, z = unionTypes.length; k < z; k++) {
unionPropType[key] = unionTypes[k];
const isValid = internalIsDeclaredInComponent(
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 {ASTNode} node The AST node being checked.
* @param {string[]} names List of names of the prop to check.
* @returns {boolean} True if the prop is declared, false if not.
*/
function isDeclaredInComponent(node, names) {
while (node) {
const component = components.get(node);
const isDeclared = component && component.confidence >= 2
&& internalIsDeclaredInComponent(component.declaredPropTypes || {}, names);
if (isDeclared) {
return true;
}
node = node.parent;
}
return false;
}
/**
* Reports undeclared proptypes for a given component
* @param {Object} component The component to process
*/
function reportUndeclaredPropTypes(component) {
const undeclareds = component.usedPropTypes.filter((propType) => (
propType.node
&& !isIgnored(propType.allNames[0])
&& !isDeclaredInComponent(component.node, propType.allNames)
));
undeclareds.forEach((propType) => {
report(context, messages.missingPropType, 'missingPropType', {
node: propType.node,
data: {
name: propType.allNames.join('.').replace(/\.__COMPUTED_PROP__/g, '[]'),
},
});
});
}
/**
* @param {Object} component The current component to process
* @param {Array} list The all components to process
* @returns {boolean} True if the component is nested False if not.
*/
function checkNestedComponent(component, list) {
const componentIsMemo = component.node.callee && component.node.callee.name === 'memo';
const argumentIsForwardRef = component.node.arguments && component.node.arguments[0].callee && component.node.arguments[0].callee.name === 'forwardRef';
if (componentIsMemo && argumentIsForwardRef) {
const forwardComponent = list.find(
(innerComponent) => (
innerComponent.node.range[0] === component.node.arguments[0].range[0]
&& innerComponent.node.range[0] === component.node.arguments[0].range[0]
));
const isValidated = mustBeValidated(forwardComponent);
const isIgnorePropsValidation = forwardComponent.ignorePropsValidation;
return isIgnorePropsValidation || isValidated;
}
}
return {
ExportDefaultDeclaration(node) {
if (node.declaration && node.declaration.type === 'Identifier') {
exportedIdentifiers.add(node.declaration.name);
}
},
ExportNamedDeclaration(node) {
if (node.specifiers) {
node.specifiers.forEach((specifier) => {
if (specifier.local) {
exportedIdentifiers.add(specifier.local.name);
}
});
}
},
AssignmentExpression(node) {
if (
node.left.type === 'MemberExpression'
&& node.left.object.type === 'Identifier'
) {
if (
node.left.object.name === 'module'
&& node.left.property.name === 'exports'
&& node.right.type === 'Identifier'
) {
exportedIdentifiers.add(node.right.name);
}
if (
node.left.object.name === 'exports'
&& node.right.type === 'Identifier'
) {
exportedIdentifiers.add(node.right.name);
}
}
},
'Program:exit'() {
const list = components.list();
// Report undeclared proptypes for all classes
values(list)
.filter((component) => mustBeValidated(component))
.forEach((component) => {
if (checkNestedComponent(component, values(list))) return;
reportUndeclaredPropTypes(component);
});
},
};
}),
};