summaryrefslogtreecommitdiffstats
path: root/tools/lint/eslint/eslint-plugin-mozilla/lib/rules/use-static-import.js
blob: 8b68eca867204cd3cd13754be8582daec1be736c (plain)
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
/**
 * @fileoverview Require use of static imports where possible.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

"use strict";

const helpers = require("../helpers");

function isIdentifier(node, id) {
  return node && node.type === "Identifier" && node.name === id;
}

module.exports = {
  meta: {
    docs: {
      url: "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/use-static-import.html",
    },
    fixable: "code",
    messages: {
      useStaticImport:
        "Please use static import instead of ChromeUtils.importESModule",
    },
    schema: [],
    type: "suggestion",
  },

  create(context) {
    return {
      VariableDeclarator(node) {
        if (
          node.init?.type != "CallExpression" ||
          node.init?.callee?.type != "MemberExpression" ||
          !context.getFilename().endsWith(".sys.mjs") ||
          !helpers.isTopLevel(context.getAncestors())
        ) {
          return;
        }

        let callee = node.init.callee;

        if (
          isIdentifier(callee.object, "ChromeUtils") &&
          isIdentifier(callee.property, "importESModule") &&
          callee.parent.arguments.length == 1
        ) {
          let sourceCode = context.getSourceCode();
          let importItemSource;
          if (node.id.type != "ObjectPattern") {
            importItemSource = sourceCode.getText(node.id);
          } else {
            importItemSource = "{ ";
            let initial = true;
            for (let property of node.id.properties) {
              if (!initial) {
                importItemSource += ", ";
              }
              initial = false;
              if (property.key.name == property.value.name) {
                importItemSource += property.key.name;
              } else {
                importItemSource += `${property.key.name} as ${property.value.name}`;
              }
            }
            importItemSource += " }";
          }

          context.report({
            node: node.parent,
            messageId: "useStaticImport",
            fix(fixer) {
              return fixer.replaceText(
                node.parent,
                `import ${importItemSource} from ${sourceCode.getText(
                  callee.parent.arguments[0]
                )}`
              );
            },
          });
        }
      },
    };
  },
};