no-global-assign.js
2.91 KB
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
88
89
90
91
92
93
94
/**
* @fileoverview Rule to disallow assignments to native objects or read-only global variables
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow assignments to native objects or read-only global variables",
recommended: true,
url: "https://eslint.org/docs/rules/no-global-assign"
},
schema: [
{
type: "object",
properties: {
exceptions: {
type: "array",
items: { type: "string" },
uniqueItems: true
}
},
additionalProperties: false
}
],
messages: {
globalShouldNotBeModified: "Read-only global '{{name}}' should not be modified."
}
},
create(context) {
const config = context.options[0];
const exceptions = (config && config.exceptions) || [];
/**
* Reports write references.
* @param {Reference} reference A reference to check.
* @param {int} index The index of the reference in the references.
* @param {Reference[]} references The array that the reference belongs to.
* @returns {void}
*/
function checkReference(reference, index, references) {
const identifier = reference.identifier;
if (reference.init === false &&
reference.isWrite() &&
/*
* Destructuring assignments can have multiple default value,
* so possibly there are multiple writeable references for the same identifier.
*/
(index === 0 || references[index - 1].identifier !== identifier)
) {
context.report({
node: identifier,
messageId: "globalShouldNotBeModified",
data: {
name: identifier.name
}
});
}
}
/**
* Reports write references if a given variable is read-only builtin.
* @param {Variable} variable A variable to check.
* @returns {void}
*/
function checkVariable(variable) {
if (variable.writeable === false && !exceptions.includes(variable.name)) {
variable.references.forEach(checkReference);
}
}
return {
Program() {
const globalScope = context.getScope();
globalScope.variables.forEach(checkVariable);
}
};
}
};