@@ -162,6 +162,37 @@ function isPromiseThenOrCatchBody(node: TSESTree.Node): boolean {
162
162
return [ "then" , "catch" ] . includes ( property . name )
163
163
}
164
164
165
+
166
+ /**
167
+ * Get all reactive variable reference.
168
+ */
169
+ function getAllReactiveVariableReferences ( context : RuleContext ) {
170
+ const scopeManager = context . getSourceCode ( ) . scopeManager
171
+ // Find the top-level (module or global) scope.
172
+ // Any variable defined at the top-level (module scope or global scope) can be made reactive.
173
+ const toplevelScope =
174
+ scopeManager . globalScope ?. childScopes . find (
175
+ ( scope ) => scope . type === "module" ,
176
+ ) || scopeManager . globalScope
177
+ if ( ! toplevelScope ) {
178
+ return [ ]
179
+ }
180
+
181
+ // Extracts all reactive references to variables defined in the top-level scope.
182
+ const reactiveVariableNodes : TSESTree . Identifier [ ] = [ ]
183
+ for ( const variable of toplevelScope . variables ) {
184
+ for ( const reference of variable . references ) {
185
+ if (
186
+ reference . identifier . type === "Identifier" &&
187
+ ! isFunctionCall ( reference . identifier )
188
+ ) {
189
+ reactiveVariableNodes . push ( reference . identifier )
190
+ }
191
+ }
192
+ }
193
+ return reactiveVariableNodes
194
+ }
195
+
165
196
/**
166
197
* Get all tracked reactive variables.
167
198
*/
@@ -170,16 +201,16 @@ function getTrackedVariableNodes(
170
201
ast : AST . SvelteReactiveStatement ,
171
202
) {
172
203
const reactiveVariableNodes : TSESTree . Identifier [ ] = [ ]
173
- traverseNodes ( ast . body , {
174
- enterNode ( node ) {
175
- if ( isReactiveVariableNode ( context , node ) ) {
176
- reactiveVariableNodes . push ( node )
177
- }
178
- } ,
179
- leaveNode ( ) {
180
- /* noop */
181
- } ,
182
- } )
204
+ for ( const identifier of getAllReactiveVariableReferences ( context ) ) {
205
+ if (
206
+ // If the identifier is within the reactive statement range,
207
+ // it is used within the reactive statement.
208
+ ast . range [ 0 ] <= identifier . range [ 0 ] &&
209
+ identifier . range [ 1 ] <= ast . range [ 1 ]
210
+ ) {
211
+ reactiveVariableNodes . push ( identifier )
212
+ }
213
+ }
183
214
return reactiveVariableNodes
184
215
}
185
216
0 commit comments