-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathno-danger.js
95 lines (78 loc) · 2.54 KB
/
no-danger.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
/**
* @fileoverview Prevent usage of dangerous JSX props
* @author Scott Andrews
*/
'use strict';
const has = require('hasown');
const fromEntries = require('object.fromentries/polyfill')();
const minimatch = require('minimatch');
const docsUrl = require('../util/docsUrl');
const jsxUtil = require('../util/jsx');
const report = require('../util/report');
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
const DANGEROUS_PROPERTY_NAMES = [
'dangerouslySetInnerHTML',
];
const DANGEROUS_PROPERTIES = fromEntries(DANGEROUS_PROPERTY_NAMES.map((prop) => [prop, prop]));
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
/**
* Checks if a JSX attribute is dangerous.
* @param {string} name - Name of the attribute to check.
* @returns {boolean} Whether or not the attribute is dangerous.
*/
function isDangerous(name) {
return has(DANGEROUS_PROPERTIES, name);
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
dangerousProp: 'Dangerous property \'{{name}}\' found',
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: 'Disallow usage of dangerous JSX properties',
category: 'Best Practices',
recommended: false,
url: docsUrl('no-danger'),
},
messages,
schema: [{
type: 'object',
properties: {
customComponentNames: {
items: {
type: 'string',
},
minItems: 0,
type: 'array',
uniqueItems: true,
},
},
}],
},
create(context) {
const configuration = context.options[0] || {};
const customComponentNames = configuration.customComponentNames || [];
return {
JSXAttribute(node) {
const functionName = node.parent.name.name;
const enableCheckingCustomComponent = customComponentNames.some((name) => minimatch(functionName, name));
if ((enableCheckingCustomComponent || jsxUtil.isDOMComponent(node.parent)) && isDangerous(node.name.name)) {
report(context, messages.dangerousProp, 'dangerousProp', {
node,
data: {
name: node.name.name,
},
});
}
},
};
},
};