prefer-node-protocol.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const isBuiltinModule = require('is-builtin-module');
  3. const {matches, STATIC_REQUIRE_SOURCE_SELECTOR} = require('./selectors/index.js');
  4. const {replaceStringLiteral} = require('./fix/index.js');
  5. const MESSAGE_ID = 'prefer-node-protocol';
  6. const messages = {
  7. [MESSAGE_ID]: 'Prefer `node:{{moduleName}}` over `{{moduleName}}`.',
  8. };
  9. const importExportSourceSelector = [
  10. ':matches(ImportDeclaration, ExportNamedDeclaration, ImportExpression)',
  11. ' > ',
  12. 'Literal.source',
  13. ].join('');
  14. const selector = matches([
  15. importExportSourceSelector,
  16. STATIC_REQUIRE_SOURCE_SELECTOR,
  17. ]);
  18. const create = () => ({
  19. [selector](node) {
  20. const {value} = node;
  21. if (
  22. typeof value !== 'string'
  23. || value.startsWith('node:')
  24. || !isBuiltinModule(value)
  25. ) {
  26. return;
  27. }
  28. return {
  29. node,
  30. messageId: MESSAGE_ID,
  31. data: {moduleName: value},
  32. /** @param {import('eslint').Rule.RuleFixer} fixer */
  33. fix: fixer => replaceStringLiteral(fixer, node, 'node:', 0, 0),
  34. };
  35. },
  36. });
  37. /** @type {import('eslint').Rule.RuleModule} */
  38. module.exports = {
  39. create,
  40. meta: {
  41. type: 'suggestion',
  42. docs: {
  43. description: 'Prefer using the `node:` protocol when importing Node.js builtin modules.',
  44. },
  45. fixable: 'code',
  46. messages,
  47. },
  48. };