2 * @fileoverview Restrict usage of specified globals.
3 * @author BenoƮt Zugmeyer
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const DEFAULT_MESSAGE_TEMPLATE = "Unexpected use of '{{name}}'.",
12 CUSTOM_MESSAGE_TEMPLATE = "Unexpected use of '{{name}}'. {{customMessage}}";
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
23 description: "disallow specified global variables",
24 category: "Variables",
26 url: "https://eslint.org/docs/rules/no-restricted-globals"
39 name: { type: "string" },
40 message: { type: "string" }
43 additionalProperties: false
54 // If no globals are restricted, we don't need to do anything
55 if (context.options.length === 0) {
59 const restrictedGlobalMessages = context.options.reduce((memo, option) => {
60 if (typeof option === "string") {
63 memo[option.name] = option.message;
70 * Report a variable to be used as a restricted global.
71 * @param {Reference} reference the variable reference
75 function reportReference(reference) {
76 const name = reference.identifier.name,
77 customMessage = restrictedGlobalMessages[name],
78 message = customMessage
79 ? CUSTOM_MESSAGE_TEMPLATE
80 : DEFAULT_MESSAGE_TEMPLATE;
83 node: reference.identifier,
93 * Check if the given name is a restricted global name.
94 * @param {string} name name of a variable
95 * @returns {boolean} whether the variable is a restricted global or not
98 function isRestricted(name) {
99 return Object.prototype.hasOwnProperty.call(restrictedGlobalMessages, name);
104 const scope = context.getScope();
106 // Report variables declared elsewhere (ex: variables defined as "global" by eslint)
107 scope.variables.forEach(variable => {
108 if (!variable.defs.length && isRestricted(variable.name)) {
109 variable.references.forEach(reportReference);
113 // Report variables not declared at all
114 scope.through.forEach(reference => {
115 if (isRestricted(reference.identifier.name)) {
116 reportReference(reference);