loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
Documentation
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! JavaScript/TypeScript AST analysis module.
//!
//! This module provides comprehensive analysis of JS/TS files using OXC AST parser,
//! including support for:
//! - Import/export detection (static, dynamic, re-exports)
//! - Svelte and Vue Single File Component parsing
//! - Tauri command detection
//! - Event emit/listen detection
//! - TypeScript type signature tracking
//! - Flow type annotation detection
//!
//! # Module Structure
//!
//! - `config`: Command detection configuration and exclusion lists
//! - `sfc`: Single File Component script/template extraction
//! - `template`: Svelte/Vue template usage parsing
//! - `visitor`: Core AST visitor and helper methods
//! - `imports`: Import declaration handling
//! - `exports`: Export declaration handling
//! - `calls`: Call expression and dynamic import handling
//!
//! VibeCrafted with AI Agents (c)2026 Loctree Team

mod calls;
mod config;
mod exports;
mod imports;
mod sfc;
mod template;
mod visitor;

use std::collections::{HashMap, HashSet};
use std::path::Path;

use oxc_allocator::Allocator;
use oxc_ast::{AstKind, ast::*};
use oxc_ast_visit::{Visit, walk::walk_expression};
use oxc_parser::Parser;
use oxc_semantic::SemanticBuilder;
use oxc_span::GetSpan;
use oxc_span::SourceType;

use crate::types::{FileAnalysis, LocalSymbol, SymbolUsage};

use super::resolvers::TsPathResolver;

// Re-export public types
pub use config::CommandDetectionConfig;

// Use internal functions from submodules
use calls::is_flow_file;
use sfc::{
    extract_svelte_script, extract_svelte_template, extract_vue_script, extract_vue_template,
};
use template::{parse_svelte_template_usages, parse_vue_template_usages};
use visitor::JsVisitor;

/// Analyze JS/TS file using OXC AST parser.
///
/// This is the main entry point for JavaScript/TypeScript analysis. It:
/// 1. Parses the source code into an AST
/// 2. Extracts script content from SFC files (Svelte/Vue)
/// 3. Traverses the AST to collect imports, exports, commands, and events
/// 4. Parses templates for function/variable usage (Svelte/Vue)
/// 5. Uses semantic analysis to track local symbol references
///
/// # Arguments
///
/// * `content` - The source file content
/// * `path` - Path to the source file
/// * `root` - Root directory of the project
/// * `extensions` - Optional set of valid file extensions for resolution
/// * `ts_resolver` - Optional TypeScript path resolver
/// * `relative` - Relative path for the analysis result
/// * `command_cfg` - Command detection configuration
///
/// # Returns
///
/// A `FileAnalysis` containing all extracted information.
pub(crate) fn analyze_js_file_ast(
    content: &str,
    path: &Path,
    root: &Path,
    extensions: Option<&HashSet<String>>,
    ts_resolver: Option<&TsPathResolver>,
    relative: String,
    command_cfg: &CommandDetectionConfig,
) -> FileAnalysis {
    let allocator = Allocator::default();

    // Determine source type from file extension
    // Only enable JSX for .tsx/.jsx files to avoid conflicts with TypeScript generics
    // (e.g., `const fn = <T>(...) =>` would be parsed as JSX tag with JSX enabled)
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let is_jsx_file = ext == "tsx" || ext == "jsx";
    let is_svelte_file = ext == "svelte";
    let is_vue_file = ext == "vue";
    let is_sfc_file = is_svelte_file || is_vue_file;

    // Detect Flow type annotations
    let is_flow = is_flow_file(content);

    // For SFC files (Svelte/Vue), extract script content first
    let parsed_content: String;
    let content_to_parse = if is_svelte_file {
        parsed_content = extract_svelte_script(content);
        parsed_content.as_str()
    } else if is_vue_file {
        parsed_content = extract_vue_script(content);
        parsed_content.as_str()
    } else {
        content
    };

    // For SFC files (Svelte/Vue), parse as TypeScript
    let source_type = if is_sfc_file {
        SourceType::tsx().with_typescript(true)
    } else {
        SourceType::from_path(path)
            .unwrap_or_default()
            .with_typescript(true)
            .with_jsx(is_jsx_file)
    };

    let ret = Parser::new(&allocator, content_to_parse, source_type).parse();

    // Log parser errors for debugging (verbose mode only)
    if !ret.errors.is_empty() && std::env::var("LOCTREE_VERBOSE").is_ok() {
        eprintln!(
            "[loctree][debug] Parser errors in {}: {} errors",
            path.display(),
            ret.errors.len()
        );
        for (i, err) in ret.errors.iter().take(5).enumerate() {
            // Get line number from error span using the labels field
            let line_info = err
                .labels
                .as_ref()
                .and_then(|labels| labels.first())
                .map(|label| {
                    let offset = label.offset();
                    let line = content[..offset].bytes().filter(|b| *b == b'\n').count() + 1;
                    format!(" (line {}, col {})", line, label.offset())
                })
                .unwrap_or_default();
            eprintln!("  [{}]{} {}", i + 1, line_info, err);
        }
    }

    let mut visitor = JsVisitor {
        analysis: FileAnalysis::new(relative),
        path,
        root,
        extensions,
        ts_resolver,
        source_text: content_to_parse,
        source_lines: content_to_parse.lines().collect(),
        command_cfg,
        namespace_imports: HashMap::new(),
    };

    visitor.visit_program(&ret.program);

    // Mark file as Flow if detected
    visitor.analysis.is_flow_file = is_flow;

    // Use oxc_semantic to track local symbol references
    // This helps detect when exported symbols are used internally (not dead)
    let semantic_ret = SemanticBuilder::new().build(&ret.program);
    if semantic_ret.errors.is_empty() {
        let semantic = semantic_ret.semantic;

        // Build set of exported symbol names for quick lookup
        let exported_names: HashSet<&str> = visitor
            .analysis
            .exports
            .iter()
            .map(|e| e.name.as_str())
            .collect();

        let mut local_symbols = Vec::new();
        let mut symbol_usages = Vec::new();
        let mut seen_defs: HashSet<(String, usize)> = HashSet::new();
        let mut seen_uses: HashSet<(String, usize)> = HashSet::new();

        const MAX_USAGES_PER_FILE: usize = 1500;

        // Check each symbol - record local defs/usages and exported local uses
        for symbol_id in semantic.scoping().symbol_ids() {
            let name = semantic.scoping().symbol_name(symbol_id);
            if name.is_empty() {
                continue;
            }

            let decl = semantic.symbol_declaration(symbol_id);
            let kind = match decl.kind() {
                AstKind::Function(_) => "function",
                AstKind::Class(_) => "class",
                AstKind::VariableDeclarator(_) => "variable",
                AstKind::TSTypeAliasDeclaration(_) => "type",
                AstKind::TSInterfaceDeclaration(_) => "interface",
                AstKind::TSEnumDeclaration(_) => "enum",
                AstKind::ImportSpecifier(_)
                | AstKind::ImportDefaultSpecifier(_)
                | AstKind::ImportNamespaceSpecifier(_) => "import",
                AstKind::FormalParameter(_) | AstKind::BindingIdentifier(_) => "binding",
                _ => "symbol",
            };

            let span = decl.kind().span();
            let line = visitor.get_line(span);
            let is_exported = exported_names.contains(name);
            let context = visitor.line_context(line);

            // Track local definitions (non-exported; skip imports here)
            if !is_exported && kind != "import" && seen_defs.insert((name.to_string(), line)) {
                local_symbols.push(LocalSymbol {
                    name: name.to_string(),
                    kind: kind.to_string(),
                    line: Some(line),
                    context,
                    is_exported,
                });
            }

            // Exported symbol used locally?
            let ref_ids = semantic.scoping().get_resolved_reference_ids(symbol_id);
            if is_exported && !ref_ids.is_empty() {
                visitor.analysis.local_uses.push(name.to_string());
            }

            // Record usage sites (identifier references)
            if symbol_usages.len() < MAX_USAGES_PER_FILE {
                for reference in semantic.symbol_references(symbol_id) {
                    if symbol_usages.len() >= MAX_USAGES_PER_FILE {
                        break;
                    }
                    let ref_span = semantic.reference_span(reference);
                    let ref_line = visitor.get_line(ref_span);
                    if ref_line == 0 {
                        continue;
                    }
                    if seen_uses.insert((name.to_string(), ref_line)) {
                        let ref_context = visitor.line_context(ref_line);
                        symbol_usages.push(SymbolUsage {
                            name: name.to_string(),
                            line: ref_line,
                            context: ref_context,
                        });
                    }
                }
            }
        }

        if !local_symbols.is_empty() {
            visitor.analysis.local_symbols = local_symbols;
        }
        if !symbol_usages.is_empty() {
            visitor.analysis.symbol_usages = symbol_usages;
        }
    }

    // For Svelte files, also parse the template section to detect function calls
    // This prevents false positives where exported functions are used in the template
    // e.g., {badgeText(account)} or on:click={handleClick}
    if is_svelte_file {
        let template = extract_svelte_template(content);
        let template_usages = parse_svelte_template_usages(&template);
        for usage in template_usages {
            if !visitor.analysis.local_uses.contains(&usage) {
                visitor.analysis.local_uses.push(usage);
            }
        }
    }

    // For Vue files, also parse the template section to detect function calls
    // This prevents false positives where exported functions are used in the template
    // e.g., {{ formatDate(value) }} or @click="handleClick"
    if is_vue_file {
        let template = extract_vue_template(content);
        let template_usages = parse_vue_template_usages(&template);
        for usage in template_usages {
            if !visitor.analysis.local_uses.contains(&usage) {
                visitor.analysis.local_uses.push(usage);
            }
        }
    }

    visitor.analysis
}

/// Custom Visit implementation for JsVisitor that delegates to submodule handlers.
///
/// This implementation wires together all the visitor methods from the submodules
/// (imports, exports, calls) while also handling expression visiting for string
/// literal and WeakMap/WeakSet detection.
impl<'a> Visit<'a> for JsVisitor<'a> {
    fn visit_expression(&mut self, expr: &Expression<'a>) {
        match expr {
            Expression::StringLiteral(lit) => {
                self.push_string_literal(&lit.value, lit.span);
            }
            Expression::TemplateLiteral(tpl) => {
                if tpl.expressions.is_empty()
                    && tpl.quasis.len() == 1
                    && let Some(cooked) = &tpl.quasis[0].value.cooked
                {
                    self.push_string_literal(cooked, tpl.span);
                } else if tpl.expressions.is_empty() && tpl.quasis.len() == 1 {
                    self.push_string_literal(&tpl.quasis[0].value.raw, tpl.span);
                }
            }
            Expression::NewExpression(new_expr) => {
                // Detect WeakMap/WeakSet constructor calls to identify global registry patterns
                // Common in React DevTools and other libraries for storing metadata
                if let Expression::Identifier(ident) = &new_expr.callee {
                    let name = ident.name.to_string();
                    if name == "WeakMap" || name == "WeakSet" {
                        self.analysis.has_weak_collections = true;
                    }
                }
            }
            _ => {}
        }
        walk_expression(self, expr);
    }

    // Import handling - delegates to imports.rs
    fn visit_import_declaration(&mut self, decl: &ImportDeclaration<'a>) {
        self.handle_import_declaration(decl);
    }

    fn visit_member_expression(&mut self, member: &MemberExpression<'a>) {
        self.handle_member_expression(member);
        oxc_ast_visit::walk::walk_member_expression(self, member);
    }

    // Export handling - delegates to exports.rs
    fn visit_export_named_declaration(&mut self, decl: &ExportNamedDeclaration<'a>) {
        self.handle_export_named_declaration(decl);
    }

    fn visit_export_default_declaration(&mut self, decl: &ExportDefaultDeclaration<'a>) {
        self.handle_export_default_declaration(decl);
    }

    fn visit_export_all_declaration(&mut self, decl: &ExportAllDeclaration<'a>) {
        self.handle_export_all_declaration(decl);
    }

    // Call expression handling - delegates to calls.rs
    fn visit_import_expression(&mut self, expr: &ImportExpression<'a>) {
        self.handle_import_expression(expr);

        // Continue visiting children
        self.visit_expression(&expr.source);
        if let Some(opts) = &expr.options {
            self.visit_expression(opts);
        }
    }

    fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
        // Continue visiting children (callee/args may contain nested invocations)
        self.visit_arguments(&call.arguments);
        self.visit_expression(&call.callee);

        self.handle_call_expression(call);
    }

    fn visit_variable_declarator(&mut self, decl: &VariableDeclarator<'a>) {
        self.handle_variable_declarator(decl);

        // IMPORTANT: Continue visiting children (e.g. init expression might contain dynamic imports)
        self.visit_binding_pattern(&decl.id);
        if let Some(init) = &decl.init {
            self.visit_expression(init);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_ast_parsing_basic() {
        let content = r#"
            import { Foo } from "./bar";
            import Default, { Named } from "./baz";
            import * as NS from "./ns";

            export const myVar = 1;
            export function myFunc() {}
            export default class MyClass {}
            export { reexported } from "./other";

            invoke("my_command");
            safeInvoke("another_command");
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/test.ts"),
            Path::new("src"),
            None,
            None,
            "test.ts".to_string(),
            &CommandDetectionConfig::default(),
        );

        // Imports
        assert_eq!(analysis.imports.len(), 3);

        let bar = analysis
            .imports
            .iter()
            .find(|i| i.source == "./bar")
            .unwrap();
        assert_eq!(bar.symbols[0].name, "Foo");
        assert!(!bar.symbols[0].is_default);

        let baz = analysis
            .imports
            .iter()
            .find(|i| i.source == "./baz")
            .unwrap();
        assert_eq!(baz.symbols.len(), 2);
        assert!(
            baz.symbols
                .iter()
                .any(|s| s.name == "Default" && s.is_default)
        );
        assert!(
            baz.symbols
                .iter()
                .any(|s| s.name == "Named" && !s.is_default)
        );

        let ns = analysis
            .imports
            .iter()
            .find(|i| i.source == "./ns")
            .unwrap();
        assert_eq!(ns.symbols[0].name, "*");
        assert_eq!(ns.symbols[0].alias.as_deref(), Some("NS"));

        // Exports
        let exports: Vec<_> = analysis.exports.iter().map(|e| e.name.as_str()).collect();
        assert!(exports.contains(&"myVar"));
        assert!(exports.contains(&"myFunc"));
        // Default exports are now named "default" for proper import matching
        assert!(exports.contains(&"default"));
        // The original class name is preserved in export_type
        assert!(
            analysis
                .exports
                .iter()
                .any(|e| e.name == "default" && e.export_type == "MyClass")
        );
        assert!(exports.contains(&"reexported"));

        // Commands
        let commands: Vec<_> = analysis
            .command_calls
            .iter()
            .map(|c| c.name.as_str())
            .collect();
        assert!(commands.contains(&"my_command"));
        assert!(commands.contains(&"another_command"));
    }

    #[test]
    fn test_register_command_not_tauri_invoke() {
        let content = r#"
            import * as vscode from "vscode";
            vscode.commands.registerCommand("loctree.analyzeImpact", () => {});
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("editors/vscode/src/commands.ts"),
            Path::new("editors/vscode/src"),
            None,
            None,
            "commands.ts".to_string(),
            &CommandDetectionConfig::default(),
        );

        assert!(
            analysis.command_calls.is_empty(),
            "VSCode registerCommand should not be treated as a Tauri invoke"
        );
    }

    #[test]
    fn test_vue_sfc_script_extraction() {
        // Vue SFC with script setup (Composition API)
        let content = r#"
<script setup lang="ts">
import { ref, computed } from 'vue'

const count = ref(0)

export function increment() {
    count.value++
}
</script>

<template>
  <div>{{ count }}</div>
</template>
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/Counter.vue"),
            Path::new("src"),
            None,
            None,
            "Counter.vue".to_string(),
            &CommandDetectionConfig::default(),
        );

        // Verify imports are detected
        assert!(
            analysis.imports.iter().any(|i| i.source == "vue"),
            "Should detect vue import"
        );

        // Verify exports are detected
        assert!(
            analysis
                .exports
                .iter()
                .any(|e| e.name == "increment" && e.kind == "function"),
            "Should detect increment export"
        );
    }

    #[test]
    fn test_vue_sfc_options_api() {
        // Vue SFC with Options API
        let content = r#"
<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
    data() {
        return { count: 0 }
    }
})
</script>

<template>
  <div>{{ count }}</div>
</template>
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/Counter.vue"),
            Path::new("src"),
            None,
            None,
            "Counter.vue".to_string(),
            &CommandDetectionConfig::default(),
        );

        // Verify import is detected
        assert!(
            analysis.imports.iter().any(|i| i.source == "vue"),
            "Should detect vue import"
        );

        // Verify default export is detected
        assert!(
            analysis.exports.iter().any(|e| e.export_type == "default"),
            "Should detect default export"
        );
    }

    #[test]
    fn test_svelte_file_full_analysis() {
        let content = r#"
<script lang="ts">
    import type { Account } from './types';

    export function badgeText(account: Account): string {
        return account.name;
    }

    export let account: Account;
</script>

<div class="badge">
    <span>{badgeText(account)}</span>
</div>

<style>
    .badge { color: blue; }
</style>
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/GitHubAccountBadge.svelte"),
            Path::new("src"),
            None,
            None,
            "GitHubAccountBadge.svelte".to_string(),
            &CommandDetectionConfig::default(),
        );

        assert!(
            analysis.local_uses.contains(&"badgeText".to_string()),
            "badgeText should be in local_uses, found: {:?}",
            analysis.local_uses
        );

        assert!(
            analysis.local_uses.contains(&"account".to_string()),
            "account should be in local_uses, found: {:?}",
            analysis.local_uses
        );
    }

    #[test]
    fn test_vue_file_full_analysis() {
        let content = r#"
<script setup lang="ts">
    import type { Product } from './types';

    export function formatPrice(price: number): string {
        return `$${price.toFixed(2)}`;
    }

    export const product: Product = { name: 'Widget', price: 29.99 };
</script>

<template>
    <div class="product">
        <h3>{{ product.name }}</h3>
        <p>{{ formatPrice(product.price) }}</p>
    </div>
</template>

<style scoped>
    .product { border: 1px solid #ccc; }
</style>
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/ProductCard.vue"),
            Path::new("src"),
            None,
            None,
            "ProductCard.vue".to_string(),
            &CommandDetectionConfig::default(),
        );

        assert!(
            analysis.local_uses.contains(&"formatPrice".to_string()),
            "formatPrice should be in local_uses, found: {:?}",
            analysis.local_uses
        );

        assert!(
            analysis.local_uses.contains(&"product".to_string()),
            "product should be in local_uses, found: {:?}",
            analysis.local_uses
        );
    }

    /// Test WeakMap/WeakSet detection for registry pattern (React DevTools, etc.)
    #[test]
    fn test_weakmap_detection() {
        let content = r#"
            // React DevTools pattern: store component metadata in WeakMap
            const componentMap = new WeakMap();
            const stateMap = new WeakSet();

            export function registerComponent(component) {
                componentMap.set(component, { name: component.name });
            }

            export const MyComponent = () => <div>Hello</div>;
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/devtools.tsx"), // Use .tsx for JSX support
            Path::new("src"),
            None,
            None,
            "devtools.tsx".to_string(),
            &CommandDetectionConfig::default(),
        );

        assert!(
            analysis.has_weak_collections,
            "Should detect WeakMap/WeakSet usage"
        );

        // Should export 2 symbols
        assert_eq!(analysis.exports.len(), 2);
        assert!(
            analysis
                .exports
                .iter()
                .any(|e| e.name == "registerComponent")
        );
        assert!(analysis.exports.iter().any(|e| e.name == "MyComponent"));
    }

    /// Test that files without WeakMap/WeakSet don't get flagged
    #[test]
    fn test_no_weakmap_detection() {
        let content = r#"
            const cache = new Map();
            export function getCached(key) {
                return cache.get(key);
            }
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/cache.ts"),
            Path::new("src"),
            None,
            None,
            "cache.ts".to_string(),
            &CommandDetectionConfig::default(),
        );

        assert!(
            !analysis.has_weak_collections,
            "Should NOT flag regular Map as WeakMap"
        );
    }

    #[test]
    fn test_local_symbols_and_usages() {
        let content = r#"
            import { Component as MyComponent } from 'react';

            const taskFilter = 'all';
            function applyFilter() {
                return taskFilter;
            }
            const onClick = () => MyComponent;
            MyComponent();
        "#;

        let analysis = analyze_js_file_ast(
            content,
            Path::new("src/test.tsx"),
            Path::new("src"),
            None,
            None,
            "test.tsx".to_string(),
            &CommandDetectionConfig::default(),
        );

        assert!(
            analysis
                .local_symbols
                .iter()
                .any(|s| s.name == "taskFilter"),
            "taskFilter should be in local_symbols"
        );
        assert!(
            analysis
                .local_symbols
                .iter()
                .any(|s| s.name == "applyFilter"),
            "applyFilter should be in local_symbols"
        );
        assert!(
            analysis
                .symbol_usages
                .iter()
                .any(|u| u.name == "taskFilter"),
            "taskFilter should be in symbol_usages"
        );
        assert!(
            analysis
                .symbol_usages
                .iter()
                .any(|u| u.name == "MyComponent"),
            "MyComponent usage should be tracked"
        );
    }
}