Skip to main content

reflex/parsers/
typescript.rs

1//! TypeScript/JavaScript language parser using Tree-sitter
2//!
3//! Extracts symbols from TypeScript and JavaScript source code:
4//! - Functions (regular, arrow, async, generator)
5//! - Classes (regular, abstract)
6//! - Interfaces
7//! - Type aliases
8//! - Enums
9//! - Variables and constants (const, let, var - all scopes)
10//! - Methods (with class scope)
11//! - Modules/Namespaces
12//!
13//! This parser handles both TypeScript (.ts, .tsx) and JavaScript (.js, .jsx)
14//! files using the tree-sitter-typescript grammar.
15
16use crate::models::{Language, SearchResult, Span, SymbolKind};
17use anyhow::{Context, Result};
18use streaming_iterator::StreamingIterator;
19use tree_sitter::{Parser, QueryCursor};
20
21/// Parse TypeScript/JavaScript source code and extract symbols
22pub fn parse(path: &str, source: &str, language: Language) -> Result<Vec<SearchResult>> {
23    let mut parser = Parser::new();
24
25    // tree-sitter-typescript provides both TypeScript and TSX grammars
26    // For JavaScript, we use the TypeScript grammar (it's a superset)
27    let ts_language_fn = match language {
28        Language::TypeScript => tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
29        Language::JavaScript => tree_sitter_typescript::LANGUAGE_TSX, // TSX handles both JS and JSX
30        _ => return Err(anyhow::anyhow!("Unsupported language: {:?}", language)),
31    };
32
33    // Convert LanguageFn to Language
34    let ts_language: tree_sitter::Language = ts_language_fn.into();
35
36    parser
37        .set_language(&ts_language)
38        .context("Failed to set TypeScript/JavaScript language")?;
39
40    let tree = parser
41        .parse(source, None)
42        .context("Failed to parse TypeScript/JavaScript source")?;
43
44    let root_node = tree.root_node();
45    let table = SYMBOL_QUERIES.run(&ts_language, &root_node, source)?;
46
47    let mut symbols = Vec::new();
48
49    // Extract different types of symbols using Tree-sitter queries
50    symbols.extend(extract_functions(source, &table)?);
51    symbols.extend(extract_arrow_functions(source, &table)?);
52    symbols.extend(extract_classes(source, &table)?);
53    symbols.extend(extract_interfaces(source, &table)?);
54    symbols.extend(extract_type_aliases(source, &table)?);
55    symbols.extend(extract_enums(source, &table)?);
56    symbols.extend(extract_variables(source, &table)?);
57    symbols.extend(extract_methods(source, &table)?);
58
59    // Add file path and language to all symbols
60    for symbol in &mut symbols {
61        symbol.path = path.to_string();
62        symbol.lang = language;
63    }
64
65    Ok(symbols)
66}
67
68/// Extract regular function declarations (including async and generator)
69fn extract_functions(
70    source: &str,
71    table: &crate::parsers::MatchTable<'_>,
72) -> Result<Vec<SearchResult>> {
73    extract_symbols(source, table, 0, SymbolKind::Function, None)
74}
75
76/// Extract arrow functions assigned to variables/constants
77fn extract_arrow_functions(
78    source: &str,
79    table: &crate::parsers::MatchTable<'_>,
80) -> Result<Vec<SearchResult>> {
81    extract_symbols(source, table, 1, SymbolKind::Function, None)
82}
83
84/// Extract class declarations (including abstract classes)
85fn extract_classes(
86    source: &str,
87    table: &crate::parsers::MatchTable<'_>,
88) -> Result<Vec<SearchResult>> {
89    extract_symbols(source, table, 2, SymbolKind::Class, None)
90}
91
92/// Extract interface declarations
93fn extract_interfaces(
94    source: &str,
95    table: &crate::parsers::MatchTable<'_>,
96) -> Result<Vec<SearchResult>> {
97    extract_symbols(source, table, 3, SymbolKind::Interface, None)
98}
99
100/// Extract type alias declarations
101fn extract_type_aliases(
102    source: &str,
103    table: &crate::parsers::MatchTable<'_>,
104) -> Result<Vec<SearchResult>> {
105    extract_symbols(source, table, 4, SymbolKind::Type, None)
106}
107
108/// Extract enum declarations
109fn extract_enums(
110    source: &str,
111    table: &crate::parsers::MatchTable<'_>,
112) -> Result<Vec<SearchResult>> {
113    extract_symbols(source, table, 5, SymbolKind::Enum, None)
114}
115
116/// Extract variable and constant declarations (const, let, var - all scopes)
117fn extract_variables(
118    source: &str,
119    table: &crate::parsers::MatchTable<'_>,
120) -> Result<Vec<SearchResult>> {
121    // Extract const/let (lexical_declaration) and var (variable_declaration)
122    // Skip arrow functions as they're already handled by extract_arrow_functions
123
124    let query = table.query();
125    let matches = table.sub(6);
126
127    let mut symbols = Vec::new();
128
129    for match_ in matches {
130        let mut name = None;
131        let mut declarator_node = None;
132
133        for capture in &match_.captures {
134            let capture_name: &str = query.capture_names()[capture.index as usize];
135            if capture_name == "name" {
136                name = Some(
137                    capture
138                        .node
139                        .utf8_text(source.as_bytes())
140                        .unwrap_or("")
141                        .to_string(),
142                );
143                // Get the variable_declarator node
144                if let Some(parent) = capture.node.parent()
145                    && parent.kind() == "variable_declarator"
146                {
147                    declarator_node = Some(parent);
148                }
149            }
150        }
151
152        if let (Some(name), Some(declarator)) = (name, declarator_node) {
153            // Check if the value is an arrow function (skip those)
154            let mut is_arrow_function = false;
155            for i in 0..declarator.child_count() {
156                if let Some(child) = declarator.child(i as u32)
157                    && child.kind() == "arrow_function"
158                {
159                    is_arrow_function = true;
160                    break;
161                }
162            }
163
164            // Only add if it's NOT an arrow function
165            if !is_arrow_function && let Some(decl_node) = declarator.parent() {
166                let span = node_to_span(&decl_node);
167                let preview = extract_preview(source, &decl_node);
168
169                // Determine if it's a constant (const) or variable (let/var)
170                let decl_text = decl_node.utf8_text(source.as_bytes()).unwrap_or("");
171                let kind = if decl_text.trim_start().starts_with("const") {
172                    SymbolKind::Constant
173                } else {
174                    SymbolKind::Variable
175                };
176
177                symbols.push(SearchResult::new(
178                    String::new(),
179                    Language::TypeScript,
180                    kind,
181                    Some(name),
182                    span,
183                    None,
184                    preview,
185                ));
186            }
187        }
188    }
189
190    Ok(symbols)
191}
192
193/// Extract method definitions from classes
194fn extract_methods(
195    source: &str,
196    table: &crate::parsers::MatchTable<'_>,
197) -> Result<Vec<SearchResult>> {
198    let query = table.query();
199    let matches = table.sub(7);
200
201    let mut symbols = Vec::new();
202
203    for match_ in matches {
204        let mut class_name = None;
205        let mut method_name = None;
206        let mut method_node = None;
207
208        for capture in &match_.captures {
209            let capture_name: &str = query.capture_names()[capture.index as usize];
210            match capture_name {
211                "class_name" => {
212                    class_name = Some(
213                        capture
214                            .node
215                            .utf8_text(source.as_bytes())
216                            .unwrap_or("")
217                            .to_string(),
218                    );
219                }
220                "method_name" => {
221                    method_name = Some(
222                        capture
223                            .node
224                            .utf8_text(source.as_bytes())
225                            .unwrap_or("")
226                            .to_string(),
227                    );
228                    // Find the parent method_definition node
229                    let mut current = capture.node;
230                    while let Some(parent) = current.parent() {
231                        if parent.kind() == "method_definition" {
232                            method_node = Some(parent);
233                            break;
234                        }
235                        current = parent;
236                    }
237                }
238                _ => {}
239            }
240        }
241
242        if let (Some(class_name), Some(method_name), Some(node)) =
243            (class_name, method_name, method_node)
244        {
245            let scope = format!("class {}", class_name);
246            let span = node_to_span(&node);
247            let preview = extract_preview(source, &node);
248
249            symbols.push(SearchResult::new(
250                String::new(),
251                Language::TypeScript,
252                SymbolKind::Method,
253                Some(method_name),
254                span,
255                Some(scope),
256                preview,
257            ));
258        }
259    }
260
261    Ok(symbols)
262}
263
264/// Generic symbol extraction helper
265fn extract_symbols(
266    source: &str,
267    table: &crate::parsers::MatchTable<'_>,
268    sub: usize,
269    kind: SymbolKind,
270    scope: Option<String>,
271) -> Result<Vec<SearchResult>> {
272    let query = table.query();
273    let matches = table.sub(sub);
274
275    let mut symbols = Vec::new();
276
277    for match_ in matches {
278        // Find the name capture and the full node
279        let mut name = None;
280        let mut full_node = None;
281
282        for capture in &match_.captures {
283            let capture_name: &str = query.capture_names()[capture.index as usize];
284            if capture_name == "name" {
285                name = Some(
286                    capture
287                        .node
288                        .utf8_text(source.as_bytes())
289                        .unwrap_or("")
290                        .to_string(),
291                );
292            } else {
293                // Assume any other capture is the full node
294                full_node = Some(capture.node);
295            }
296        }
297
298        if let (Some(name), Some(node)) = (name, full_node) {
299            let span = node_to_span(&node);
300            let preview = extract_preview(source, &node);
301
302            symbols.push(SearchResult::new(
303                String::new(),
304                Language::TypeScript,
305                kind.clone(),
306                Some(name),
307                span,
308                scope.clone(),
309                preview,
310            ));
311        }
312    }
313
314    Ok(symbols)
315}
316
317/// Convert a Tree-sitter node to a Span
318fn node_to_span(node: &tree_sitter::Node) -> Span {
319    let start = node.start_position();
320    let end = node.end_position();
321
322    Span::new(
323        start.row + 1, // Convert 0-indexed to 1-indexed
324        start.column,
325        end.row + 1,
326        end.column,
327    )
328}
329
330/// Extract a preview (7 lines) around the symbol
331fn extract_preview(source: &str, node: &tree_sitter::Node) -> String {
332    // Starts at the node, not at byte 0: see `crate::parsers::preview`.
333    crate::parsers::preview::extract_preview_for_node(source, node)
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    #[test]
341    fn test_parse_function() {
342        let source = r#"
343            function greet(name: string): string {
344                return `Hello, ${name}!`;
345            }
346        "#;
347
348        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
349        assert_eq!(symbols.len(), 1);
350        assert_eq!(symbols[0].symbol.as_deref(), Some("greet"));
351        assert!(matches!(symbols[0].kind, SymbolKind::Function));
352    }
353
354    #[test]
355    fn test_parse_arrow_function() {
356        let source = r#"
357            const add = (a: number, b: number): number => {
358                return a + b;
359            };
360        "#;
361
362        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
363        assert_eq!(symbols.len(), 1);
364        assert_eq!(symbols[0].symbol.as_deref(), Some("add"));
365        assert!(matches!(symbols[0].kind, SymbolKind::Function));
366    }
367
368    #[test]
369    fn test_parse_async_function() {
370        let source = r#"
371            async function fetchData(url: string): Promise<Response> {
372                return await fetch(url);
373            }
374        "#;
375
376        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
377        assert_eq!(symbols.len(), 1);
378        assert_eq!(symbols[0].symbol.as_deref(), Some("fetchData"));
379        assert!(matches!(symbols[0].kind, SymbolKind::Function));
380    }
381
382    #[test]
383    fn test_parse_class() {
384        let source = r#"
385            class User {
386                name: string;
387                age: number;
388
389                constructor(name: string, age: number) {
390                    this.name = name;
391                    this.age = age;
392                }
393            }
394        "#;
395
396        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
397
398        // Should find class
399        let class_symbols: Vec<_> = symbols
400            .iter()
401            .filter(|s| matches!(s.kind, SymbolKind::Class))
402            .collect();
403
404        assert_eq!(class_symbols.len(), 1);
405        assert_eq!(class_symbols[0].symbol.as_deref(), Some("User"));
406    }
407
408    #[test]
409    fn test_parse_class_with_methods() {
410        let source = r#"
411            class Calculator {
412                add(a: number, b: number): number {
413                    return a + b;
414                }
415
416                subtract(a: number, b: number): number {
417                    return a - b;
418                }
419            }
420        "#;
421
422        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
423
424        // Should find class + 2 methods
425        assert!(symbols.len() >= 3);
426
427        let method_symbols: Vec<_> = symbols
428            .iter()
429            .filter(|s| matches!(s.kind, SymbolKind::Method))
430            .collect();
431
432        assert_eq!(method_symbols.len(), 2);
433        assert!(
434            method_symbols
435                .iter()
436                .any(|s| s.symbol.as_deref() == Some("add"))
437        );
438        assert!(
439            method_symbols
440                .iter()
441                .any(|s| s.symbol.as_deref() == Some("subtract"))
442        );
443
444        // Check scope
445        for _method in method_symbols {
446            // Removed: scope field no longer exists: assert_eq!(method.scope.as_ref().unwrap(), "class Calculator");
447        }
448    }
449
450    #[test]
451    fn test_parse_interface() {
452        let source = r#"
453            interface User {
454                name: string;
455                age: number;
456                email?: string;
457            }
458        "#;
459
460        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
461        assert_eq!(symbols.len(), 1);
462        assert_eq!(symbols[0].symbol.as_deref(), Some("User"));
463        assert!(matches!(symbols[0].kind, SymbolKind::Interface));
464    }
465
466    #[test]
467    fn test_parse_type_alias() {
468        let source = r#"
469            type UserId = string | number;
470            type UserRole = 'admin' | 'user' | 'guest';
471        "#;
472
473        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
474        assert_eq!(symbols.len(), 2);
475
476        let type_symbols: Vec<_> = symbols
477            .iter()
478            .filter(|s| matches!(s.kind, SymbolKind::Type))
479            .collect();
480
481        assert_eq!(type_symbols.len(), 2);
482        assert!(
483            type_symbols
484                .iter()
485                .any(|s| s.symbol.as_deref() == Some("UserId"))
486        );
487        assert!(
488            type_symbols
489                .iter()
490                .any(|s| s.symbol.as_deref() == Some("UserRole"))
491        );
492    }
493
494    #[test]
495    fn test_parse_enum() {
496        let source = r#"
497            enum Status {
498                Active,
499                Inactive,
500                Pending
501            }
502        "#;
503
504        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
505        assert_eq!(symbols.len(), 1);
506        assert_eq!(symbols[0].symbol.as_deref(), Some("Status"));
507        assert!(matches!(symbols[0].kind, SymbolKind::Enum));
508    }
509
510    #[test]
511    fn test_parse_const() {
512        let source = r#"
513            const MAX_SIZE = 100;
514            const DEFAULT_USER = {
515                name: "Anonymous",
516                age: 0
517            };
518        "#;
519
520        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
521        assert_eq!(symbols.len(), 2);
522
523        let const_symbols: Vec<_> = symbols
524            .iter()
525            .filter(|s| matches!(s.kind, SymbolKind::Constant))
526            .collect();
527
528        assert_eq!(const_symbols.len(), 2);
529        assert!(
530            const_symbols
531                .iter()
532                .any(|s| s.symbol.as_deref() == Some("MAX_SIZE"))
533        );
534        assert!(
535            const_symbols
536                .iter()
537                .any(|s| s.symbol.as_deref() == Some("DEFAULT_USER"))
538        );
539    }
540
541    #[test]
542    fn test_parse_react_component() {
543        let source = r#"
544            import React, { useState } from 'react';
545
546            interface ButtonProps {
547                label: string;
548                onClick: () => void;
549            }
550
551            const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
552                return (
553                    <button onClick={onClick}>
554                        {label}
555                    </button>
556                );
557            };
558
559            function useCounter(initial: number) {
560                const [count, setCount] = React.useState(initial);
561                return { count, setCount };
562            }
563
564            export default Button;
565        "#;
566
567        let symbols = parse("Button.tsx", source, Language::TypeScript).unwrap();
568
569        // Should find interface, Button component (arrow fn), useCounter hook (function)
570        assert!(
571            symbols
572                .iter()
573                .any(|s| s.symbol.as_deref() == Some("ButtonProps")
574                    && matches!(s.kind, SymbolKind::Interface))
575        );
576        assert!(symbols.iter().any(
577            |s| s.symbol.as_deref() == Some("Button") && matches!(s.kind, SymbolKind::Function)
578        ));
579        assert!(
580            symbols
581                .iter()
582                .any(|s| s.symbol.as_deref() == Some("useCounter")
583                    && matches!(s.kind, SymbolKind::Function))
584        );
585    }
586
587    #[test]
588    fn test_parse_mixed_symbols() {
589        let source = r#"
590            interface Config {
591                debug: boolean;
592            }
593
594            type ConfigKey = keyof Config;
595
596            const DEFAULT_CONFIG: Config = {
597                debug: false
598            };
599
600            class ConfigManager {
601                private config: Config;
602
603                constructor(config: Config) {
604                    this.config = config;
605                }
606
607                getConfig(): Config {
608                    return this.config;
609                }
610            }
611
612            function loadConfig(): Config {
613                return DEFAULT_CONFIG;
614            }
615        "#;
616
617        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
618
619        // Should find: interface, type, const, class, method, function
620        assert!(symbols.len() >= 6);
621
622        let kinds: Vec<&SymbolKind> = symbols.iter().map(|s| &s.kind).collect();
623        assert!(kinds.contains(&&SymbolKind::Interface));
624        assert!(kinds.contains(&&SymbolKind::Type));
625        assert!(kinds.contains(&&SymbolKind::Constant));
626        assert!(kinds.contains(&&SymbolKind::Class));
627        assert!(kinds.contains(&&SymbolKind::Method));
628        assert!(kinds.contains(&&SymbolKind::Function));
629    }
630
631    #[test]
632    fn test_parse_async_class_methods() {
633        let source = r#"
634            export class CentralUsersModule {
635                async getAllUsers(params) {
636                    return await this.call('get', `/users`, params)
637                }
638
639                async getUser(userId) {
640                    return await this.call('get', `/users/${userId}`)
641                }
642
643                deleteUser(userId) {
644                    return this.call('delete', `/user/${userId}`)
645                }
646            }
647        "#;
648
649        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
650
651        // Debug: Print all symbols
652        println!("\nAll symbols found:");
653        for symbol in &symbols {
654            println!(
655                "  {:?} - {}",
656                symbol.kind,
657                symbol.symbol.as_deref().unwrap_or("")
658            );
659        }
660
661        // Should find: class + 3 methods (2 async, 1 regular)
662        let class_symbols: Vec<_> = symbols
663            .iter()
664            .filter(|s| matches!(s.kind, SymbolKind::Class))
665            .collect();
666        assert_eq!(class_symbols.len(), 1);
667        assert_eq!(
668            class_symbols[0].symbol.as_deref(),
669            Some("CentralUsersModule")
670        );
671
672        let method_symbols: Vec<_> = symbols
673            .iter()
674            .filter(|s| matches!(s.kind, SymbolKind::Method))
675            .collect();
676
677        // All three should be detected as methods, not variables
678        assert_eq!(
679            method_symbols.len(),
680            3,
681            "Expected 3 methods, found {}",
682            method_symbols.len()
683        );
684        assert!(
685            method_symbols
686                .iter()
687                .any(|s| s.symbol.as_deref() == Some("getAllUsers"))
688        );
689        assert!(
690            method_symbols
691                .iter()
692                .any(|s| s.symbol.as_deref() == Some("getUser"))
693        );
694        assert!(
695            method_symbols
696                .iter()
697                .any(|s| s.symbol.as_deref() == Some("deleteUser"))
698        );
699
700        // Verify no async methods are misclassified as variables
701        let variable_symbols: Vec<_> = symbols
702            .iter()
703            .filter(|s| {
704                matches!(s.kind, SymbolKind::Constant) || matches!(s.kind, SymbolKind::Variable)
705            })
706            .collect();
707        assert_eq!(
708            variable_symbols.len(),
709            0,
710            "Async methods should not be classified as variables"
711        );
712
713        // Check scope
714        for _method in method_symbols {
715            // Removed: scope field no longer exists: assert_eq!(method.scope.as_ref().unwrap(), "class CentralUsersModule");
716        }
717    }
718
719    #[test]
720    fn test_parse_user_exact_code() {
721        // User's exact code with TypeScript types
722        let source = r#"
723export class CentralUsersModule extends HttpFactory<WatchHookMap, WatchEvents> {
724  protected $events = {
725    //
726  }
727
728  async checkAuthenticated() {
729    return await this.call('get', '/check')
730  }
731
732  async getUser(userId: CentralUser['id']) {
733    return await this.call<CentralUser>('get', `/users/${userId}`)
734  }
735
736  async getAllUsers(params?: PaginatedParams & SortableParams & SearchableParams) {
737    return await this.call<CentralUser[]>('get', `/users`, params)
738  }
739
740  async deleteUser(userId: CentralUser['id']) {
741    return await this.call<void>('delete', `/user/${userId}`)
742  }
743}
744        "#;
745
746        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
747
748        // Debug: Print all symbols
749        println!("\nAll symbols found in user code:");
750        for symbol in &symbols {
751            println!(
752                "  {:?} - {}",
753                symbol.kind,
754                symbol.symbol.as_deref().unwrap_or("")
755            );
756        }
757
758        // Verify getAllUsers is a Method, not a Variable
759        let get_all_users_symbols: Vec<_> = symbols
760            .iter()
761            .filter(|s| s.symbol.as_deref() == Some("getAllUsers"))
762            .collect();
763
764        assert_eq!(
765            get_all_users_symbols.len(),
766            1,
767            "Should find exactly one getAllUsers"
768        );
769        assert!(
770            matches!(get_all_users_symbols[0].kind, SymbolKind::Method),
771            "getAllUsers should be a Method, not {:?}",
772            get_all_users_symbols[0].kind
773        );
774    }
775
776    #[test]
777    fn test_local_variables_included() {
778        let source = r#"
779            const GLOBAL_CONSTANT = 100;
780            let globalLet = 50;
781            var globalVar = 25;
782
783            function calculate(x: number): number {
784                const localConst = x * 2;
785                let localLet = 5;
786                var localVar = 10;
787                return localConst + localLet + localVar;
788            }
789        "#;
790
791        let symbols = parse("test.ts", source, Language::TypeScript).unwrap();
792
793        let var_symbols: Vec<_> = symbols
794            .iter()
795            .filter(|s| {
796                matches!(s.kind, SymbolKind::Variable) || matches!(s.kind, SymbolKind::Constant)
797            })
798            .collect();
799
800        // Should find all: 3 global + 3 local = 6 variables
801        assert_eq!(var_symbols.len(), 6);
802
803        // Check globals
804        assert!(
805            var_symbols
806                .iter()
807                .any(|s| s.symbol.as_deref() == Some("GLOBAL_CONSTANT"))
808        );
809        assert!(
810            var_symbols
811                .iter()
812                .any(|s| s.symbol.as_deref() == Some("globalLet"))
813        );
814        assert!(
815            var_symbols
816                .iter()
817                .any(|s| s.symbol.as_deref() == Some("globalVar"))
818        );
819
820        // Check locals
821        assert!(
822            var_symbols
823                .iter()
824                .any(|s| s.symbol.as_deref() == Some("localConst"))
825        );
826        assert!(
827            var_symbols
828                .iter()
829                .any(|s| s.symbol.as_deref() == Some("localLet"))
830        );
831        assert!(
832            var_symbols
833                .iter()
834                .any(|s| s.symbol.as_deref() == Some("localVar"))
835        );
836
837        // Verify const vs variable classification
838        let global_const = var_symbols
839            .iter()
840            .find(|s| s.symbol.as_deref() == Some("GLOBAL_CONSTANT"))
841            .unwrap();
842        assert!(matches!(global_const.kind, SymbolKind::Constant));
843
844        let global_let = var_symbols
845            .iter()
846            .find(|s| s.symbol.as_deref() == Some("globalLet"))
847            .unwrap();
848        assert!(matches!(global_let.kind, SymbolKind::Variable));
849    }
850}
851
852// ============================================================================
853// Dependency Extraction
854// ============================================================================
855
856use crate::models::ImportType;
857use crate::parsers::{DependencyExtractor, ImportInfo};
858
859/// TypeScript/JavaScript dependency extractor
860pub struct TypeScriptDependencyExtractor;
861
862impl DependencyExtractor for TypeScriptDependencyExtractor {
863    fn extract_dependencies(source: &str) -> Result<Vec<ImportInfo>> {
864        // Delegate to the version without alias map for compatibility
865        Self::extract_dependencies_with_alias_map(source, None)
866    }
867}
868
869impl TypeScriptDependencyExtractor {
870    /// Extract dependencies with optional tsconfig alias map support
871    ///
872    /// This version properly classifies path alias imports (like @packages/*, ~/*) as Internal
873    /// when they match configured aliases from tsconfig.json.
874    pub fn extract_dependencies_with_alias_map(
875        source: &str,
876        alias_map: Option<&crate::parsers::tsconfig::PathAliasMap>,
877    ) -> Result<Vec<ImportInfo>> {
878        let mut parser = Parser::new();
879        let language = tree_sitter_typescript::LANGUAGE_TSX; // Use TSX for JS/TS compatibility
880
881        parser
882            .set_language(&language.into())
883            .context("Failed to set TypeScript/JavaScript language")?;
884
885        let tree = parser
886            .parse(source, None)
887            .context("Failed to parse TypeScript/JavaScript source")?;
888
889        let root_node = tree.root_node();
890
891        let mut imports = Vec::new();
892
893        // Extract ES6 import statements
894        imports.extend(extract_import_declarations(source, &root_node, alias_map)?);
895
896        // Extract require() statements
897        imports.extend(extract_require_statements(source, &root_node, alias_map)?);
898
899        Ok(imports)
900    }
901
902    /// Imports and re-exports from ONE parse of `source`.
903    ///
904    /// Same rows as `extract_dependencies_with_alias_map` followed by
905    /// `extract_export_declarations`; the indexer used to call both and parse
906    /// every TypeScript file twice.
907    pub fn extract_dependencies_and_exports(
908        source: &str,
909        alias_map: Option<&crate::parsers::tsconfig::PathAliasMap>,
910    ) -> Result<(Vec<ImportInfo>, Vec<ExportInfo>)> {
911        let mut parser = Parser::new();
912        let language = tree_sitter_typescript::LANGUAGE_TSX;
913
914        parser
915            .set_language(&language.into())
916            .context("Failed to set TypeScript/JavaScript language")?;
917
918        let tree = parser
919            .parse(source, None)
920            .context("Failed to parse TypeScript/JavaScript source")?;
921
922        let root_node = tree.root_node();
923
924        let mut imports = extract_import_declarations(source, &root_node, alias_map)?;
925        imports.extend(extract_require_statements(source, &root_node, alias_map)?);
926        let exports = extract_export_from_statements(source, &root_node)?;
927
928        Ok((imports, exports))
929    }
930}
931
932/// Extract ES6 import declarations: import { foo } from 'module'
933fn extract_import_declarations(
934    source: &str,
935    root: &tree_sitter::Node,
936    alias_map: Option<&crate::parsers::tsconfig::PathAliasMap>,
937) -> Result<Vec<ImportInfo>> {
938    let language = tree_sitter_typescript::LANGUAGE_TSX;
939
940    let query_str = r#"
941        (import_statement
942            source: (string) @import_path) @import
943    "#;
944
945    static QUERY_1: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
946    let query = crate::parsers::cached_query(&QUERY_1, language, query_str)
947        .context("Failed to create import declaration query")?;
948
949    let mut cursor = QueryCursor::new();
950    let mut matches = cursor.matches(query, *root, source.as_bytes());
951
952    let mut imports = Vec::new();
953
954    while let Some(match_) = matches.next() {
955        let mut import_path = None;
956        let mut import_node = None;
957
958        for capture in match_.captures {
959            let capture_name: &str = query.capture_names()[capture.index as usize];
960            match capture_name {
961                "import_path" => {
962                    // Remove quotes from string literal
963                    let raw_path = capture.node.utf8_text(source.as_bytes()).unwrap_or("");
964                    import_path = Some(
965                        raw_path
966                            .trim_matches(|c| c == '"' || c == '\'' || c == '`')
967                            .to_string(),
968                    );
969                }
970                "import" => {
971                    import_node = Some(capture.node);
972                }
973                _ => {}
974            }
975        }
976
977        if let (Some(path), Some(node)) = (import_path, import_node) {
978            let import_type = classify_js_import(&path, alias_map);
979            let line_number = node.start_position().row + 1;
980
981            // Extract imported symbols
982            let imported_symbols = extract_imported_symbols_js(source, &node);
983
984            imports.push(ImportInfo {
985                imported_path: path,
986                import_type,
987                line_number,
988                imported_symbols,
989            });
990        }
991    }
992
993    Ok(imports)
994}
995
996/// Extract require() statements: const foo = require('module')
997fn extract_require_statements(
998    source: &str,
999    root: &tree_sitter::Node,
1000    alias_map: Option<&crate::parsers::tsconfig::PathAliasMap>,
1001) -> Result<Vec<ImportInfo>> {
1002    let language = tree_sitter_typescript::LANGUAGE_TSX;
1003
1004    let query_str = r#"
1005        (call_expression
1006            function: (identifier) @func_name
1007            arguments: (arguments (string) @require_path)) @require_call
1008    "#;
1009
1010    static QUERY_2: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
1011    let query = crate::parsers::cached_query(&QUERY_2, language, query_str)
1012        .context("Failed to create require query")?;
1013
1014    let mut cursor = QueryCursor::new();
1015    let mut matches = cursor.matches(query, *root, source.as_bytes());
1016
1017    let mut imports = Vec::new();
1018
1019    while let Some(match_) = matches.next() {
1020        let mut func_name = None;
1021        let mut require_path = None;
1022        let mut require_node = None;
1023
1024        for capture in match_.captures {
1025            let capture_name: &str = query.capture_names()[capture.index as usize];
1026            match capture_name {
1027                "func_name" => {
1028                    func_name = Some(capture.node.utf8_text(source.as_bytes()).unwrap_or(""));
1029                }
1030                "require_path" => {
1031                    // Remove quotes from string literal
1032                    let raw_path = capture.node.utf8_text(source.as_bytes()).unwrap_or("");
1033                    require_path = Some(
1034                        raw_path
1035                            .trim_matches(|c| c == '"' || c == '\'' || c == '`')
1036                            .to_string(),
1037                    );
1038                }
1039                "require_call" => {
1040                    require_node = Some(capture.node);
1041                }
1042                _ => {}
1043            }
1044        }
1045
1046        // Only process if it's actually a require() call
1047        if func_name == Some("require")
1048            && let (Some(path), Some(node)) = (require_path, require_node)
1049        {
1050            let import_type = classify_js_import(&path, alias_map);
1051            let line_number = node.start_position().row + 1;
1052
1053            imports.push(ImportInfo {
1054                imported_path: path,
1055                import_type,
1056                line_number,
1057                imported_symbols: None, // require doesn't have selective imports
1058            });
1059        }
1060    }
1061
1062    Ok(imports)
1063}
1064
1065/// Extract the list of imported symbols from an import statement
1066fn extract_imported_symbols_js(
1067    source: &str,
1068    import_node: &tree_sitter::Node,
1069) -> Option<Vec<String>> {
1070    let mut symbols = Vec::new();
1071
1072    // Walk children to find import_clause nodes
1073    let mut cursor = import_node.walk();
1074    for child in import_node.children(&mut cursor) {
1075        if child.kind() == "import_clause" {
1076            // Look for named_imports or namespace_import
1077            let mut clause_cursor = child.walk();
1078            for grandchild in child.children(&mut clause_cursor) {
1079                match grandchild.kind() {
1080                    "named_imports" => {
1081                        // Extract individual import specifiers
1082                        let mut specifier_cursor = grandchild.walk();
1083                        for specifier in grandchild.children(&mut specifier_cursor) {
1084                            if specifier.kind() == "import_specifier" {
1085                                // Get the name (could be aliased)
1086                                if let Ok(text) = specifier.utf8_text(source.as_bytes()) {
1087                                    // Parse "foo as bar" or just "foo"
1088                                    let name = text.split_whitespace().next().unwrap_or(text);
1089                                    symbols.push(name.to_string());
1090                                }
1091                            }
1092                        }
1093                    }
1094                    "identifier" => {
1095                        // Default import: import Foo from 'module'
1096                        if let Ok(text) = grandchild.utf8_text(source.as_bytes()) {
1097                            symbols.push(text.to_string());
1098                        }
1099                    }
1100                    _ => {}
1101                }
1102            }
1103        }
1104    }
1105
1106    if symbols.is_empty() {
1107        None
1108    } else {
1109        Some(symbols)
1110    }
1111}
1112
1113/// Classify a JavaScript/TypeScript import as internal, external, or stdlib
1114///
1115/// # Arguments
1116///
1117/// * `import_path` - The import path string
1118/// * `alias_map` - Optional tsconfig path alias mappings
1119///
1120/// Path alias imports (like `@packages/*` from tsconfig.json) are classified as Internal
1121/// when they match a configured alias pattern.
1122fn classify_js_import(
1123    import_path: &str,
1124    alias_map: Option<&crate::parsers::tsconfig::PathAliasMap>,
1125) -> ImportType {
1126    // Relative imports (./ or ../)
1127    if import_path.starts_with("./") || import_path.starts_with("../") {
1128        log::trace!(
1129            "classify_js_import: '{}' => Internal (relative)",
1130            import_path
1131        );
1132        return ImportType::Internal;
1133    }
1134
1135    // Absolute imports starting with /
1136    if import_path.starts_with("/") {
1137        log::trace!(
1138            "classify_js_import: '{}' => Internal (absolute)",
1139            import_path
1140        );
1141        return ImportType::Internal;
1142    }
1143
1144    // Check if import matches a configured path alias (e.g., @packages/*, ~/*)
1145    if let Some(map) = alias_map {
1146        log::trace!(
1147            "classify_js_import: checking '{}' against {} aliases",
1148            import_path,
1149            map.aliases.len()
1150        );
1151        for alias_pattern in map.aliases.keys() {
1152            // Check for wildcard patterns like "@packages/*"
1153            if alias_pattern.ends_with("/*") {
1154                let alias_prefix = alias_pattern.trim_end_matches("/*");
1155                if import_path.starts_with(alias_prefix) {
1156                    log::info!(
1157                        "classify_js_import: '{}' => Internal (matches alias pattern '{}')",
1158                        import_path,
1159                        alias_pattern
1160                    );
1161                    return ImportType::Internal;
1162                }
1163            } else {
1164                // Exact match
1165                if import_path == alias_pattern {
1166                    log::info!(
1167                        "classify_js_import: '{}' => Internal (exact match alias '{}')",
1168                        import_path,
1169                        alias_pattern
1170                    );
1171                    return ImportType::Internal;
1172                }
1173            }
1174        }
1175        log::trace!(
1176            "classify_js_import: '{}' did not match any of {} alias patterns",
1177            import_path,
1178            map.aliases.len()
1179        );
1180    } else {
1181        log::trace!(
1182            "classify_js_import: no alias map provided for '{}'",
1183            import_path
1184        );
1185    }
1186
1187    // Node.js built-in modules (stdlib)
1188    const STDLIB_MODULES: &[&str] = &[
1189        "fs",
1190        "path",
1191        "os",
1192        "crypto",
1193        "util",
1194        "events",
1195        "stream",
1196        "buffer",
1197        "http",
1198        "https",
1199        "net",
1200        "tls",
1201        "url",
1202        "querystring",
1203        "dns",
1204        "child_process",
1205        "cluster",
1206        "worker_threads",
1207        "readline",
1208        "zlib",
1209        "assert",
1210        "console",
1211        "module",
1212        "process",
1213        "timers",
1214        "vm",
1215        "string_decoder",
1216        "dgram",
1217        "v8",
1218        "perf_hooks",
1219        // Node.js prefixed imports (node:fs, etc.)
1220        "node:fs",
1221        "node:path",
1222        "node:os",
1223        "node:crypto",
1224        "node:util",
1225        "node:events",
1226        "node:stream",
1227        "node:buffer",
1228        "node:http",
1229        "node:https",
1230        "node:net",
1231    ];
1232
1233    // Check if it's a stdlib module
1234    if STDLIB_MODULES.contains(&import_path) {
1235        log::trace!("classify_js_import: '{}' => Stdlib", import_path);
1236        return ImportType::Stdlib;
1237    }
1238
1239    // Everything else is external (third-party packages from npm)
1240    log::info!(
1241        "classify_js_import: '{}' => External (not alias, relative, absolute, or stdlib)",
1242        import_path
1243    );
1244    ImportType::External
1245}
1246
1247// ============================================================================
1248// Export Extraction (for barrel export tracking)
1249// ============================================================================
1250
1251use crate::parsers::ExportInfo;
1252
1253const SYMQ_0: &str = r#"
1254        (function_declaration
1255            name: (identifier) @name) @function
1256
1257        (generator_function_declaration
1258            name: (identifier) @name) @function
1259    "#;
1260const SYMQ_1: &str = r#"
1261        (lexical_declaration
1262            (variable_declarator
1263                name: (identifier) @name
1264                value: (arrow_function))) @arrow_fn
1265
1266        (variable_declaration
1267            (variable_declarator
1268                name: (identifier) @name
1269                value: (arrow_function))) @arrow_fn
1270    "#;
1271const SYMQ_2: &str = r#"
1272        (class_declaration
1273            name: (type_identifier) @name) @class
1274
1275        (abstract_class_declaration
1276            name: (type_identifier) @name) @class
1277    "#;
1278const SYMQ_3: &str = r#"
1279        (interface_declaration
1280            name: (type_identifier) @name) @interface
1281    "#;
1282const SYMQ_4: &str = r#"
1283        (type_alias_declaration
1284            name: (type_identifier) @name) @type
1285    "#;
1286const SYMQ_5: &str = r#"
1287        (enum_declaration
1288            name: (identifier) @name) @enum
1289    "#;
1290const SYMQ_6: &str = r#"
1291        (lexical_declaration
1292            (variable_declarator
1293                name: (identifier) @name)) @decl
1294
1295        (variable_declaration
1296            (variable_declarator
1297                name: (identifier) @name)) @decl
1298    "#;
1299const SYMQ_7: &str = r#"
1300        (class_declaration
1301            name: (type_identifier) @class_name
1302            body: (class_body
1303                (method_definition
1304                    name: (_) @method_name))) @class
1305
1306        (abstract_class_declaration
1307            name: (type_identifier) @class_name
1308            body: (class_body
1309                (method_definition
1310                    name: (_) @method_name))) @class
1311    "#;
1312
1313/// Every symbol query of this module, run as ONE query per file (see
1314/// `crate::parsers::LanguageQueries`).
1315static SYMBOL_QUERIES: crate::parsers::LanguageQueries = crate::parsers::LanguageQueries::new(&[
1316    SYMQ_0, SYMQ_1, SYMQ_2, SYMQ_3, SYMQ_4, SYMQ_5, SYMQ_6, SYMQ_7,
1317]);
1318
1319impl TypeScriptDependencyExtractor {
1320    /// Extract export/re-export statements for barrel export tracking
1321    ///
1322    /// Extracts:
1323    /// - `export * from './module'` (wildcard re-exports)
1324    /// - `export { Named } from './module'` (named re-exports)
1325    /// - `export { default as Name } from './module'` (default re-exports)
1326    ///
1327    /// Returns ExportInfo records with the exported symbol name (None for wildcard)
1328    /// and the source path. The indexer will resolve these to file IDs.
1329    pub fn extract_export_declarations(
1330        source: &str,
1331        _alias_map: Option<&crate::parsers::tsconfig::PathAliasMap>,
1332    ) -> Result<Vec<ExportInfo>> {
1333        let mut parser = Parser::new();
1334        let language = tree_sitter_typescript::LANGUAGE_TSX;
1335
1336        parser
1337            .set_language(&language.into())
1338            .context("Failed to set TypeScript/JavaScript language")?;
1339
1340        let tree = parser
1341            .parse(source, None)
1342            .context("Failed to parse TypeScript/JavaScript source for export extraction")?;
1343
1344        let root_node = tree.root_node();
1345
1346        let mut exports = Vec::new();
1347
1348        // Extract ES6 export statements with source paths
1349        exports.extend(extract_export_from_statements(source, &root_node)?);
1350
1351        Ok(exports)
1352    }
1353}
1354
1355/// Extract export statements that re-export from other modules
1356///
1357/// Handles:
1358/// - export * from './module'
1359/// - export { Named } from './module'
1360/// - export { Named as Alias } from './module'
1361/// - export { default as Name } from './module.vue'
1362fn extract_export_from_statements(
1363    source: &str,
1364    root: &tree_sitter::Node,
1365) -> Result<Vec<ExportInfo>> {
1366    let language = tree_sitter_typescript::LANGUAGE_TSX;
1367
1368    // Query for export statements with a source clause
1369    let query_str = r#"
1370        (export_statement
1371            source: (string) @source_path) @export
1372    "#;
1373
1374    static QUERY_3: crate::parsers::CachedQuery = crate::parsers::CachedQuery::new();
1375    let query = crate::parsers::cached_query(&QUERY_3, language, query_str)
1376        .context("Failed to create export statement query")?;
1377
1378    let mut cursor = QueryCursor::new();
1379    let mut matches = cursor.matches(query, *root, source.as_bytes());
1380
1381    let mut exports = Vec::new();
1382
1383    while let Some(match_) = matches.next() {
1384        let mut source_path = None;
1385        let mut export_node = None;
1386
1387        for capture in match_.captures {
1388            let capture_name: &str = query.capture_names()[capture.index as usize];
1389            match capture_name {
1390                "source_path" => {
1391                    // Remove quotes from string literal
1392                    let raw_path = capture.node.utf8_text(source.as_bytes()).unwrap_or("");
1393                    source_path = Some(
1394                        raw_path
1395                            .trim_matches(|c| c == '"' || c == '\'' || c == '`')
1396                            .to_string(),
1397                    );
1398                }
1399                "export" => {
1400                    export_node = Some(capture.node);
1401                }
1402                _ => {}
1403            }
1404        }
1405
1406        if let (Some(path), Some(node)) = (source_path, export_node) {
1407            let line_number = node.start_position().row + 1;
1408
1409            // Extract exported symbols from this export statement
1410            let exported_symbols = extract_exported_symbols(source, &node)?;
1411
1412            // If no specific symbols extracted (export *), create one entry with None
1413            if exported_symbols.is_empty() {
1414                exports.push(ExportInfo {
1415                    exported_symbol: None, // Wildcard export
1416                    source_path: path,
1417                    line_number,
1418                });
1419            } else {
1420                // Create one entry per exported symbol
1421                for symbol in exported_symbols {
1422                    exports.push(ExportInfo {
1423                        exported_symbol: Some(symbol),
1424                        source_path: path.clone(),
1425                        line_number,
1426                    });
1427                }
1428            }
1429        }
1430    }
1431
1432    Ok(exports)
1433}
1434
1435/// Extract the list of symbols being exported from an export statement
1436///
1437/// For `export { A, B as C } from './module'`, returns ["A", "B"]
1438/// For `export * from './module'`, returns empty vec (handled by caller)
1439fn extract_exported_symbols(source: &str, export_node: &tree_sitter::Node) -> Result<Vec<String>> {
1440    let mut symbols = Vec::new();
1441
1442    // Walk children to find export_clause
1443    let mut cursor = export_node.walk();
1444    for child in export_node.children(&mut cursor) {
1445        if child.kind() == "export_clause" {
1446            // Extract individual export specifiers
1447            let mut specifier_cursor = child.walk();
1448            for specifier in child.children(&mut specifier_cursor) {
1449                if specifier.kind() == "export_specifier" {
1450                    // Get the exported name (before "as" if aliased)
1451                    // For `export { foo as bar }`, we want "foo" (the original name)
1452                    if let Ok(text) = specifier.utf8_text(source.as_bytes()) {
1453                        // Parse "foo as bar" or just "foo"
1454                        let name = text.split_whitespace().next().unwrap_or(text);
1455                        symbols.push(name.to_string());
1456                    }
1457                }
1458            }
1459        }
1460    }
1461
1462    Ok(symbols)
1463}
1464
1465// ============================================================================
1466// Path Resolution
1467// ============================================================================
1468
1469/// Resolve a TypeScript/JavaScript import to a file path
1470///
1471/// Handles:
1472/// - Path aliases: `@packages/ui/store` → `../../packages/ui/store.ts` (requires tsconfig.json)
1473/// - Relative imports: `./components/Button` → `components/Button.tsx` or `components/Button/index.tsx`
1474/// - Parent directory imports: `../../utils/helper` → `../../utils/helper.ts`
1475/// - Index files: `./components` → `components/index.ts`
1476///
1477/// Does NOT handle:
1478/// - Node modules (external dependencies)
1479pub fn resolve_ts_import_to_path(
1480    import_path: &str,
1481    current_file_path: Option<&str>,
1482    alias_map: Option<&crate::parsers::tsconfig::PathAliasMap>,
1483) -> Option<String> {
1484    log::debug!(
1485        "resolve_ts_import_to_path: import_path={}, current_file={:?}, has_alias_map={}",
1486        import_path,
1487        current_file_path,
1488        alias_map.is_some()
1489    );
1490
1491    // Try path alias resolution first (if alias map is provided)
1492    if let Some(map) = alias_map {
1493        log::debug!(
1494            "  Trying alias resolution with {} aliases (config_dir: {:?}, base_url: {:?})",
1495            map.aliases.len(),
1496            map.config_dir,
1497            map.base_url
1498        );
1499        if let Some(resolved_alias) = map.resolve_alias(import_path) {
1500            log::debug!("  Alias matched! {} => {}", import_path, resolved_alias);
1501            // Alias matched! Now resolve relative to the tsconfig directory
1502            let resolved_path = map.resolve_relative_to_config(&resolved_alias);
1503            // Normalize to forward slashes for deterministic, cross-platform output.
1504            let path_str = resolved_path.to_string_lossy().replace('\\', "/");
1505            log::debug!("  After resolve_relative_to_config: {}", path_str);
1506
1507            // Check if resolved path has an extension
1508            let has_extension = path_str.ends_with(".vue")
1509                || path_str.ends_with(".svelte")
1510                || path_str.ends_with(".ts")
1511                || path_str.ends_with(".tsx")
1512                || path_str.ends_with(".js")
1513                || path_str.ends_with(".jsx")
1514                || path_str.ends_with(".mjs")
1515                || path_str.ends_with(".cjs");
1516
1517            if has_extension {
1518                log::trace!("Resolved alias {} => {}", import_path, path_str);
1519                return Some(path_str);
1520            }
1521
1522            // No extension - generate candidates
1523            let extensions = vec![
1524                ".tsx",
1525                ".ts",
1526                ".jsx",
1527                ".js",
1528                ".mjs",
1529                ".cjs",
1530                "/index.tsx",
1531                "/index.ts",
1532                "/index.jsx",
1533                "/index.js",
1534            ];
1535
1536            let candidates: Vec<String> = extensions
1537                .iter()
1538                .map(|ext| format!("{}{}", path_str, ext))
1539                .collect();
1540
1541            log::trace!(
1542                "Resolved alias {} => {} (candidates: {})",
1543                import_path,
1544                path_str,
1545                candidates.join(" | ")
1546            );
1547            return Some(candidates.join("|"));
1548        }
1549    }
1550
1551    // Fall back to relative import resolution
1552    // Only handle relative imports
1553    if !import_path.starts_with("./") && !import_path.starts_with("../") {
1554        return None;
1555    }
1556
1557    let current_file = current_file_path?;
1558
1559    // Get the directory of the current file
1560    let current_dir = std::path::Path::new(current_file).parent()?;
1561
1562    // Resolve the import path relative to current directory
1563    let resolved = current_dir.join(import_path);
1564
1565    // Normalize the path (resolve .. and . components)
1566    // Use components() to properly handle . and .. without requiring filesystem access
1567    let normalized_path = std::path::Path::new(&resolved).components().fold(
1568        std::path::PathBuf::new(),
1569        |mut acc, component| {
1570            match component {
1571                std::path::Component::CurDir => acc, // Skip .
1572                std::path::Component::ParentDir => {
1573                    acc.pop(); // Go up one level for ..
1574                    acc
1575                }
1576                _ => {
1577                    acc.push(component);
1578                    acc
1579                }
1580            }
1581        },
1582    );
1583
1584    // Normalize to forward slashes so the resolved path is deterministic
1585    // across platforms. `join`/`components` on Windows produces backslashes
1586    // which would otherwise break downstream string lookups.
1587    let normalized = normalized_path.to_string_lossy().replace('\\', "/");
1588
1589    // Check if the import already has a known extension
1590    // Vue/Svelte files are imported with their extension: import Foo from './Foo.vue'
1591    let has_extension = normalized.ends_with(".vue")
1592        || normalized.ends_with(".svelte")
1593        || normalized.ends_with(".ts")
1594        || normalized.ends_with(".tsx")
1595        || normalized.ends_with(".js")
1596        || normalized.ends_with(".jsx")
1597        || normalized.ends_with(".mjs")
1598        || normalized.ends_with(".cjs");
1599
1600    if has_extension {
1601        // Import already has an extension - just return it normalized
1602        log::trace!("TS/JS import with extension: {}", normalized);
1603        return Some(normalized);
1604    }
1605
1606    // No extension - try multiple file extensions in order of preference
1607    // TypeScript: .ts, .tsx, .d.ts
1608    // JavaScript: .js, .jsx, .mjs, .cjs
1609    // Also try index files if the import is a directory
1610    //
1611    // NOTE: We return a list of candidates separated by "|" delimiter
1612    // The indexer will try each one in order until it finds a match in the database
1613    let extensions = vec![
1614        ".tsx",
1615        ".ts",
1616        ".jsx",
1617        ".js",
1618        ".mjs",
1619        ".cjs",
1620        "/index.tsx",
1621        "/index.ts",
1622        "/index.jsx",
1623        "/index.js",
1624    ];
1625
1626    let candidates: Vec<String> = extensions
1627        .iter()
1628        .map(|ext| format!("{}{}", normalized, ext))
1629        .collect();
1630
1631    log::trace!(
1632        "TS/JS import candidates (no extension): {}",
1633        candidates.join(" | ")
1634    );
1635
1636    // Return all candidates as a pipe-delimited string
1637    // Format: "path.tsx|path.ts|path.jsx|path.js|..."
1638    Some(candidates.join("|"))
1639}
1640
1641#[cfg(test)]
1642mod path_resolution_tests {
1643    use super::*;
1644
1645    #[test]
1646    fn test_resolve_relative_import_same_directory() {
1647        // import { Button } from './Button'
1648        let result = resolve_ts_import_to_path("./Button", Some("src/components/App.tsx"), None);
1649
1650        assert!(result.is_some());
1651        let candidates = result.unwrap();
1652        // Should contain pipe-delimited candidates with .tsx first, then .ts, etc.
1653        assert!(candidates.contains("Button.tsx"));
1654        assert!(candidates.contains("Button.ts"));
1655        // First candidate should be .tsx
1656        assert!(
1657            candidates.starts_with("src/components/Button.tsx")
1658                || candidates.contains("/Button.tsx|")
1659        );
1660    }
1661
1662    #[test]
1663    fn test_resolve_relative_import_parent_directory() {
1664        // import { helper} from '../utils/helper'
1665        let result =
1666            resolve_ts_import_to_path("../utils/helper", Some("src/components/Button.tsx"), None);
1667
1668        assert!(result.is_some());
1669        let path = result.unwrap();
1670        assert!(path.contains("utils/helper"));
1671    }
1672
1673    #[test]
1674    fn test_resolve_relative_import_multiple_parents() {
1675        // import { config } from '../../config/app'
1676        let result = resolve_ts_import_to_path(
1677            "../../config/app",
1678            Some("src/components/ui/Button.tsx"),
1679            None,
1680        );
1681
1682        assert!(result.is_some());
1683        let path = result.unwrap();
1684        assert!(path.contains("config/app"));
1685    }
1686
1687    #[test]
1688    fn test_resolve_index_file() {
1689        // import { components } from './components' (should try ./components/index.tsx)
1690        let result = resolve_ts_import_to_path("./components", Some("src/App.tsx"), None);
1691
1692        assert!(result.is_some());
1693        // The function returns the first candidate, which is .tsx
1694        // In reality, the indexer would try each candidate
1695        assert!(result.unwrap().contains("components"));
1696    }
1697
1698    #[test]
1699    fn test_absolute_import_not_supported_without_alias_map() {
1700        // import { Button } from '@components/Button' (requires tsconfig.json)
1701        let result = resolve_ts_import_to_path("@components/Button", Some("src/App.tsx"), None);
1702
1703        // Should return None for absolute imports when no alias map provided
1704        assert!(result.is_none());
1705    }
1706
1707    #[test]
1708    fn test_node_modules_import_not_supported() {
1709        // import { React } from 'react'
1710        let result = resolve_ts_import_to_path("react", Some("src/App.tsx"), None);
1711
1712        // Should return None for node_modules imports
1713        assert!(result.is_none());
1714    }
1715
1716    #[test]
1717    fn test_resolve_without_current_file() {
1718        let result = resolve_ts_import_to_path("./Button", None, None);
1719
1720        // Should return None if no current file provided
1721        assert!(result.is_none());
1722    }
1723
1724    #[test]
1725    fn test_resolve_nested_directory_structure() {
1726        // import { api } from './api/client'
1727        let result = resolve_ts_import_to_path("./api/client", Some("src/services/http.ts"), None);
1728
1729        assert!(result.is_some());
1730        let path = result.unwrap();
1731        // Should resolve to src/services/api/client with an extension
1732        assert!(path.contains("api/client"));
1733    }
1734}
1735
1736#[cfg(test)]
1737mod dependency_extraction_tests {
1738    use super::*;
1739
1740    #[test]
1741    fn test_extract_basic_imports() {
1742        let source = r#"
1743            import { Button } from './components/Button';
1744            import React from 'react';
1745            import fs from 'fs';
1746            import '../styles.css';
1747        "#;
1748
1749        let deps = TypeScriptDependencyExtractor::extract_dependencies(source).unwrap();
1750
1751        assert_eq!(deps.len(), 4, "Should extract 4 import statements");
1752        assert!(
1753            deps.iter()
1754                .any(|d| d.imported_path == "./components/Button")
1755        );
1756        assert!(deps.iter().any(|d| d.imported_path == "react"));
1757        assert!(deps.iter().any(|d| d.imported_path == "fs"));
1758        assert!(deps.iter().any(|d| d.imported_path == "../styles.css"));
1759    }
1760
1761    #[test]
1762    fn test_dynamic_imports_filtered() {
1763        let source = r#"
1764            import { Button } from './components/Button';
1765            import React from 'react';
1766            const fs = require('fs');
1767
1768            // Dynamic imports - should be filtered out
1769            const moduleName = './dynamic-module';
1770            import(moduleName);
1771            import(`./templates/${template}`);
1772            require(variable);
1773            require(CONFIG_PATH + '/settings.js');
1774        "#;
1775
1776        let deps = TypeScriptDependencyExtractor::extract_dependencies(source).unwrap();
1777
1778        // Should only find static imports (Button, React, fs)
1779        // Variable and template literal imports are filtered (not (string) nodes)
1780        assert_eq!(deps.len(), 3, "Should extract 3 static imports only");
1781
1782        assert!(
1783            deps.iter()
1784                .any(|d| d.imported_path == "./components/Button")
1785        );
1786        assert!(deps.iter().any(|d| d.imported_path == "react"));
1787        assert!(deps.iter().any(|d| d.imported_path == "fs"));
1788
1789        // Verify dynamic imports are NOT captured
1790        assert!(!deps.iter().any(|d| d.imported_path.contains("moduleName")));
1791        assert!(!deps.iter().any(|d| d.imported_path.contains("template")));
1792        assert!(!deps.iter().any(|d| d.imported_path.contains("variable")));
1793        assert!(!deps.iter().any(|d| d.imported_path.contains("CONFIG_PATH")));
1794    }
1795
1796    #[test]
1797    fn test_require_with_template_literals_filtered() {
1798        let source = r#"
1799            const path = require('path');
1800            const utils = require('./utils');
1801
1802            // Dynamic requires with template literals - should be filtered out
1803            const config = require(`./config/${env}.json`);
1804            const plugin = require(`${PLUGIN_DIR}/loader`);
1805        "#;
1806
1807        let deps = TypeScriptDependencyExtractor::extract_dependencies(source).unwrap();
1808
1809        // Should only find static requires (path, ./utils)
1810        // Template literal requires are filtered (template_string nodes, not string nodes)
1811        assert_eq!(deps.len(), 2, "Should extract 2 static requires only");
1812
1813        assert!(deps.iter().any(|d| d.imported_path == "path"));
1814        assert!(deps.iter().any(|d| d.imported_path == "./utils"));
1815
1816        // Verify dynamic requires are NOT captured
1817        assert!(!deps.iter().any(|d| d.imported_path.contains("env")));
1818        assert!(!deps.iter().any(|d| d.imported_path.contains("PLUGIN_DIR")));
1819    }
1820}