Skip to content

Commit 1833bc1

Browse files
committed
use acorn.isIdentifierStart and isIdentifierChar to determine validity
1 parent b193036 commit 1833bc1

File tree

3 files changed

+31
-27
lines changed

3 files changed

+31
-27
lines changed

src/utils/isValidIdentifier.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { isIdentifierStart, isIdentifierChar } from 'acorn';
2+
3+
export default function isValidIdentifier(str) {
4+
if (!isIdentifierStart(str.charCodeAt(0), true)) return false;
5+
6+
for (let i = 0; i < str.length; i += 1) {
7+
if (!isIdentifierChar(str.charCodeAt(i), true)) return false;
8+
}
9+
10+
return true;
11+
}

src/validate/js/propValidators/computed.ts

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import checkForDupes from '../utils/checkForDupes';
22
import checkForComputedKeys from '../utils/checkForComputedKeys';
3-
import checkForValidIdentifiers from '../utils/checkForValidIdentifiers';
3+
import getName from '../../../utils/getName';
4+
import isValidIdentifier from '../../../utils/isValidIdentifier';
5+
import reservedNames from '../../../utils/reservedNames';
46
import { Validator } from '../../';
57
import { Node } from '../../../interfaces';
68
import walkThroughTopFunctionScope from '../../../utils/walkThroughTopFunctionScope';
@@ -21,9 +23,25 @@ export default function computed(validator: Validator, prop: Node) {
2123

2224
checkForDupes(validator, prop.value.properties);
2325
checkForComputedKeys(validator, prop.value.properties);
24-
checkForValidIdentifiers(validator, prop.value.properties);
2526

2627
prop.value.properties.forEach((computation: Node) => {
28+
const name = getName(computation.key);
29+
30+
if (!isValidIdentifier(name)) {
31+
const suggestion = name.replace(/[^_$a-z0-9]/ig, '_').replace(/^\d/, '_$&');
32+
validator.error(
33+
`Computed property name '${name}' is invalid — must be a valid identifier such as ${suggestion}`,
34+
computation.start
35+
);
36+
}
37+
38+
if (reservedNames.has(name)) {
39+
validator.error(
40+
`Computed property name '${name}' is invalid — cannot be a JavaScript reserved word`,
41+
computation.start
42+
);
43+
}
44+
2745
if (!isFunctionExpression.has(computation.value.type)) {
2846
validator.error(
2947
`Computed properties can be function expressions or arrow function expressions`,

src/validate/js/utils/checkForValidIdentifiers.ts

Lines changed: 0 additions & 25 deletions
This file was deleted.

0 commit comments

Comments
 (0)