2 * @fileoverview Restrict usage of specified globals.
3 * @author BenoƮt Zugmeyer
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
16 description: "disallow specified global variables",
17 category: "Variables",
19 url: "https://eslint.org/docs/rules/no-restricted-globals"
32 name: { type: "string" },
33 message: { type: "string" }
36 additionalProperties: false
45 defaultMessage: "Unexpected use of '{{name}}'.",
46 // eslint-disable-next-line eslint-plugin/report-message-format
47 customMessage: "Unexpected use of '{{name}}'. {{customMessage}}"
53 // If no globals are restricted, we don't need to do anything
54 if (context.options.length === 0) {
58 const restrictedGlobalMessages = context.options.reduce((memo, option) => {
59 if (typeof option === "string") {
62 memo[option.name] = option.message;
69 * Report a variable to be used as a restricted global.
70 * @param {Reference} reference the variable reference
74 function reportReference(reference) {
75 const name = reference.identifier.name,
76 customMessage = restrictedGlobalMessages[name],
77 messageId = customMessage
82 node: reference.identifier,
92 * Check if the given name is a restricted global name.
93 * @param {string} name name of a variable
94 * @returns {boolean} whether the variable is a restricted global or not
97 function isRestricted(name) {
98 return Object.prototype.hasOwnProperty.call(restrictedGlobalMessages, name);
103 const scope = context.getScope();
105 // Report variables declared elsewhere (ex: variables defined as "global" by eslint)
106 scope.variables.forEach(variable => {
107 if (!variable.defs.length && isRestricted(variable.name)) {
108 variable.references.forEach(reportReference);
112 // Report variables not declared at all
113 scope.through.forEach(reference => {
114 if (isRestricted(reference.identifier.name)) {
115 reportReference(reference);