This repository was archived by the owner on Mar 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 509
/
Copy pathdisallow-quoted-keys-in-objects.js
111 lines (92 loc) · 2.7 KB
/
disallow-quoted-keys-in-objects.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* Disallows quoted keys in object if possible.
*
* Types: `Boolean`, `String` or `Object`
*
* Values:
*
* - `true` for strict mode
* - `"allButReserved"` (*deprecated* use `"allExcept": ["reserved"]`)
* - `Object`:
* - `"allExcept"` array of exceptions:
* - `"reserved"` allows ES3+ reserved words to remain quoted
* which is helpful when using this option with JSHint's `es3` flag.
*
* #### Example
*
* ```js
* "disallowQuotedKeysInObjects": true
* ```
*
* ##### Valid for mode `true`
*
* ```js
* var x = { a: { default: 1 } };
* ```
*
* ##### Valid for mode `{"allExcept": ["reserved"]}`
*
* ```js
* var x = {a: 1, 'default': 2};
* ```
*
* ##### Invalid
*
* ```js
* var x = {'a': 1};
* ```
*/
var assert = require('assert');
var reservedWords = require('reserved-words');
var cst = require('cst');
module.exports = function() {};
module.exports.prototype = {
configure: function(options) {
assert(
options === true || options === 'allButReserved' || typeof options === 'object',
this.getOptionName() + ' option requires a true value or an object'
);
this._exceptReserved = options === 'allButReserved';
if (Array.isArray(options.allExcept)) {
this._exceptReserved = options.allExcept.indexOf('reserved') !== -1;
}
},
getOptionName: function() {
return 'disallowQuotedKeysInObjects';
},
check: function(file, errors) {
var KEY_NAME_RE = /^(0|[1-9][0-9]*|[a-zA-Z_$]+[\w$]*)$/; // number or identifier
var exceptReserved = this._exceptReserved;
file.iterateNodesByType('ObjectExpression', function(node) {
node.properties.forEach(function(prop) {
var key = prop.key;
// Spread properties
if (!key) {
return;
}
if (key.type !== 'StringLiteral') {
return;
}
if (typeof key.value !== 'string') {
return;
}
if (!KEY_NAME_RE.test(key.value)) {
return;
}
if (exceptReserved && reservedWords.check(key.value, file.getDialect(), true)) {
return;
}
errors.cast({
message: 'Extra quotes for key',
element: prop
});
});
});
},
_fix: function(file, error) {
var node = error.element;
var key = node.key.childElements[0];
var newKey = new cst.Token(key.type, key.getSourceCode().slice(1, -1));
node.key.replaceChild(newKey, key);
}
};