|
| 1 | +/** |
| 2 | + * @author Toru Nagashima |
| 3 | + * See LICENSE file in root directory for full license. |
| 4 | + */ |
| 5 | +"use strict" |
| 6 | + |
| 7 | +const { ReferenceTracker } = require("eslint-utils") |
| 8 | + |
| 9 | +/** |
| 10 | + * Verifier for `prefer-global/*` rules. |
| 11 | + */ |
| 12 | +class Verifier { |
| 13 | + /** |
| 14 | + * Initialize this instance. |
| 15 | + * @param {RuleContext} context The rule context to report. |
| 16 | + * @param {{modules:object,globals:object}} trackMap The track map. |
| 17 | + */ |
| 18 | + constructor(context, trackMap) { |
| 19 | + this.context = context |
| 20 | + this.trackMap = trackMap |
| 21 | + this.verify = |
| 22 | + context.options[0] === "never" |
| 23 | + ? this.verifyToPreferModules |
| 24 | + : this.verifyToPreferGlobals |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Verify the code to suggest the use of globals. |
| 29 | + * @returns {void} |
| 30 | + */ |
| 31 | + verifyToPreferGlobals() { |
| 32 | + const { context, trackMap } = this |
| 33 | + const tracker = new ReferenceTracker(context.getScope(), { |
| 34 | + mode: "legacy", |
| 35 | + }) |
| 36 | + |
| 37 | + for (const { node } of [ |
| 38 | + ...tracker.iterateCjsReferences(trackMap.modules), |
| 39 | + ...tracker.iterateEsmReferences(trackMap.modules), |
| 40 | + ]) { |
| 41 | + context.report({ node, messageId: "preferGlobal" }) |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Verify the code to suggest the use of modules. |
| 47 | + * @returns {void} |
| 48 | + */ |
| 49 | + verifyToPreferModules() { |
| 50 | + const { context, trackMap } = this |
| 51 | + const tracker = new ReferenceTracker(context.getScope()) |
| 52 | + |
| 53 | + for (const { node } of tracker.iterateGlobalReferences( |
| 54 | + trackMap.globals |
| 55 | + )) { |
| 56 | + context.report({ node, messageId: "preferModule" }) |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +module.exports = function checkForPreferGlobal(context, trackMap) { |
| 62 | + new Verifier(context, trackMap).verify() |
| 63 | +} |
0 commit comments