forked from sindresorhus/eslint-plugin-unicorn
/
prefer-node-protocol.js
74 lines (67 loc) · 1.57 KB
/
prefer-node-protocol.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
'use strict';
const isBuiltinModule = require('is-builtin-module');
const {matches, STATIC_REQUIRE_SOURCE_SELECTOR} = require('./selectors/index.js');
const MESSAGE_ID = 'prefer-node-protocol';
const messages = {
[MESSAGE_ID]: 'Prefer `node:{{moduleName}}` over `{{moduleName}}`.',
};
const importExportSourceSelector = [
':matches(ImportDeclaration, ExportNamedDeclaration, ImportExpression)',
' > ',
'Literal.source',
].join('');
/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
const {checkRequire} = {
checkRequire: false,
...context.options[0],
};
const selectors = [importExportSourceSelector];
if (checkRequire) {
selectors.push(STATIC_REQUIRE_SOURCE_SELECTOR);
}
return {
[matches(selectors)](node) {
const {value} = node;
if (
typeof value !== 'string'
|| value.startsWith('node:')
|| !isBuiltinModule(value)
) {
return;
}
const firstCharacterIndex = node.range[0] + 1;
return {
node,
messageId: MESSAGE_ID,
data: {moduleName: value},
/** @param {import('eslint').Rule.RuleFixer} fixer */
fix: fixer => fixer.insertTextBeforeRange([firstCharacterIndex, firstCharacterIndex], 'node:'),
};
},
};
};
const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
checkRequire: {
type: 'boolean',
default: false,
},
},
},
];
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer using the `node:` protocol when importing Node.js builtin modules.',
},
fixable: 'code',
schema,
messages,
},
};