@@ -8,7 +8,6 @@ export default createRule("valid-context-access", {
8
8
description :
9
9
"context functions must be called during component initialization." ,
10
10
category : "Possible Errors" ,
11
- // TODO Switch to recommended in the major version.
12
11
recommended : false ,
13
12
} ,
14
13
schema : [ ] ,
@@ -19,7 +18,28 @@ export default createRule("valid-context-access", {
19
18
type : "problem" ,
20
19
} ,
21
20
create ( context ) {
22
- const scopeManager = context . getSourceCode ( ) . scopeManager
21
+ // // This rule doesn't check other than Svelte files.
22
+ if ( ! context . parserServices . isSvelte ) {
23
+ return { }
24
+ }
25
+
26
+ // Extract <script> blocks that is not module=context.
27
+ const sourceCode = context . getSourceCode ( )
28
+ const scriptNotModuleElements = sourceCode . ast . body . filter ( ( b ) => {
29
+ if ( b . type !== "SvelteScriptElement" ) return false
30
+ const isModule = b . startTag . attributes . some ( ( a ) => {
31
+ return (
32
+ a . type === "SvelteAttribute" &&
33
+ a . key . name === "context" &&
34
+ a . value . some (
35
+ ( v ) => v . type === "SvelteLiteral" && v . value === "module" ,
36
+ )
37
+ )
38
+ } )
39
+ return ! isModule
40
+ } )
41
+
42
+ const scopeManager = sourceCode . scopeManager
23
43
const toplevelScope =
24
44
scopeManager . globalScope ?. childScopes . find (
25
45
( scope ) => scope . type === "module" ,
@@ -53,17 +73,32 @@ export default createRule("valid-context-access", {
53
73
return [ ]
54
74
}
55
75
76
+ /** Return true if the node is there inside of <script> block that is not module=context. */
77
+ function isInsideOfSvelteScriptElement ( node : TSESTree . Node ) {
78
+ for ( const script of scriptNotModuleElements ) {
79
+ if (
80
+ node . range [ 0 ] >= script . range [ 0 ] &&
81
+ node . range [ 1 ] <= script . range [ 1 ]
82
+ ) {
83
+ return true
84
+ }
85
+ }
86
+ return false
87
+ }
88
+
56
89
/** Let's lint! */
57
90
function doLint (
58
91
visitedCallExpressions : TSESTree . CallExpression [ ] ,
59
92
contextCallExpression : TSESTree . CallExpression ,
60
93
currentNode : TSESTree . CallExpression ,
61
94
) {
62
- let { parent } = currentNode
63
- if ( parent ?. type !== "ExpressionStatement" ) {
95
+ // Report if context function is called outside of <script> block.
96
+ if ( ! isInsideOfSvelteScriptElement ( currentNode ) ) {
64
97
report ( contextCallExpression )
65
98
return
66
99
}
100
+
101
+ let { parent } = currentNode
67
102
while ( parent ) {
68
103
parent = parent . parent
69
104
if (
0 commit comments