2
2
3
3
import { dirRE } from './parser/index'
4
4
5
- const keywordRE = new RegExp ( '\\b' + (
6
- 'do,if,in,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
7
- 'super,throw,while,yield,delete,export,import,return,switch,typeof,default,' +
8
- 'extends,finally,continue,debugger,function,arguments,instanceof'
5
+ // operators like typeof, instanceof and in are allowed
6
+ const prohibitedKeywordRE = new RegExp ( '\\b' + (
7
+ 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
8
+ 'super,throw,while,yield,delete,export,import,return,switch,default,' +
9
+ 'extends,finally,continue,debugger,function,arguments'
9
10
) . split ( ',' ) . join ( '\\b|\\b' ) + '\\b' )
11
+ // check valid identifier for v-for
12
+ const identRE = / [ ^ \w $ \. ] (?: [ A - Z a - z _ $ ] [ \w $ ] * ) /
10
13
11
14
// detect problematic expressions in a template
12
15
export function detectErrors ( ast : ?ASTNode ) : Array < string > {
@@ -23,7 +26,11 @@ function checkNode (node: ASTNode, errors: Array<string>) {
23
26
if ( dirRE . test ( name ) ) {
24
27
const value = node . attrsMap [ name ]
25
28
if ( value ) {
26
- checkExpression ( value , `${ name } ="${ value } "` , errors )
29
+ if ( name === 'v-for' ) {
30
+ checkFor ( node , `v-for="${ value } "` , errors )
31
+ } else {
32
+ checkExpression ( value , `${ name } ="${ value } "` , errors )
33
+ }
27
34
}
28
35
}
29
36
}
@@ -37,17 +44,30 @@ function checkNode (node: ASTNode, errors: Array<string>) {
37
44
}
38
45
}
39
46
47
+ function checkFor ( node : ASTElement , text : string , errors : Array < string > ) {
48
+ checkExpression ( node . for || '' , text , errors )
49
+ checkIdentifier ( node . alias , 'v-for alias' , text , errors )
50
+ checkIdentifier ( node . iterator1 , 'v-for iterator' , text , errors )
51
+ checkIdentifier ( node . iterator2 , 'v-for iterator' , text , errors )
52
+ }
53
+
54
+ function checkIdentifier ( ident : ?string , type : string , text : string , errors : Array < string > ) {
55
+ if ( typeof ident === 'string' && ! identRE . test ( ident ) ) {
56
+ errors . push ( `- invalid ${ type } "${ ident } " in expression: ${ text } ` )
57
+ }
58
+ }
59
+
40
60
function checkExpression ( exp : string , text : string , errors : Array < string > ) {
41
61
exp = stripToString ( exp )
42
- const keywordMatch = exp . match ( keywordRE )
62
+ const keywordMatch = exp . match ( prohibitedKeywordRE )
43
63
if ( keywordMatch ) {
44
64
errors . push (
45
65
`- avoid using JavaScript keyword as property name: ` +
46
66
`"${ keywordMatch [ 0 ] } " in expression ${ text } `
47
67
)
48
68
} else {
49
69
try {
50
- new Function ( exp )
70
+ new Function ( `return ${ exp } ` )
51
71
} catch ( e ) {
52
72
errors . push ( `- invalid expression: ${ text } ` )
53
73
}
0 commit comments