-
-
Notifications
You must be signed in to change notification settings - Fork 353
/
no-unnecessary-polyfills.js
176 lines (151 loc) · 4.59 KB
/
no-unnecessary-polyfills.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
'use strict';
const path = require('node:path');
const readPkgUp = require('read-pkg-up');
const coreJsCompat = require('core-js-compat');
const {camelCase} = require('./utils/lodash.js');
const isStaticRequire = require('./ast/is-static-require.js');
const {data: compatData, entries: coreJsEntries} = coreJsCompat;
const MESSAGE_ID_POLYFILL = 'unnecessaryPolyfill';
const MESSAGE_ID_CORE_JS = 'unnecessaryCoreJsModule';
const messages = {
[MESSAGE_ID_POLYFILL]: 'Use built-in instead.',
[MESSAGE_ID_CORE_JS]:
'All polyfilled features imported from `{{coreJsModule}}` are available as built-ins. Use the built-ins instead.',
};
const additionalPolyfillPatterns = {
'es.promise.finally': '|(p-finally)',
'es.object.set-prototype-of': '|(setprototypeof)',
'es.string.code-point-at': '|(code-point-at)',
};
const prefixes = '(mdn-polyfills/|polyfill-)';
const suffixes = '(-polyfill)';
const delimiter = '(\\.|-|\\.prototype\\.|/)?';
const polyfills = Object.keys(compatData).map(feature => {
let [ecmaVersion, constructorName, methodName = ''] = feature.split('.');
if (ecmaVersion === 'es') {
ecmaVersion = '(es\\d*)';
}
constructorName = `(${constructorName}|${camelCase(constructorName)})`;
methodName &&= `(${methodName}|${camelCase(methodName)})`;
const methodOrConstructor = methodName || constructorName;
const patterns = [
`^((${prefixes}?(`,
methodName && `(${ecmaVersion}${delimiter}${constructorName}${delimiter}${methodName})|`, // Ex: es6-array-copy-within
methodName && `(${constructorName}${delimiter}${methodName})|`, // Ex: array-copy-within
`(${ecmaVersion}${delimiter}${constructorName}))`, // Ex: es6-array
`${suffixes}?)|`,
`(${prefixes}${methodOrConstructor}|${methodOrConstructor}${suffixes})`, // Ex: polyfill-copy-within / polyfill-promise
`${additionalPolyfillPatterns[feature] || ''})$`,
];
return {
feature,
pattern: new RegExp(patterns.join(''), 'i'),
};
});
function getTargets(options, dirname) {
if (options?.targets) {
return options.targets;
}
/** @type {readPkgUp.ReadResult | undefined} */
let packageResult;
try {
// It can fail if, for example, the package.json file has comments.
packageResult = readPkgUp.sync({normalize: false, cwd: dirname});
} catch {}
if (!packageResult) {
return;
}
const {browserlist, engines} = packageResult.packageJson;
return browserlist ?? engines;
}
function create(context) {
const targets = getTargets(context.options[0], path.dirname(context.filename));
if (!targets) {
return {};
}
let unavailableFeatures;
try {
unavailableFeatures = coreJsCompat({targets}).list;
} catch {
// This can happen if the targets are invalid or use unsupported syntax like `{node:'*'}`.
return {};
}
const checkFeatures = features => !features.every(feature => unavailableFeatures.includes(feature));
return {
Literal(node) {
if (
!(
(['ImportDeclaration', 'ImportExpression'].includes(node.parent.type) && node.parent.source === node)
|| (isStaticRequire(node.parent) && node.parent.arguments[0] === node)
)
) {
return;
}
const importedModule = node.value;
if (typeof importedModule !== 'string' || ['.', '/'].includes(importedModule[0])) {
return;
}
const coreJsModuleFeatures = coreJsEntries[importedModule.replace('core-js-pure', 'core-js')];
if (coreJsModuleFeatures) {
if (coreJsModuleFeatures.length > 1) {
if (checkFeatures(coreJsModuleFeatures)) {
return {
node,
messageId: MESSAGE_ID_CORE_JS,
data: {
coreJsModule: importedModule,
},
};
}
} else if (!unavailableFeatures.includes(coreJsModuleFeatures[0])) {
return {node, messageId: MESSAGE_ID_POLYFILL};
}
return;
}
const polyfill = polyfills.find(({pattern}) => pattern.test(importedModule));
if (polyfill) {
const [, namespace, method = ''] = polyfill.feature.split('.');
const [, features] = Object.entries(coreJsEntries).find(
entry => entry[0] === `core-js/full/${namespace}${method && '/'}${method}`,
);
if (checkFeatures(features)) {
return {node, messageId: MESSAGE_ID_POLYFILL};
}
}
},
};
}
const schema = [
{
type: 'object',
additionalProperties: false,
required: ['targets'],
properties: {
targets: {
oneOf: [
{
type: 'string',
},
{
type: 'array',
},
{
type: 'object',
},
],
},
},
},
];
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Enforce the use of built-in methods instead of unnecessary polyfills.',
},
schema,
messages,
},
};