Skip to main content

sqry_lang_javascript/relations/
graph_builder.rs

1use std::{
2    collections::HashMap,
3    path::Path,
4    sync::{Arc, OnceLock},
5};
6
7use sqry_core::graph::unified::build::helper::CalleeKindHint;
8use sqry_core::graph::unified::build::shape::{CfBucket, ShapeMapping};
9use sqry_core::graph::unified::edge::kind::TypeOfContext;
10use sqry_core::graph::unified::edge::{ExportKind, FfiConvention, HttpMethod};
11use sqry_core::graph::unified::storage::shape::SignatureShape;
12use sqry_core::graph::unified::{GraphBuildHelper, NodeId, StagingGraph};
13use sqry_core::graph::{GraphBuilder, GraphBuilderError, GraphResult, Language, Position, Span};
14use sqry_core::relations::SyntheticNameBuilder;
15use tree_sitter::{Node, Tree};
16
17use super::jsdoc_parser::{extract_jsdoc_comment, parse_jsdoc_tags};
18use super::local_scopes;
19use super::type_extractor::{canonical_type_string, extract_type_names};
20
21const DEFAULT_SCOPE_DEPTH: usize = 4;
22type CallEdgeData = (NodeId, NodeId, u8, bool, Option<Span>);
23type ConstructorEdgeData = (NodeId, NodeId, u8, Option<Span>);
24
25/// Graph builder for JavaScript files using unified `CodeGraph` architecture.
26#[derive(Debug, Clone, Copy)]
27pub struct JavaScriptGraphBuilder {
28    max_scope_depth: usize,
29}
30
31impl Default for JavaScriptGraphBuilder {
32    fn default() -> Self {
33        Self {
34            max_scope_depth: DEFAULT_SCOPE_DEPTH,
35        }
36    }
37}
38
39impl JavaScriptGraphBuilder {
40    #[must_use]
41    pub fn new(max_scope_depth: usize) -> Self {
42        Self { max_scope_depth }
43    }
44}
45
46/// Infer visibility from JavaScript naming convention.
47/// Functions/methods starting with underscore are considered private.
48fn infer_visibility(qualified_name: &str) -> &'static str {
49    // For qualified names like "MyClass._privateMethod", check the method name part
50    let name_part = qualified_name.rsplit('.').next().unwrap_or(qualified_name);
51    if name_part.starts_with('_') {
52        "private"
53    } else {
54        "public"
55    }
56}
57
58impl GraphBuilder for JavaScriptGraphBuilder {
59    fn build_graph(
60        &self,
61        tree: &Tree,
62        content: &[u8],
63        file: &Path,
64        staging: &mut StagingGraph,
65    ) -> GraphResult<()> {
66        // Initialize the helper for this file
67        let mut helper = GraphBuildHelper::new(staging, file, Language::JavaScript);
68        let file_arc = Arc::from(file.to_string_lossy().to_string());
69
70        // Build AST graph for context resolution
71        let ast_graph = ASTGraph::from_tree(tree, content, self.max_scope_depth).map_err(|e| {
72            GraphBuilderError::ParseError {
73                span: Span::default(),
74                reason: e,
75            }
76        })?;
77
78        // Create function/method nodes for all callables
79        for context in ast_graph.contexts() {
80            let span = Some(Span::from_bytes(context.span.0, context.span.1));
81            // Infer visibility from naming convention: leading underscore = private
82            let visibility = infer_visibility(&context.qualified_name);
83
84            // Determine if this is a method (contains a dot indicating it's in a class)
85            if context.qualified_name.contains('.') {
86                helper.add_method_with_visibility(
87                    &context.qualified_name,
88                    span,
89                    context.is_async,
90                    false, // is_static - we don't track this in CallContext
91                    Some(visibility),
92                );
93            } else {
94                helper.add_function_with_visibility(
95                    &context.qualified_name,
96                    span,
97                    context.is_async,
98                    false, // is_unsafe - N/A for JavaScript
99                    Some(visibility),
100                );
101            }
102        }
103
104        // Build local scope tree for variable reference resolution
105        let mut scope_tree = local_scopes::build(tree.root_node(), content)?;
106
107        // Walk the AST to find and build edges
108        let mut cursor = tree.root_node().walk();
109        extract_edges_recursive(
110            tree.root_node(),
111            &mut cursor,
112            content,
113            &file_arc,
114            &ast_graph,
115            &mut helper,
116            &mut scope_tree,
117        )?;
118
119        // Second pass: Process JSDoc annotations for TypeOf and Reference edges
120        process_jsdoc_annotations(tree.root_node(), content, &mut helper)?;
121
122        Ok(())
123    }
124
125    fn language(&self) -> Language {
126        Language::JavaScript
127    }
128
129    fn shape_mapping(&self) -> Option<&dyn ShapeMapping> {
130        Some(javascript_shape_mapping())
131    }
132}
133
134/// Per-language [`ShapeMapping`] for JavaScript.
135///
136/// Holds a precomputed `kind_id -> CfBucket` table built once from the
137/// tree-sitter-javascript grammar and shared process-wide via
138/// [`javascript_shape_mapping`]. Everything except this mapping is the one
139/// shared `compute_shape_descriptor` routine.
140pub struct JavaScriptShapeMapping {
141    cf_by_kind_id: Vec<Option<CfBucket>>,
142}
143
144impl JavaScriptShapeMapping {
145    /// Build the `kind_id -> CfBucket` table from the tree-sitter-javascript grammar.
146    fn build() -> Self {
147        let lang: tree_sitter::Language = tree_sitter_javascript::LANGUAGE.into();
148        let count = lang.node_kind_count();
149        let mut cf_by_kind_id = vec![None; count];
150        for (id, slot) in cf_by_kind_id.iter_mut().enumerate() {
151            let Ok(kind_id) = u16::try_from(id) else {
152                break;
153            };
154            if !lang.node_kind_is_named(kind_id) {
155                continue;
156            }
157            if let Some(name) = lang.node_kind_for_id(kind_id) {
158                *slot = cf_bucket_for_javascript_kind(name);
159            }
160        }
161        Self { cf_by_kind_id }
162    }
163}
164
165impl ShapeMapping for JavaScriptShapeMapping {
166    fn cf_bucket(&self, ts_node_kind_id: u16) -> Option<CfBucket> {
167        self.cf_by_kind_id
168            .get(ts_node_kind_id as usize)
169            .copied()
170            .flatten()
171    }
172
173    fn signature_shape(&self, fn_node: Node, _src: &[u8]) -> SignatureShape {
174        let mut shape = SignatureShape::default();
175        if let Some(params) = fn_node.child_by_field_name("parameters") {
176            let mut cursor = params.walk();
177            for child in params.named_children(&mut cursor) {
178                match child.kind() {
179                    // Plain or destructured positional parameter.
180                    "identifier" | "object_pattern" | "array_pattern" => {
181                        shape.arity_positional = shape.arity_positional.saturating_add(1);
182                    }
183                    // `x = 1` default initializer.
184                    "assignment_pattern" => {
185                        shape.arity_positional = shape.arity_positional.saturating_add(1);
186                        shape.has_defaults = true;
187                    }
188                    // `...rest` variadic.
189                    "rest_pattern" => shape.has_varargs = true,
190                    _ => {}
191                }
192            }
193        }
194        // JavaScript carries no return-type annotation in the grammar.
195        shape
196    }
197}
198
199/// Map one tree-sitter-javascript grammar node-kind name to its canonical
200/// control-flow bucket. Additive-only; the bucket set is frozen.
201fn cf_bucket_for_javascript_kind(name: &str) -> Option<CfBucket> {
202    let bucket = match name {
203        "if_statement" | "ternary_expression" => CfBucket::Branch,
204        "for_statement" | "for_in_statement" | "while_statement" | "do_statement" => CfBucket::Loop,
205        "switch_statement" | "switch_case" | "switch_default" => CfBucket::Match,
206        "try_statement" => CfBucket::Try,
207        "catch_clause" => CfBucket::Catch,
208        "throw_statement" => CfBucket::Throw,
209        "return_statement" => CfBucket::Return,
210        "yield_expression" => CfBucket::Yield,
211        "await_expression" => CfBucket::Await,
212        "break_statement" | "continue_statement" => CfBucket::BreakContinue,
213        "call_expression" | "new_expression" => CfBucket::Call,
214        "lexical_declaration"
215        | "variable_declaration"
216        | "assignment_expression"
217        | "augmented_assignment_expression" => CfBucket::Assign,
218        "arrow_function" | "function_expression" => CfBucket::Closure,
219        _ => return None,
220    };
221    Some(bucket)
222}
223
224/// The process-wide JavaScript shape mapping, built once on first use.
225#[must_use]
226pub fn javascript_shape_mapping() -> &'static JavaScriptShapeMapping {
227    static MAPPING: OnceLock<JavaScriptShapeMapping> = OnceLock::new();
228    MAPPING.get_or_init(JavaScriptShapeMapping::build)
229}
230
231/// Recursively extract edges (calls, constructors, imports) from the AST
232fn extract_edges_recursive<'a>(
233    node: Node<'a>,
234    cursor: &mut tree_sitter::TreeCursor<'a>,
235    content: &[u8],
236    file: &Arc<str>,
237    ast_graph: &ASTGraph,
238    helper: &mut GraphBuildHelper,
239    scope_tree: &mut local_scopes::JavaScriptScopeTree,
240) -> GraphResult<()> {
241    match node.kind() {
242        "call_expression" => {
243            // Add HTTP request edges when applicable (fetch/axios patterns)
244            let _ = build_http_request_edge(ast_graph, node, content, helper);
245            // Detect Express/Koa/Fastify route endpoint registrations
246            let _ = detect_route_endpoint(node, content, helper);
247            // Check for FFI patterns first (WebAssembly, native addons)
248            let is_ffi = build_ffi_call_edge(ast_graph, node, content, helper)?;
249            if !is_ffi {
250                // Not an FFI call - process as regular call
251                if let Some((caller_id, callee_id, argument_count, is_async, span)) =
252                    build_call_edge_with_helper(ast_graph, node, content, helper)?
253                {
254                    helper.add_call_edge_full_with_span(
255                        caller_id,
256                        callee_id,
257                        argument_count,
258                        is_async,
259                        span.into_iter().collect(),
260                    );
261                }
262            }
263        }
264        "new_expression" => {
265            // Check for WebAssembly constructor patterns
266            let is_ffi = build_ffi_new_edge(ast_graph, node, content, helper)?;
267            if !is_ffi {
268                // Not an FFI constructor - process as regular constructor
269                if let Some((caller_id, callee_id, argument_count, span)) =
270                    build_constructor_edge_with_helper(ast_graph, node, content, helper)?
271                {
272                    helper.add_call_edge_full_with_span(
273                        caller_id,
274                        callee_id,
275                        argument_count,
276                        false,
277                        span.into_iter().collect(),
278                    );
279                }
280            }
281        }
282        "import_statement" => {
283            if let Some((from_id, to_id)) =
284                build_import_edge_with_helper(node, content, file, helper)?
285            {
286                helper.add_import_edge(from_id, to_id);
287            }
288        }
289        "export_statement" => {
290            build_export_edges_with_helper(node, content, file, helper);
291        }
292        "expression_statement" => {
293            // Check for CommonJS export patterns
294            build_commonjs_export_edges(node, content, helper);
295        }
296        "class_declaration" | "class" => {
297            build_inherits_edge_with_helper(node, content, helper);
298        }
299        "identifier" => {
300            local_scopes::handle_identifier_for_reference(node, content, scope_tree, helper);
301        }
302        _ => {}
303    }
304
305    // Recursively process children
306    // Collect children into a vec to avoid borrowing issues
307    let children: Vec<_> = node.children(cursor).collect();
308    for child in children {
309        let mut child_cursor = child.walk();
310        extract_edges_recursive(
311            child,
312            &mut child_cursor,
313            content,
314            file,
315            ast_graph,
316            helper,
317            scope_tree,
318        )?;
319    }
320
321    Ok(())
322}
323
324/// Build a call edge using `GraphBuildHelper`
325fn build_call_edge_with_helper(
326    ast_graph: &ASTGraph,
327    call_node: Node<'_>,
328    content: &[u8],
329    helper: &mut GraphBuildHelper,
330) -> GraphResult<Option<CallEdgeData>> {
331    // Get or create module-level context for top-level calls
332    let module_context;
333    let call_context = if let Some(ctx) = ast_graph.get_callable_context(call_node.id()) {
334        ctx
335    } else {
336        // Create synthetic module-level context for top-level calls
337        module_context = CallContext {
338            name: Arc::from("<module>"),
339            qualified_name: "<module>".to_string(),
340            span: (0, content.len()),
341            is_async: false,
342        };
343        &module_context
344    };
345
346    let Some(callee_expr) = call_node.child_by_field_name("function") else {
347        return Ok(None);
348    };
349
350    let raw_callee_text = callee_expr
351        .utf8_text(content)
352        .map_err(|_| GraphBuilderError::ParseError {
353            span: span_from_node(call_node),
354            reason: "failed to read call expression".to_string(),
355        })?
356        .trim()
357        .to_string();
358
359    // Normalize optional chain syntax
360    let callee_text = if raw_callee_text.contains("?.") {
361        normalize_optional_chain(&raw_callee_text)
362    } else {
363        raw_callee_text
364    };
365
366    if callee_text.is_empty() {
367        return Ok(None);
368    }
369
370    let callee_simple = simple_name(&callee_text);
371    if callee_simple.is_empty() {
372        return Ok(None);
373    }
374
375    // Derive qualified callee name with proper this/super resolution
376    let caller_qname = call_context.qualified_name();
377    let target_qname = if let Some(method_name) = callee_text.strip_prefix("this.") {
378        // Resolve this.method() to ClassName.method()
379        if let Some(scope_idx) = caller_qname.rfind('.') {
380            let class_name = &caller_qname[..scope_idx];
381            format!("{}.{}", class_name, simple_name(method_name))
382        } else {
383            callee_text.clone()
384        }
385    } else if callee_text.starts_with("super.") || callee_text.contains('.') {
386        callee_text.clone()
387    } else {
388        callee_simple.to_string()
389    };
390
391    // Ensure nodes exist using helper
392    let source_id = ensure_caller_node(helper, call_context);
393    let call_site_span = span_from_node(call_node);
394    let target_id = helper.ensure_callee(&target_qname, call_site_span, CalleeKindHint::Function);
395
396    let span = Some(call_site_span);
397    let argument_count = u8::try_from(count_arguments(call_node)).unwrap_or(u8::MAX);
398    let is_async = check_uses_await(call_node);
399
400    Ok(Some((source_id, target_id, argument_count, is_async, span)))
401}
402
403#[derive(Debug, Clone)]
404struct HttpRequestInfo {
405    method: HttpMethod,
406    url: Option<String>,
407}
408
409fn build_http_request_edge(
410    ast_graph: &ASTGraph,
411    call_node: Node<'_>,
412    content: &[u8],
413    helper: &mut GraphBuildHelper,
414) -> bool {
415    let Some(info) = extract_http_request_info(call_node, content) else {
416        return false;
417    };
418
419    let caller_id = get_caller_node_id(ast_graph, call_node, content, helper);
420    let target_name = info.url.as_ref().map_or_else(
421        || format!("http::{}", info.method.as_str()),
422        |url| format!("http::{url}"),
423    );
424    let target_id = helper.add_module(&target_name, Some(span_from_node(call_node)));
425
426    helper.add_http_request_edge(caller_id, target_id, info.method, info.url.as_deref());
427    true
428}
429
430/// Detect Express/Koa/Fastify-style route endpoint registrations.
431///
432/// Matches patterns like:
433/// - `app.get("/api/users", handler)` -> Endpoint node `route::GET::/api/users`
434/// - `router.post("/api/items", handler)` -> Endpoint node `route::POST::/api/items`
435/// - `app.delete("/api/items/:id", handler)` -> Endpoint node `route::DELETE::/api/items/:id`
436/// - `server.all("/health", handler)` -> Endpoint node `route::ALL::/health`
437///
438/// The receiver can be any variable name (app, router, server, etc.).
439/// Creates an Endpoint node with qualified name `route::METHOD::/path` and a
440/// Contains edge from the endpoint to the handler function if identifiable.
441///
442/// Returns `true` if a route endpoint was detected, `false` otherwise.
443fn detect_route_endpoint(
444    call_node: Node<'_>,
445    content: &[u8],
446    helper: &mut GraphBuildHelper,
447) -> bool {
448    // The callee must be a member_expression (e.g., `app.get`)
449    let Some(callee) = call_node.child_by_field_name("function") else {
450        return false;
451    };
452
453    if callee.kind() != "member_expression" {
454        return false;
455    }
456
457    // Extract the property name (the HTTP method)
458    let Some(property) = callee.child_by_field_name("property") else {
459        return false;
460    };
461
462    let Ok(method_name) = property.utf8_text(content) else {
463        return false;
464    };
465    let method_name = method_name.trim();
466
467    // Map the property name to an HTTP method string for the qualified name
468    let method_str = match method_name {
469        "get" => "GET",
470        "post" => "POST",
471        "put" => "PUT",
472        "delete" => "DELETE",
473        "patch" => "PATCH",
474        "all" => "ALL",
475        _ => return false,
476    };
477
478    // Extract the first argument which should be the route path string
479    let Some(args) = call_node.child_by_field_name("arguments") else {
480        return false;
481    };
482
483    let mut cursor = args.walk();
484    let first_arg = args
485        .children(&mut cursor)
486        .find(|child| !matches!(child.kind(), "(" | ")" | ","));
487
488    let Some(first_arg) = first_arg else {
489        return false;
490    };
491
492    // The first argument must be a string literal containing the path
493    let Some(path) = extract_string_literal(&first_arg, content) else {
494        return false;
495    };
496
497    // Build the qualified endpoint name: route::METHOD::/path
498    let qualified_name = format!("route::{method_str}::{path}");
499
500    // Create the Endpoint node
501    let endpoint_id = helper.add_endpoint(&qualified_name, Some(span_from_node(call_node)));
502
503    // Try to find and link the handler function (second argument)
504    // Supports: identifier references, member expressions
505    let mut handler_cursor = args.walk();
506    let handler_arg = args
507        .children(&mut handler_cursor)
508        .filter(|child| !matches!(child.kind(), "(" | ")" | ","))
509        .nth(1);
510
511    if let Some(handler_node) = handler_arg
512        && let Ok(handler_text) = handler_node.utf8_text(content)
513    {
514        let handler_name = handler_text.trim();
515        if !handler_name.is_empty()
516            && matches!(handler_node.kind(), "identifier" | "member_expression")
517        {
518            let handler_id = helper.ensure_callee(
519                handler_name,
520                span_from_node(handler_node),
521                CalleeKindHint::Function,
522            );
523            helper.add_contains_edge(endpoint_id, handler_id);
524        }
525    }
526
527    true
528}
529
530fn extract_http_request_info(call_node: Node<'_>, content: &[u8]) -> Option<HttpRequestInfo> {
531    let callee = call_node.child_by_field_name("function")?;
532    let callee_text = callee.utf8_text(content).ok()?.trim().to_string();
533
534    if callee_text == "fetch" {
535        return Some(extract_fetch_http_info(call_node, content));
536    }
537
538    if callee_text == "axios" {
539        return extract_axios_http_info(call_node, content);
540    }
541
542    if let Some(method_name) = callee_text.strip_prefix("axios.") {
543        let method = http_method_from_name(method_name)?;
544        let url = extract_first_arg_url(call_node, content);
545        return Some(HttpRequestInfo { method, url });
546    }
547
548    None
549}
550
551fn extract_fetch_http_info(call_node: Node<'_>, content: &[u8]) -> HttpRequestInfo {
552    let url = extract_first_arg_url(call_node, content);
553    let method = extract_method_from_options(call_node, content).unwrap_or(HttpMethod::Get);
554    HttpRequestInfo { method, url }
555}
556
557fn extract_axios_http_info(call_node: Node<'_>, content: &[u8]) -> Option<HttpRequestInfo> {
558    let args = call_node.child_by_field_name("arguments")?;
559    let mut cursor = args.walk();
560    let mut non_trivia = args
561        .children(&mut cursor)
562        .filter(|child| !matches!(child.kind(), "(" | ")" | ","));
563
564    let first_arg = non_trivia.next()?;
565    let second_arg = non_trivia.next();
566
567    if first_arg.kind() == "object" {
568        let (method, url) = extract_method_and_url_from_object(first_arg, content);
569        return Some(HttpRequestInfo {
570            method: method.unwrap_or(HttpMethod::Get),
571            url,
572        });
573    }
574
575    let url = extract_string_literal(&first_arg, content);
576    let method = if let Some(config) = second_arg {
577        if config.kind() == "object" {
578            extract_method_from_object(config, content)
579        } else {
580            None
581        }
582    } else {
583        None
584    };
585
586    Some(HttpRequestInfo {
587        method: method.unwrap_or(HttpMethod::Get),
588        url,
589    })
590}
591
592fn extract_first_arg_url(call_node: Node<'_>, content: &[u8]) -> Option<String> {
593    let args = call_node.child_by_field_name("arguments")?;
594    let mut cursor = args.walk();
595    let first_arg = args
596        .children(&mut cursor)
597        .find(|child| !matches!(child.kind(), "(" | ")" | ","))?;
598    extract_string_literal(&first_arg, content)
599}
600
601fn extract_method_from_options(call_node: Node<'_>, content: &[u8]) -> Option<HttpMethod> {
602    let args = call_node.child_by_field_name("arguments")?;
603    let mut cursor = args.walk();
604    let mut non_trivia = args
605        .children(&mut cursor)
606        .filter(|child| !matches!(child.kind(), "(" | ")" | ","));
607
608    let _first_arg = non_trivia.next()?;
609    let second_arg = non_trivia.next()?;
610    if second_arg.kind() != "object" {
611        return None;
612    }
613
614    extract_method_from_object(second_arg, content)
615}
616
617fn extract_method_from_object(obj_node: Node<'_>, content: &[u8]) -> Option<HttpMethod> {
618    let (method, _url) = extract_method_and_url_from_object(obj_node, content);
619    method
620}
621
622fn extract_method_and_url_from_object(
623    obj_node: Node<'_>,
624    content: &[u8],
625) -> (Option<HttpMethod>, Option<String>) {
626    let mut method = None;
627    let mut url = None;
628    let mut cursor = obj_node.walk();
629
630    for child in obj_node.children(&mut cursor) {
631        if child.kind() != "pair" {
632            continue;
633        }
634
635        let Some(key_node) = child.child_by_field_name("key") else {
636            continue;
637        };
638        let key_text = extract_object_key_text(&key_node, content);
639
640        let Some(value_node) = child.child_by_field_name("value") else {
641            continue;
642        };
643
644        if key_text.as_deref() == Some("method") {
645            if let Some(value) = extract_string_literal(&value_node, content) {
646                method = http_method_from_name(&value);
647            }
648        } else if key_text.as_deref() == Some("url") {
649            url = extract_string_literal(&value_node, content);
650        }
651    }
652
653    (method, url)
654}
655
656fn extract_object_key_text(node: &Node<'_>, content: &[u8]) -> Option<String> {
657    let raw = node.utf8_text(content).ok()?.trim().to_string();
658    if let Some(value) = extract_string_literal(node, content) {
659        return Some(value);
660    }
661    if raw.is_empty() {
662        return None;
663    }
664    Some(raw)
665}
666
667fn http_method_from_name(name: &str) -> Option<HttpMethod> {
668    match name.trim().to_ascii_lowercase().as_str() {
669        "get" => Some(HttpMethod::Get),
670        "post" => Some(HttpMethod::Post),
671        "put" => Some(HttpMethod::Put),
672        "delete" => Some(HttpMethod::Delete),
673        "patch" => Some(HttpMethod::Patch),
674        "head" => Some(HttpMethod::Head),
675        "options" => Some(HttpMethod::Options),
676        _ => None,
677    }
678}
679
680/// Build a constructor edge using `GraphBuildHelper`
681fn build_constructor_edge_with_helper(
682    ast_graph: &ASTGraph,
683    new_node: Node<'_>,
684    content: &[u8],
685    helper: &mut GraphBuildHelper,
686) -> GraphResult<Option<ConstructorEdgeData>> {
687    // Get or create module-level context
688    let module_context;
689    let call_context = if let Some(ctx) = ast_graph.get_callable_context(new_node.id()) {
690        ctx
691    } else {
692        module_context = CallContext {
693            name: Arc::from("<module>"),
694            qualified_name: "<module>".to_string(),
695            span: (0, content.len()),
696            is_async: false,
697        };
698        &module_context
699    };
700
701    let Some(constructor_expr) = new_node.child_by_field_name("constructor") else {
702        return Ok(None);
703    };
704
705    let constructor_text = constructor_expr
706        .utf8_text(content)
707        .map_err(|_| GraphBuilderError::ParseError {
708            span: span_from_node(new_node),
709            reason: "failed to read constructor expression".to_string(),
710        })?
711        .trim()
712        .to_string();
713
714    if constructor_text.is_empty() {
715        return Ok(None);
716    }
717
718    let constructor_simple = simple_name(&constructor_text);
719    let source_id = ensure_caller_node(helper, call_context);
720    let new_site_span = span_from_node(new_node);
721    let target_id =
722        helper.ensure_callee(constructor_simple, new_site_span, CalleeKindHint::Function);
723
724    let span = Some(new_site_span);
725    let argument_count = u8::try_from(count_arguments(new_node)).unwrap_or(u8::MAX);
726
727    Ok(Some((source_id, target_id, argument_count, span)))
728}
729
730/// Build an import edge using `GraphBuildHelper`
731fn build_import_edge_with_helper(
732    import_node: Node<'_>,
733    content: &[u8],
734    file: &Arc<str>,
735    helper: &mut GraphBuildHelper,
736) -> GraphResult<
737    Option<(
738        sqry_core::graph::unified::NodeId,
739        sqry_core::graph::unified::NodeId,
740    )>,
741> {
742    let Some(source_node) = import_node.child_by_field_name("source") else {
743        return Ok(None);
744    };
745
746    let source_text = source_node
747        .utf8_text(content)
748        .map_err(|_| GraphBuilderError::ParseError {
749            span: span_from_node(import_node),
750            reason: "failed to read import source".to_string(),
751        })?
752        .trim()
753        .trim_matches(|c| c == '"' || c == '\'')
754        .to_string();
755
756    if source_text.is_empty() {
757        return Ok(None);
758    }
759
760    // Resolve the import path
761    let resolved_path =
762        sqry_core::graph::resolve_import_path(std::path::Path::new(file.as_ref()), &source_text)?;
763
764    // Create module nodes
765    let from_id = helper.add_module("<module>", None);
766    let to_id = helper.add_import(&resolved_path, Some(span_from_node(import_node)));
767
768    Ok(Some((from_id, to_id)))
769}
770
771/// Build export edges from an `export_statement` node.
772///
773/// Handles all JavaScript/ESM export forms:
774/// - `export default foo` -> Default export
775/// - `export { name }` -> Named export (Direct)
776/// - `export { name as alias }` -> Named export with alias
777/// - `export * from 'module'` -> Wildcard re-export
778/// - `export { name } from 'module'` -> Named re-export
779/// - `export * as ns from 'module'` -> Namespace re-export
780/// - `export function/class/const` -> Declaration exports (Direct)
781#[allow(clippy::too_many_lines)]
782fn build_export_edges_with_helper(
783    export_node: Node<'_>,
784    content: &[u8],
785    file: &Arc<str>,
786    helper: &mut GraphBuildHelper,
787) {
788    // Get the module node (exporter)
789    let module_id = helper.add_module("<module>", None);
790
791    // Check for re-export: has a "source" (from clause)
792    let source_node = export_node.child_by_field_name("source");
793    let is_reexport = source_node.is_some();
794
795    // Check for default export
796    let has_default = export_node
797        .children(&mut export_node.walk())
798        .any(|child| child.kind() == "default");
799
800    // Check for namespace export: `export * as ns from 'module'`
801    let namespace_export = export_node
802        .children(&mut export_node.walk())
803        .find(|child| child.kind() == "namespace_export");
804
805    // Check for wildcard: `export * from 'module'`
806    let has_wildcard = export_node
807        .children(&mut export_node.walk())
808        .any(|child| child.kind() == "*");
809
810    // Check for export clause: `export { foo, bar }`
811    let export_clause = export_node
812        .children(&mut export_node.walk())
813        .find(|child| child.kind() == "export_clause");
814
815    // Check for declaration export: `export function/class/const/let/var`
816    let declaration = export_node.children(&mut export_node.walk()).find(|child| {
817        matches!(
818            child.kind(),
819            "function_declaration"
820                | "class_declaration"
821                | "lexical_declaration"
822                | "variable_declaration"
823                | "generator_function_declaration"
824        )
825    });
826
827    if has_default {
828        // Default export: `export default foo` or `export default function foo() {}`
829        // Find the exported item (identifier, function, class, etc.)
830        let exported_name = if let Some(ref decl) = declaration {
831            // export default function foo() {} or export default class Bar {}
832            decl.child_by_field_name("name")
833                .and_then(|n| n.utf8_text(content).ok())
834                .map_or_else(|| "default".to_string(), |s| s.trim().to_string())
835        } else {
836            // export default identifier
837            export_node
838                .children(&mut export_node.walk())
839                .find(|child| child.kind() == "identifier")
840                .and_then(|n| n.utf8_text(content).ok())
841                .map_or_else(|| "default".to_string(), |s| s.trim().to_string())
842        };
843
844        let exported_id = helper.add_function(&exported_name, None, false, false);
845        helper.add_export_edge_full(module_id, exported_id, ExportKind::Default, None);
846    } else if let Some(ns_export) = namespace_export {
847        // Namespace re-export: `export * as ns from 'module'`
848        // Get the namespace alias from the namespace_export node
849        let alias = ns_export
850            .children(&mut ns_export.walk())
851            .find(|child| child.kind() == "identifier")
852            .and_then(|n| n.utf8_text(content).ok())
853            .map(|s| s.trim().to_string());
854
855        // Create a node representing the source module
856        let source_path = source_node
857            .and_then(|s| s.utf8_text(content).ok())
858            .map_or_else(
859                || "<unknown>".to_string(),
860                |s| s.trim().trim_matches(|c| c == '"' || c == '\'').to_string(),
861            );
862
863        let resolved_path = sqry_core::graph::resolve_import_path(
864            std::path::Path::new(file.as_ref()),
865            &source_path,
866        )
867        .unwrap_or(source_path);
868
869        let source_module_id = helper.add_module(&resolved_path, None);
870        helper.add_export_edge_full(
871            module_id,
872            source_module_id,
873            ExportKind::Namespace,
874            alias.as_deref(),
875        );
876    } else if has_wildcard && is_reexport {
877        // Wildcard re-export: `export * from 'module'`
878        let source_path = source_node
879            .and_then(|s| s.utf8_text(content).ok())
880            .map_or_else(
881                || "<unknown>".to_string(),
882                |s| s.trim().trim_matches(|c| c == '"' || c == '\'').to_string(),
883            );
884
885        let resolved_path = sqry_core::graph::resolve_import_path(
886            std::path::Path::new(file.as_ref()),
887            &source_path,
888        )
889        .unwrap_or(source_path);
890
891        let source_module_id = helper.add_module(&resolved_path, None);
892        // Wildcard re-export uses Reexport kind with no alias
893        helper.add_export_edge_full(module_id, source_module_id, ExportKind::Reexport, None);
894    } else if let Some(clause) = export_clause {
895        // Named exports: `export { foo, bar }` or `export { foo } from 'module'`
896        let mut cursor = clause.walk();
897        for child in clause.children(&mut cursor) {
898            if child.kind() == "export_specifier" {
899                // Get the identifiers from the export specifier
900                // First identifier is the local name, second (if present) is the alias
901                let identifiers: Vec<_> = child
902                    .children(&mut child.walk())
903                    .filter(|n| n.kind() == "identifier")
904                    .collect();
905
906                if let Some(first_ident) = identifiers.first() {
907                    let local_name = first_ident
908                        .utf8_text(content)
909                        .ok()
910                        .map(|s| s.trim().to_string())
911                        .unwrap_or_default();
912
913                    if local_name.is_empty() {
914                        continue;
915                    }
916
917                    // Check if there's an alias (second identifier)
918                    let alias = identifiers.get(1).and_then(|n| {
919                        n.utf8_text(content)
920                            .ok()
921                            .map(|s| s.trim().to_string())
922                            .filter(|s| !s.is_empty())
923                    });
924
925                    let exported_id = helper.add_function(&local_name, None, false, false);
926
927                    let kind = if is_reexport {
928                        ExportKind::Reexport
929                    } else {
930                        ExportKind::Direct
931                    };
932
933                    helper.add_export_edge_full(module_id, exported_id, kind, alias.as_deref());
934                }
935            }
936        }
937    } else if let Some(decl) = declaration {
938        // Declaration export: `export function foo() {}` or `export const x = 1;`
939        match decl.kind() {
940            "function_declaration" | "generator_function_declaration" => {
941                if let Some(name_node) = decl.child_by_field_name("name")
942                    && let Ok(name) = name_node.utf8_text(content)
943                {
944                    let name = name.trim().to_string();
945                    if !name.is_empty() {
946                        let exported_id = helper.add_function(&name, None, false, false);
947                        helper.add_export_edge_full(
948                            module_id,
949                            exported_id,
950                            ExportKind::Direct,
951                            None,
952                        );
953                    }
954                }
955            }
956            "class_declaration" => {
957                if let Some(name_node) = decl.child_by_field_name("name")
958                    && let Ok(name) = name_node.utf8_text(content)
959                {
960                    let name = name.trim().to_string();
961                    if !name.is_empty() {
962                        let exported_id = helper.add_class(&name, None);
963                        helper.add_export_edge_full(
964                            module_id,
965                            exported_id,
966                            ExportKind::Direct,
967                            None,
968                        );
969                    }
970                }
971            }
972            "lexical_declaration" | "variable_declaration" => {
973                // export const/let/var - can have multiple declarators
974                let mut cursor = decl.walk();
975                for child in decl.children(&mut cursor) {
976                    if child.kind() == "variable_declarator"
977                        && let Some(name_node) = child.child_by_field_name("name")
978                        && let Ok(name) = name_node.utf8_text(content)
979                    {
980                        let name = name.trim().to_string();
981                        if !name.is_empty() {
982                            let exported_id = helper.add_variable(&name, None);
983                            helper.add_export_edge_full(
984                                module_id,
985                                exported_id,
986                                ExportKind::Direct,
987                                None,
988                            );
989                        }
990                    }
991                }
992            }
993            _ => {}
994        }
995    }
996}
997
998/// Build export edges for `CommonJS` patterns.
999///
1000/// Handles:
1001/// - `module.exports = { foo, bar }` -> Named exports from object literal
1002/// - `module.exports = foo` -> Default export
1003/// - `exports.foo = bar` -> Named export
1004/// - `module.exports.foo = bar` -> Named export
1005fn build_commonjs_export_edges(
1006    expr_stmt_node: Node<'_>,
1007    content: &[u8],
1008    helper: &mut GraphBuildHelper,
1009) {
1010    // Get the assignment expression from the expression statement
1011    let Some(assignment) = expr_stmt_node
1012        .children(&mut expr_stmt_node.walk())
1013        .find(|child| child.kind() == "assignment_expression")
1014    else {
1015        return;
1016    };
1017
1018    let Some(left) = assignment.child_by_field_name("left") else {
1019        return;
1020    };
1021    let Some(right) = assignment.child_by_field_name("right") else {
1022        return;
1023    };
1024
1025    let left_text = left.utf8_text(content).ok().map(|s| s.trim().to_string());
1026    let Some(left_text) = left_text else {
1027        return;
1028    };
1029
1030    let module_id = helper.add_module("<module>", None);
1031
1032    // Pattern 1: `module.exports = { foo, bar }` or `module.exports = foo`
1033    if left_text == "module.exports" {
1034        if right.kind() == "object" {
1035            // Object literal: export each property as a named export
1036            let mut cursor = right.walk();
1037            for child in right.children(&mut cursor) {
1038                if child.kind() == "shorthand_property_identifier" {
1039                    // `{ foo }` - shorthand, name is both local and exported
1040                    if let Ok(name) = child.utf8_text(content) {
1041                        let name = name.trim();
1042                        if !name.is_empty() {
1043                            let exported_id = helper.add_function(name, None, false, false);
1044                            helper.add_export_edge_full(
1045                                module_id,
1046                                exported_id,
1047                                ExportKind::Direct,
1048                                None,
1049                            );
1050                        }
1051                    }
1052                } else if child.kind() == "pair" {
1053                    // `{ foo: bar }` - key is export name, value is local
1054                    if let Some(key_node) = child.child_by_field_name("key")
1055                        && let Ok(export_name) = key_node.utf8_text(content)
1056                    {
1057                        let export_name = export_name.trim();
1058                        if !export_name.is_empty() {
1059                            let exported_id = helper.add_function(export_name, None, false, false);
1060                            helper.add_export_edge_full(
1061                                module_id,
1062                                exported_id,
1063                                ExportKind::Direct,
1064                                None,
1065                            );
1066                        }
1067                    }
1068                } else if child.kind() == "spread_element" {
1069                    // `{ ...other }` - spread export (complex to resolve statically)
1070                }
1071            }
1072        } else if right.kind() == "identifier" || right.kind() == "member_expression" {
1073            // Single value export: `module.exports = foo` -> default export
1074            let export_name = right
1075                .utf8_text(content)
1076                .ok()
1077                .map_or_else(|| "default".to_string(), |s| s.trim().to_string());
1078
1079            if !export_name.is_empty() {
1080                let exported_id = helper.add_function(&export_name, None, false, false);
1081                helper.add_export_edge_full(module_id, exported_id, ExportKind::Default, None);
1082            }
1083        } else if matches!(
1084            right.kind(),
1085            "function_expression"
1086                | "arrow_function"
1087                | "class"
1088                | "call_expression"
1089                | "new_expression"
1090        ) {
1091            // Anonymous/inline export: `module.exports = function() {}` -> default export
1092            let exported_id = helper.add_function("default", None, false, false);
1093            helper.add_export_edge_full(module_id, exported_id, ExportKind::Default, None);
1094        }
1095    }
1096    // Pattern 2: `exports.foo = bar` or `module.exports.foo = bar`
1097    else if left_text.starts_with("exports.") || left_text.starts_with("module.exports.") {
1098        // Extract the property name being exported
1099        let export_name = if let Some(name) = left_text.strip_prefix("module.exports.") {
1100            name
1101        } else if let Some(name) = left_text.strip_prefix("exports.") {
1102            name
1103        } else {
1104            return;
1105        };
1106
1107        if !export_name.is_empty() {
1108            let exported_id = helper.add_function(export_name, None, false, false);
1109            helper.add_export_edge_full(module_id, exported_id, ExportKind::Direct, None);
1110        }
1111    }
1112}
1113
1114/// Build inherits edge for class declarations with extends clause.
1115///
1116/// Handles:
1117/// - `class Child extends Parent {}` (`class_declaration` with simple identifier)
1118/// - `class Child extends Module.Parent {}` (`class_declaration` with qualified path)
1119/// - `const Foo = class extends Base {}` (class expression)
1120fn build_inherits_edge_with_helper(
1121    class_node: Node<'_>,
1122    content: &[u8],
1123    helper: &mut GraphBuildHelper,
1124) {
1125    // Look for class_heritage child which contains the extends clause
1126    let heritage = class_node
1127        .children(&mut class_node.walk())
1128        .find(|child| child.kind() == "class_heritage");
1129
1130    let Some(heritage_node) = heritage else {
1131        return; // No inheritance
1132    };
1133
1134    // Get the class name
1135    let class_name = if class_node.kind() == "class_declaration" {
1136        class_node
1137            .child_by_field_name("name")
1138            .and_then(|n| n.utf8_text(content).ok())
1139            .map(|s| s.trim().to_string())
1140    } else {
1141        // For class expressions, try to get the name from parent variable_declarator
1142        class_node
1143            .parent()
1144            .filter(|p| p.kind() == "variable_declarator")
1145            .and_then(|p| p.child_by_field_name("name"))
1146            .and_then(|n| n.utf8_text(content).ok())
1147            .map(|s| s.trim().to_string())
1148            .or_else(|| {
1149                // Anonymous class expression - use synthetic name
1150                Some(SyntheticNameBuilder::from_node_with_hash(
1151                    &class_node,
1152                    content,
1153                    "class",
1154                ))
1155            })
1156    };
1157
1158    // Get the parent class name from heritage
1159    // Handles both simple identifiers and qualified paths (member_expression)
1160    let parent_name = extract_parent_class_name(heritage_node, content);
1161
1162    // Only create edge if we have both names
1163    if let (Some(child_name), Some(parent_name)) = (class_name, parent_name)
1164        && !child_name.is_empty()
1165        && !parent_name.is_empty()
1166    {
1167        let child_id = helper.add_class(&child_name, None);
1168        let parent_id = helper.add_class(&parent_name, None);
1169        helper.add_inherits_edge(child_id, parent_id);
1170    }
1171}
1172
1173/// Extract the parent class name from a `class_heritage` node.
1174///
1175/// Handles:
1176/// - Simple identifier: `extends Parent` -> "Parent"
1177/// - Member expression: `extends Module.Parent` -> "Module.Parent"
1178/// - Nested member: `extends a.b.c.Parent` -> "a.b.c.Parent"
1179/// - Call expression: `extends mixin(Base)` -> "mixin(Base)" (full expression for clarity)
1180///
1181/// **Note on mixin patterns**: For call expressions like `extends mixin(Base)` or
1182/// `extends WithLogging(Component)`, we store the full expression text rather than
1183/// just the function name. This provides clearer semantics for consumers:
1184/// - The node name shows the actual mixin composition
1185/// - Graph queries can distinguish `mixin(A)` from `mixin(B)`
1186/// - The pattern remains compatible with standard inheritance queries
1187fn extract_parent_class_name(heritage_node: Node<'_>, content: &[u8]) -> Option<String> {
1188    let mut cursor = heritage_node.walk();
1189    for child in heritage_node.children(&mut cursor) {
1190        match child.kind() {
1191            "identifier" => {
1192                // Simple extends: `extends Parent`
1193                return child.utf8_text(content).ok().map(|s| s.trim().to_string());
1194            }
1195            "member_expression" => {
1196                // Qualified extends: `extends Module.Parent` or `extends a.b.c.Parent`
1197                // Get the full text of the member expression
1198                return child.utf8_text(content).ok().map(|s| s.trim().to_string());
1199            }
1200            "call_expression" => {
1201                // Mixin pattern: `extends mixin(Base)` or `extends WithLogging(Component)`
1202                // Store full call expression for semantic clarity - consumers can see
1203                // the actual composition, not just the mixin factory function name.
1204                // This avoids ambiguity when the same mixin is used with different bases.
1205                return child.utf8_text(content).ok().map(|s| s.trim().to_string());
1206            }
1207            _ => {}
1208        }
1209    }
1210    None
1211}
1212
1213fn simple_name(name: &str) -> &str {
1214    // Split on . and / to get the last segment of a qualified name
1215    // Do NOT split on '?' - it's part of ternary (?:) and nullish coalescing (??) operators
1216    name.rsplit(['.', '/']).next().unwrap_or(name)
1217}
1218
1219/// Normalizes optional chain syntax by removing `?.` operators
1220/// Converts `user?.getName` to `user.getName` for consistent processing
1221/// Preserves standalone `?` characters (from ternary/nullish operators) by only replacing `?.`
1222fn normalize_optional_chain(text: &str) -> String {
1223    text.replace("?.", ".")
1224        .trim()
1225        .trim_end_matches('.')
1226        .to_string()
1227}
1228
1229fn check_uses_await(call_node: Node<'_>) -> bool {
1230    // Check if the call_node's parent is an await_expression
1231    let mut current = call_node;
1232    for _ in 0..2 {
1233        // Check up to 2 levels up
1234        if let Some(parent) = current.parent() {
1235            if parent.kind() == "await_expression" {
1236                return true;
1237            }
1238            current = parent;
1239        } else {
1240            break;
1241        }
1242    }
1243    false
1244}
1245
1246fn count_arguments(node: Node<'_>) -> usize {
1247    node.child_by_field_name("arguments").map_or(0, |args| {
1248        let mut count = 0;
1249        let mut cursor = args.walk();
1250        for child in args.children(&mut cursor) {
1251            if !matches!(child.kind(), "(" | ")" | ",") {
1252                count += 1;
1253            }
1254        }
1255        count
1256    })
1257}
1258
1259fn span_from_node(node: Node<'_>) -> Span {
1260    let start = node.start_position();
1261    let end = node.end_position();
1262    Span::new(
1263        Position::new(start.row, start.column),
1264        Position::new(end.row, end.column),
1265    )
1266}
1267
1268fn extract_string_literal(node: &Node, content: &[u8]) -> Option<String> {
1269    let text = node.utf8_text(content).ok()?;
1270    let trimmed = text.trim();
1271
1272    // Remove quotes
1273    trimmed
1274        .strip_prefix('"')
1275        .and_then(|s| s.strip_suffix('"'))
1276        .or_else(|| {
1277            trimmed
1278                .strip_prefix('\'')
1279                .and_then(|s| s.strip_suffix('\''))
1280        })
1281        .or_else(|| trimmed.strip_prefix('`').and_then(|s| s.strip_suffix('`')))
1282        .map(std::string::ToString::to_string)
1283}
1284
1285// ========== ASTGraph: Pre-computed AST metadata ==========
1286
1287#[derive(Debug, Clone)]
1288pub struct CallContext {
1289    #[allow(dead_code)] // Reserved for future context queries
1290    pub name: Arc<str>,
1291    pub qualified_name: String,
1292    pub span: (usize, usize),
1293    pub is_async: bool,
1294}
1295
1296impl CallContext {
1297    pub fn qualified_name(&self) -> &str {
1298        &self.qualified_name
1299    }
1300}
1301
1302pub struct ASTGraph {
1303    /// Maps node ID to its enclosing callable node ID
1304    callable_map: HashMap<usize, usize>,
1305    /// Maps callable node ID to its context (name, scope, etc.)
1306    context_map: HashMap<usize, CallContext>,
1307}
1308
1309impl ASTGraph {
1310    /// Build the graph structure from the AST in a single O(n) pass
1311    pub fn from_tree(tree: &Tree, content: &[u8], max_scope_depth: usize) -> Result<Self, String> {
1312        let mut builder = ASTGraphBuilder::new(content, max_scope_depth);
1313
1314        // Create recursion guard
1315        let recursion_limits = sqry_core::config::RecursionLimits::load_or_default()
1316            .map_err(|e| format!("Failed to load recursion limits: {e}"))?;
1317        let file_ops_depth = recursion_limits
1318            .effective_file_ops_depth()
1319            .map_err(|e| format!("Invalid file_ops_depth configuration: {e}"))?;
1320        let mut guard = sqry_core::query::security::RecursionGuard::new(file_ops_depth)
1321            .map_err(|e| format!("Failed to create recursion guard: {e}"))?;
1322
1323        builder
1324            .visit(tree.root_node(), None, &mut guard)
1325            .map_err(|e| format!("JavaScript AST traversal hit recursion limit: {e}"))?;
1326        Ok(builder.build())
1327    }
1328
1329    /// Get the enclosing callable context for a node (O(1) lookup)
1330    pub fn get_callable_context(&self, node_id: usize) -> Option<&CallContext> {
1331        let callable_id = self.callable_map.get(&node_id)?;
1332        self.context_map.get(callable_id)
1333    }
1334
1335    /// Get all callable contexts
1336    pub fn contexts(&self) -> impl Iterator<Item = &CallContext> {
1337        self.context_map.values()
1338    }
1339}
1340
1341struct ASTGraphBuilder<'a> {
1342    content: &'a [u8],
1343    max_scope_depth: usize,
1344    callable_map: HashMap<usize, usize>,
1345    context_map: HashMap<usize, CallContext>,
1346    #[allow(dead_code)] // Reserved for nested callable tracking
1347    current_callable: Option<usize>,
1348    current_scope: Vec<Arc<str>>,
1349}
1350
1351impl<'a> ASTGraphBuilder<'a> {
1352    fn new(content: &'a [u8], max_scope_depth: usize) -> Self {
1353        Self {
1354            content,
1355            max_scope_depth,
1356            callable_map: HashMap::new(),
1357            context_map: HashMap::new(),
1358            current_callable: None,
1359            current_scope: Vec::new(),
1360        }
1361    }
1362
1363    fn build(self) -> ASTGraph {
1364        ASTGraph {
1365            callable_map: self.callable_map,
1366            context_map: self.context_map,
1367        }
1368    }
1369
1370    /// # Errors
1371    ///
1372    /// Returns [`sqry_core::query::security::RecursionError::DepthLimitExceeded`] if recursion depth exceeds the guard's limit.
1373    fn visit(
1374        &mut self,
1375        node: Node<'_>,
1376        parent_callable: Option<usize>,
1377        guard: &mut sqry_core::query::security::RecursionGuard,
1378    ) -> Result<(), sqry_core::query::security::RecursionError> {
1379        guard.enter()?;
1380
1381        let node_id = node.id();
1382
1383        // Check if this node is a callable (function, method, arrow function)
1384        let callable_name = callable_node_name(node, self.content);
1385
1386        let new_callable = if let Some(name) = callable_name {
1387            // This is a callable - create context
1388            let start = node.start_byte();
1389            let end = node.end_byte();
1390            let is_async = is_async_function(node, self.content);
1391
1392            let qualified_name = if self.current_scope.is_empty() {
1393                name.clone()
1394            } else if self.current_scope.len() <= self.max_scope_depth {
1395                format!("{}.{}", self.current_scope.join("."), name)
1396            } else {
1397                // Truncate deep scopes
1398                let truncated = &self.current_scope[..self.max_scope_depth];
1399                format!("{}.{}", truncated.join("."), name)
1400            };
1401
1402            let context = CallContext {
1403                name: Arc::from(name),
1404                qualified_name,
1405                span: (start, end),
1406                is_async,
1407            };
1408
1409            self.context_map.insert(node_id, context);
1410            Some(node_id)
1411        } else {
1412            None
1413        };
1414
1415        // Use new callable context if we entered one, otherwise inherit parent's
1416        let effective_callable = new_callable.or(parent_callable);
1417
1418        // Map this node to its enclosing callable
1419        if let Some(callable_id) = effective_callable {
1420            self.callable_map.insert(node_id, callable_id);
1421        }
1422
1423        // Handle scope tracking (classes, objects, etc.)
1424        let scope_name = scope_node_name(node, self.content);
1425        let pushed_scope = if let Some(name) = scope_name {
1426            self.current_scope.push(Arc::from(name));
1427            true
1428        } else {
1429            false
1430        };
1431
1432        // Recursively visit children
1433        let mut cursor = node.walk();
1434        for child in node.children(&mut cursor) {
1435            self.visit(child, effective_callable, guard)?;
1436        }
1437
1438        // Pop scope if we pushed one
1439        if pushed_scope {
1440            self.current_scope.pop();
1441        }
1442
1443        guard.exit();
1444        Ok(())
1445    }
1446}
1447
1448/// Check if a node represents a callable (function, method, arrow function, etc.)
1449fn callable_node_name(node: Node<'_>, content: &[u8]) -> Option<String> {
1450    match node.kind() {
1451        "function_declaration" | "generator_function_declaration" => node
1452            .child_by_field_name("name")
1453            .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string())),
1454        "function_expression" | "generator_function" => {
1455            // Named function expression
1456            node.child_by_field_name("name")
1457                .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string()))
1458                .or_else(|| {
1459                    Some(SyntheticNameBuilder::from_node_with_hash(
1460                        &node, content, "function",
1461                    ))
1462                })
1463        }
1464        "arrow_function" => {
1465            // FR-JS-PATCH-1/2 compliance: Differentiate truly anonymous vs variable-assigned
1466            // Variable-assigned: const foo = () => {} → use "foo" (declared name)
1467            // Truly anonymous: [].map(() => {}) → use anon:arrow:<hash> (FR-JS-PATCH-2)
1468            if let Some(parent) = node.parent()
1469                && parent.kind() == "variable_declarator"
1470                && let Some(name_node) = parent.child_by_field_name("name")
1471                && let Ok(name) = name_node.utf8_text(content)
1472            {
1473                let trimmed = name.trim();
1474                if !trimmed.is_empty() {
1475                    return Some(trimmed.to_string());
1476                }
1477            }
1478            // Fallback: truly anonymous arrow functions (callbacks, IIFEs, etc.)
1479            // Use hash-based synthetic naming per FR-JS-PATCH-2
1480            Some(SyntheticNameBuilder::from_node_with_hash(
1481                &node, content, "arrow",
1482            ))
1483        }
1484        "method_definition" => node
1485            .child_by_field_name("name")
1486            .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string())),
1487        _ => None,
1488    }
1489}
1490
1491fn scope_node_name(node: Node<'_>, content: &[u8]) -> Option<String> {
1492    match node.kind() {
1493        "class_declaration" | "class" => node
1494            .child_by_field_name("name")
1495            .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string()))
1496            .or_else(|| {
1497                Some(SyntheticNameBuilder::from_node_with_hash(
1498                    &node, content, "class",
1499                ))
1500            }),
1501        _ => None,
1502    }
1503}
1504
1505fn is_async_function(node: Node<'_>, _content: &[u8]) -> bool {
1506    // Check if function has async modifier
1507    let mut cursor = node.walk();
1508    node.children(&mut cursor)
1509        .any(|child| child.kind() == "async")
1510}
1511
1512// ========== JSDoc TypeOf/Reference Processing ==========
1513
1514/// Process `JSDoc` annotations to create `TypeOf` and Reference edges
1515/// This is a post-processing pass that runs after all nodes are created
1516fn process_jsdoc_annotations(
1517    node: Node,
1518    content: &[u8],
1519    helper: &mut GraphBuildHelper,
1520) -> GraphResult<()> {
1521    // Recursively walk the tree looking for nodes with JSDoc
1522    match node.kind() {
1523        "function_declaration" | "generator_function_declaration" => {
1524            process_function_jsdoc(node, content, helper)?;
1525        }
1526        "method_definition" => {
1527            process_method_jsdoc(node, content, helper)?;
1528        }
1529        "lexical_declaration" | "variable_declaration" => {
1530            process_variable_jsdoc(node, content, helper)?;
1531        }
1532        "class_declaration" | "class" => {
1533            process_class_fields(node, content, helper)?;
1534            process_constructor_this_assignments(node, content, helper)?;
1535        }
1536        _ => {}
1537    }
1538
1539    // Recurse into children
1540    let mut cursor = node.walk();
1541    for child in node.children(&mut cursor) {
1542        process_jsdoc_annotations(child, content, helper)?;
1543    }
1544
1545    Ok(())
1546}
1547
1548/// Process `JSDoc` for function declarations
1549fn process_function_jsdoc(
1550    func_node: Node,
1551    content: &[u8],
1552    helper: &mut GraphBuildHelper,
1553) -> GraphResult<()> {
1554    // Extract JSDoc comment
1555    let Some(jsdoc_text) = extract_jsdoc_comment(func_node, content) else {
1556        return Ok(());
1557    };
1558
1559    // Parse JSDoc tags
1560    let tags = parse_jsdoc_tags(&jsdoc_text);
1561
1562    // Get function name
1563    let Some(name_node) = func_node.child_by_field_name("name") else {
1564        return Ok(());
1565    };
1566
1567    let function_name = name_node
1568        .utf8_text(content)
1569        .map_err(|_| GraphBuilderError::ParseError {
1570            span: span_from_node(func_node),
1571            reason: "failed to read function name".to_string(),
1572        })?
1573        .trim()
1574        .to_string();
1575
1576    if function_name.is_empty() {
1577        return Ok(());
1578    }
1579
1580    // Get or create function node
1581    let func_node_id = helper.ensure_callee(
1582        &function_name,
1583        span_from_node(func_node),
1584        CalleeKindHint::Function,
1585    );
1586
1587    // ISSUE 1 FIX: Extract AST parameter list with indices
1588    // Map JSDoc tags to AST parameters by name, use AST index (not JSDoc order)
1589    let ast_params = extract_ast_parameters(func_node, content);
1590    let ast_param_map: HashMap<&str, usize> = ast_params
1591        .iter()
1592        .map(|(idx, name)| (name.as_str(), *idx))
1593        .collect();
1594
1595    // Process @param tags - map to AST indices by name
1596    for param_tag in &tags.params {
1597        // Find AST index for this JSDoc parameter name
1598        // Handle optional params [name], rest params ...name, dotted names (options.foo)
1599        let mut normalized_name = param_tag
1600            .name
1601            .trim_start_matches("...")
1602            .trim_matches(|c| c == '[' || c == ']');
1603
1604        // Handle dotted parameter names (e.g., "options.name" -> "options")
1605        // For property-path JSDoc tags, use the base parameter name
1606        if let Some(base_name) = normalized_name.split('.').next() {
1607            normalized_name = base_name;
1608        }
1609
1610        let Some(&ast_index) = ast_param_map.get(normalized_name) else {
1611            // JSDoc tag doesn't match any AST parameter - skip it
1612            continue;
1613        };
1614
1615        // Create TypeOf edge: function -> parameter type
1616        let canonical_type = canonical_type_string(&param_tag.type_str);
1617        let type_node_id = helper.add_type(&canonical_type, None);
1618        helper.add_typeof_edge_with_context(
1619            func_node_id,
1620            type_node_id,
1621            Some(TypeOfContext::Parameter),
1622            ast_index.try_into().ok(), // Use AST index, not JSDoc order
1623            Some(&param_tag.name),
1624        );
1625
1626        // Create Reference edges: function -> each referenced type
1627        let type_names = extract_type_names(&param_tag.type_str);
1628        for type_name in type_names {
1629            let ref_type_id = helper.add_type(&type_name, None);
1630            helper.add_reference_edge(func_node_id, ref_type_id);
1631        }
1632    }
1633
1634    // Process @returns tag
1635    if let Some(return_type) = &tags.returns {
1636        let canonical_type = canonical_type_string(return_type);
1637        let type_node_id = helper.add_type(&canonical_type, None);
1638        helper.add_typeof_edge_with_context(
1639            func_node_id,
1640            type_node_id,
1641            Some(TypeOfContext::Return),
1642            Some(0),
1643            None,
1644        );
1645
1646        // Create Reference edges for return type
1647        let type_names = extract_type_names(return_type);
1648        for type_name in type_names {
1649            let ref_type_id = helper.add_type(&type_name, None);
1650            helper.add_reference_edge(func_node_id, ref_type_id);
1651        }
1652    }
1653
1654    Ok(())
1655}
1656
1657/// Process `JSDoc` for method definitions
1658fn process_method_jsdoc(
1659    method_node: Node,
1660    content: &[u8],
1661    helper: &mut GraphBuildHelper,
1662) -> GraphResult<()> {
1663    // Extract JSDoc comment
1664    let Some(jsdoc_text) = extract_jsdoc_comment(method_node, content) else {
1665        return Ok(());
1666    };
1667
1668    // Parse JSDoc tags
1669    let tags = parse_jsdoc_tags(&jsdoc_text);
1670
1671    // Get method name
1672    let Some(name_node) = method_node.child_by_field_name("name") else {
1673        return Ok(());
1674    };
1675
1676    let method_name = name_node
1677        .utf8_text(content)
1678        .map_err(|_| GraphBuilderError::ParseError {
1679            span: span_from_node(method_node),
1680            reason: "failed to read method name".to_string(),
1681        })?
1682        .trim()
1683        .to_string();
1684
1685    if method_name.is_empty() {
1686        return Ok(());
1687    }
1688
1689    // Find the class name by walking up the tree
1690    let class_name = get_enclosing_class_name(method_node, content)?;
1691    let Some(class_name) = class_name else {
1692        return Ok(());
1693    };
1694
1695    // Create qualified method name: ClassName.methodName
1696    let qualified_name = format!("{class_name}.{method_name}");
1697
1698    // Get existing method node (should already exist from main traversal)
1699    // Use ensure_method to handle case where it might not exist yet
1700    let method_node_id = helper.ensure_method(&qualified_name, None, false, false);
1701
1702    // ISSUE 1 FIX: Extract AST parameter list with indices
1703    // Map JSDoc tags to AST parameters by name, use AST index (not JSDoc order)
1704    let ast_params = extract_ast_parameters(method_node, content);
1705    let ast_param_map: HashMap<&str, usize> = ast_params
1706        .iter()
1707        .map(|(idx, name)| (name.as_str(), *idx))
1708        .collect();
1709
1710    // Process @param tags - map to AST indices by name
1711    for param_tag in &tags.params {
1712        // Find AST index for this JSDoc parameter name
1713        // Handle optional params [name], rest params ...name, dotted names (options.foo)
1714        let mut normalized_name = param_tag
1715            .name
1716            .trim_start_matches("...")
1717            .trim_matches(|c| c == '[' || c == ']');
1718
1719        // Handle dotted parameter names (e.g., "options.name" -> "options")
1720        // For property-path JSDoc tags, use the base parameter name
1721        if let Some(base_name) = normalized_name.split('.').next() {
1722            normalized_name = base_name;
1723        }
1724
1725        let Some(&ast_index) = ast_param_map.get(normalized_name) else {
1726            // JSDoc tag doesn't match any AST parameter - skip it
1727            continue;
1728        };
1729
1730        let canonical_type = canonical_type_string(&param_tag.type_str);
1731        let type_node_id = helper.add_type(&canonical_type, None);
1732        helper.add_typeof_edge_with_context(
1733            method_node_id,
1734            type_node_id,
1735            Some(TypeOfContext::Parameter),
1736            ast_index.try_into().ok(), // Use AST index, not JSDoc order
1737            Some(&param_tag.name),
1738        );
1739
1740        // Create Reference edges
1741        let type_names = extract_type_names(&param_tag.type_str);
1742        for type_name in type_names {
1743            let ref_type_id = helper.add_type(&type_name, None);
1744            helper.add_reference_edge(method_node_id, ref_type_id);
1745        }
1746    }
1747
1748    // Process @returns tag
1749    if let Some(return_type) = &tags.returns {
1750        let canonical_type = canonical_type_string(return_type);
1751        let type_node_id = helper.add_type(&canonical_type, None);
1752        helper.add_typeof_edge_with_context(
1753            method_node_id,
1754            type_node_id,
1755            Some(TypeOfContext::Return),
1756            Some(0),
1757            None,
1758        );
1759
1760        // Create Reference edges
1761        let type_names = extract_type_names(return_type);
1762        for type_name in type_names {
1763            let ref_type_id = helper.add_type(&type_name, None);
1764            helper.add_reference_edge(method_node_id, ref_type_id);
1765        }
1766    }
1767
1768    Ok(())
1769}
1770
1771/// Process `JSDoc` @type annotations for variables
1772fn process_variable_jsdoc(
1773    decl_node: Node,
1774    content: &[u8],
1775    helper: &mut GraphBuildHelper,
1776) -> GraphResult<()> {
1777    // Check if this is a top-level variable (not inside a function)
1778    if !is_top_level_variable(decl_node) {
1779        return Ok(());
1780    }
1781
1782    // Extract JSDoc comment
1783    let Some(jsdoc_text) = extract_jsdoc_comment(decl_node, content) else {
1784        return Ok(());
1785    };
1786
1787    // Parse JSDoc tags
1788    let tags = parse_jsdoc_tags(&jsdoc_text);
1789
1790    // Only process if there's a @type annotation
1791    let Some(type_annotation) = &tags.type_annotation else {
1792        return Ok(());
1793    };
1794
1795    // Find all variable declarators in this declaration
1796    let mut cursor = decl_node.walk();
1797    for child in decl_node.children(&mut cursor) {
1798        if child.kind() == "variable_declarator"
1799            && let Some(name_node) = child.child_by_field_name("name")
1800        {
1801            let var_name = name_node
1802                .utf8_text(content)
1803                .map_err(|_| GraphBuilderError::ParseError {
1804                    span: span_from_node(child),
1805                    reason: "failed to read variable name".to_string(),
1806                })?
1807                .trim()
1808                .to_string();
1809
1810            if !var_name.is_empty() {
1811                // Get or create variable node
1812                let var_node_id = helper.add_variable(&var_name, None);
1813
1814                // Create TypeOf edge
1815                let canonical_type = canonical_type_string(type_annotation);
1816                let type_node_id = helper.add_type(&canonical_type, None);
1817                helper.add_typeof_edge_with_context(
1818                    var_node_id,
1819                    type_node_id,
1820                    Some(TypeOfContext::Variable),
1821                    None,
1822                    None,
1823                );
1824
1825                // Create Reference edges
1826                let type_names = extract_type_names(type_annotation);
1827                for type_name in type_names {
1828                    let ref_type_id = helper.add_type(&type_name, None);
1829                    helper.add_reference_edge(var_node_id, ref_type_id);
1830                }
1831            }
1832        }
1833    }
1834
1835    Ok(())
1836}
1837
1838/// Resolve the class name for a `class_declaration` or `class` expression node.
1839///
1840/// For named classes: reads the `name` field child.
1841/// For anonymous class expressions: falls back to the binding identifier when
1842/// the class is assigned to a `variable_declarator` or `assignment_expression`
1843/// (mirrors the historic behaviour of `process_class_fields_jsdoc`).
1844///
1845/// Returns `None` for anonymous classes that are not bound to an identifier
1846/// (e.g. immediately invoked or passed as an argument). Callers must skip
1847/// emission in that case to avoid creating ill-formed `Class.field` names.
1848fn resolve_class_name_for_fields(
1849    class_node: Node<'_>,
1850    content: &[u8],
1851) -> GraphResult<Option<String>> {
1852    if let Some(name_node) = class_node.child_by_field_name("name") {
1853        let name = name_node
1854            .utf8_text(content)
1855            .map_err(|_| GraphBuilderError::ParseError {
1856                span: span_from_node(class_node),
1857                reason: "failed to read class name".to_string(),
1858            })?
1859            .trim()
1860            .to_string();
1861        if name.is_empty() {
1862            return Ok(None);
1863        }
1864        return Ok(Some(name));
1865    }
1866
1867    // Anonymous class expression — try to find the binding identifier.
1868    let Some(parent) = class_node.parent() else {
1869        return Ok(None);
1870    };
1871
1872    match parent.kind() {
1873        "variable_declarator" => {
1874            if let Some(name_node) = parent.child_by_field_name("name")
1875                && let Ok(var_name) = name_node.utf8_text(content)
1876            {
1877                let var_name = var_name.trim().to_string();
1878                if var_name.is_empty() {
1879                    return Ok(None);
1880                }
1881                return Ok(Some(var_name));
1882            }
1883            Ok(None)
1884        }
1885        "assignment_expression" => {
1886            if let Some(left) = parent.child_by_field_name("left")
1887                && let Ok(assign_name) = left.utf8_text(content)
1888            {
1889                let assign_name = assign_name.trim().to_string();
1890                if assign_name.is_empty() {
1891                    return Ok(None);
1892                }
1893                return Ok(Some(assign_name));
1894            }
1895            Ok(None)
1896        }
1897        _ => Ok(None),
1898    }
1899}
1900
1901/// Emit Property nodes for every `field_definition` in a class body, and
1902/// optionally enrich them with `TypeOf{Field}` + `References` edges when a
1903/// `JSDoc` `@type` annotation is present (REQ:R0001..R0006, R0008, R0023).
1904///
1905/// Replaces the historic JSDoc-gated `process_class_fields_jsdoc` function:
1906/// emission is now unconditional. `JSDoc`, when present, is treated as
1907/// enrichment for the type edge rather than a gate.
1908///
1909/// AC mapping:
1910/// - AC-1 unconditional Property emission on every `field_definition`
1911/// - AC-2 span sourced from the field-definition node
1912/// - AC-3 `static` modifier → `is_static = true`
1913/// - AC-4 `private_property_identifier` (`#name`) → visibility = "private"
1914/// - AC-5 `TypeOf` edge name = bare field name (not `Class.field`)
1915/// - AC-7 `JSDoc` `@type` is preserved as enrichment, not a gate
1916fn process_class_fields(
1917    class_node: Node<'_>,
1918    content: &[u8],
1919    helper: &mut GraphBuildHelper,
1920) -> GraphResult<()> {
1921    let Some(class_name) = resolve_class_name_for_fields(class_node, content)? else {
1922        return Ok(());
1923    };
1924
1925    let Some(body_node) = class_node.child_by_field_name("body") else {
1926        return Ok(());
1927    };
1928
1929    let mut cursor = body_node.walk();
1930    for child in body_node.children(&mut cursor) {
1931        if child.kind() != "field_definition" {
1932            continue;
1933        }
1934        emit_class_field_node(child, content, helper, &class_name)?;
1935    }
1936
1937    Ok(())
1938}
1939
1940/// Emit a single class field as a Property node and (when `JSDoc` `@type` is
1941/// present) the corresponding `TypeOf{Field}` + Reference edges.
1942fn emit_class_field_node(
1943    field_node: Node<'_>,
1944    content: &[u8],
1945    helper: &mut GraphBuildHelper,
1946    class_name: &str,
1947) -> GraphResult<()> {
1948    // Field name lives under the `property` field for `field_definition` in
1949    // tree-sitter-javascript. The child node is either an identifier or a
1950    // `private_property_identifier` (the `#name` form).
1951    let Some(name_node) = field_node.child_by_field_name("property") else {
1952        return Ok(());
1953    };
1954
1955    let raw_name = name_node
1956        .utf8_text(content)
1957        .map_err(|_| GraphBuilderError::ParseError {
1958            span: span_from_node(field_node),
1959            reason: "failed to read field name".to_string(),
1960        })?
1961        .trim()
1962        .to_string();
1963
1964    if raw_name.is_empty() {
1965        return Ok(());
1966    }
1967
1968    let is_hash_private = name_node.kind() == "private_property_identifier";
1969
1970    // Scan modifier-like direct children. tree-sitter-javascript surfaces
1971    // `static` as an anonymous keyword child of `field_definition`; there is
1972    // no accessibility-modifier surface in the JS grammar (visibility is
1973    // inferred from the `#`-prefix only).
1974    let mut is_static = false;
1975    let mut mod_cursor = field_node.walk();
1976    for modifier in field_node.children(&mut mod_cursor) {
1977        if modifier.kind() == "static" {
1978            is_static = true;
1979        }
1980    }
1981
1982    // Per design §3.3 + AC-4: JS field visibility is syntactic.
1983    // `#`-prefix → "private"; otherwise → "public". Underscore-prefix
1984    // naming heuristics (e.g. `_foo`) are deliberately NOT applied at the
1985    // field call site — the field contract is grammar-level, not
1986    // naming-convention-based.
1987    let visibility: Option<&str> = if is_hash_private {
1988        Some("private")
1989    } else {
1990        Some("public")
1991    };
1992
1993    let qualified_name = format!("{class_name}.{raw_name}");
1994    let span = Some(span_from_node(field_node));
1995
1996    let field_id = helper.add_property_with_static_and_visibility(
1997        &qualified_name,
1998        span,
1999        is_static,
2000        visibility,
2001    );
2002
2003    // JSDoc `@type` is now enrichment, not a gate. When present, emit the
2004    // `TypeOf{Field}` edge with the BARE field name (AC-5) and add
2005    // Reference edges for every named type appearing in the annotation.
2006    if let Some(jsdoc_text) = extract_jsdoc_comment(field_node, content) {
2007        let tags = parse_jsdoc_tags(&jsdoc_text);
2008        if let Some(type_annotation) = &tags.type_annotation {
2009            let canonical_type = canonical_type_string(type_annotation);
2010            let type_node_id = helper.add_type(&canonical_type, None);
2011            helper.add_typeof_edge_with_context(
2012                field_id,
2013                type_node_id,
2014                Some(TypeOfContext::Field),
2015                None,
2016                Some(&raw_name),
2017            );
2018
2019            let type_names = extract_type_names(type_annotation);
2020            for type_name in type_names {
2021                let ref_type_id = helper.add_type(&type_name, None);
2022                helper.add_reference_edge(field_id, ref_type_id);
2023            }
2024        }
2025    }
2026
2027    Ok(())
2028}
2029
2030/// Walk a class body and, for every constructor body, emit Property nodes
2031/// for each `this.<identifier> = ...` assignment encountered (AC-6).
2032///
2033/// The walker recurses through all assignment expressions in the constructor
2034/// body — including those inside nested arrow functions (which inherit
2035/// `this`). Non-`this` assignments, `this.x.y = ...` deep paths, and
2036/// computed `this[expr] = ...` accesses are skipped.
2037///
2038/// Deduplication with explicit field declarations (FR-13) is handled by the
2039/// helper's `node_cache`: an existing `Property` with the same canonical
2040/// qualified name is returned without creating a duplicate node.
2041fn process_constructor_this_assignments(
2042    class_node: Node<'_>,
2043    content: &[u8],
2044    helper: &mut GraphBuildHelper,
2045) -> GraphResult<()> {
2046    let Some(class_name) = resolve_class_name_for_fields(class_node, content)? else {
2047        return Ok(());
2048    };
2049
2050    let Some(body_node) = class_node.child_by_field_name("body") else {
2051        return Ok(());
2052    };
2053
2054    let mut cursor = body_node.walk();
2055    for child in body_node.children(&mut cursor) {
2056        if child.kind() != "method_definition" {
2057            continue;
2058        }
2059
2060        // Only process the constructor — `this.x = ...` in other methods is
2061        // not necessarily a field declaration site (it may shadow or
2062        // mutate). Constructor-time assignments are the standard
2063        // class-field discovery surface.
2064        let Some(name_node) = child.child_by_field_name("name") else {
2065            continue;
2066        };
2067        let Ok(method_name) = name_node.utf8_text(content) else {
2068            continue;
2069        };
2070        if method_name.trim() != "constructor" {
2071            continue;
2072        }
2073
2074        let Some(method_body) = child.child_by_field_name("body") else {
2075            continue;
2076        };
2077
2078        walk_for_this_assignments(method_body, content, helper, &class_name);
2079    }
2080
2081    Ok(())
2082}
2083
2084/// Recursively scan a subtree for `assignment_expression` nodes whose left
2085/// side is `this.<identifier>` and emit Property nodes for the corresponding
2086/// `Class.<identifier>` qualified names.
2087fn walk_for_this_assignments(
2088    node: Node<'_>,
2089    content: &[u8],
2090    helper: &mut GraphBuildHelper,
2091    class_name: &str,
2092) {
2093    if node.kind() == "assignment_expression"
2094        && let Some(left) = node.child_by_field_name("left")
2095        && left.kind() == "member_expression"
2096        && let Some(object) = left.child_by_field_name("object")
2097        && object.kind() == "this"
2098        && let Some(property) = left.child_by_field_name("property")
2099        && property.kind() == "property_identifier"
2100        && let Ok(field_name) = property.utf8_text(content)
2101    {
2102        let field_name = field_name.trim();
2103        if !field_name.is_empty() {
2104            let qualified_name = format!("{class_name}.{field_name}");
2105            // Span sourced from the `this.<name>` member expression so the
2106            // node carries a useful location even when the explicit-field
2107            // path did not run.
2108            // Per design §3.3 + AC-4: JS field visibility is syntactic.
2109            // `this.<name>` discovered fields lack a `#`-prefix surface
2110            // (the property_identifier branch only matches non-private
2111            // identifiers — private-instance access uses
2112            // `private_property_identifier` and is filtered out above),
2113            // so they default to "public".
2114            let _ = helper.add_property_with_static_and_visibility(
2115                &qualified_name,
2116                Some(span_from_node(left)),
2117                false,
2118                Some("public"),
2119            );
2120        }
2121    }
2122
2123    // Recurse into all children. Nested arrow functions are intentionally
2124    // walked because they inherit `this`. Non-arrow nested functions also
2125    // recurse, but `this` inside them is rebound so a `this.x = ...` there
2126    // would be misattributed; this is a known limitation that mirrors the
2127    // best-effort behaviour of class-field discovery elsewhere in the
2128    // ecosystem (the JS grammar offers no static way to distinguish at
2129    // tree-walk time without full scope analysis).
2130    let mut cursor = node.walk();
2131    for child in node.children(&mut cursor) {
2132        walk_for_this_assignments(child, content, helper, class_name);
2133    }
2134}
2135
2136/// Helper: Get enclosing class name for a method
2137/// Supports both named classes and anonymous classes assigned to variables
2138/// ISSUE 3 FIX: Handle anonymous class expressions
2139fn get_enclosing_class_name(method_node: Node, content: &[u8]) -> GraphResult<Option<String>> {
2140    // Walk up the tree to find the class declaration or expression
2141    let mut current = method_node;
2142    while let Some(parent) = current.parent() {
2143        if parent.kind() == "class_declaration" {
2144            // Named class declaration
2145            if let Some(name_node) = parent.child_by_field_name("name") {
2146                let class_name = name_node
2147                    .utf8_text(content)
2148                    .map_err(|_| GraphBuilderError::ParseError {
2149                        span: span_from_node(parent),
2150                        reason: "failed to read class name".to_string(),
2151                    })?
2152                    .trim()
2153                    .to_string();
2154
2155                if !class_name.is_empty() {
2156                    return Ok(Some(class_name));
2157                }
2158            }
2159        } else if parent.kind() == "class" {
2160            // Anonymous class expression - check if assigned to variable
2161            // Example: const MyClass = class { ... }
2162            if let Some(grandparent) = parent.parent() {
2163                if grandparent.kind() == "variable_declarator" {
2164                    // Get variable name
2165                    if let Some(name_node) = grandparent.child_by_field_name("name")
2166                        && let Ok(var_name) = name_node.utf8_text(content)
2167                    {
2168                        let var_name = var_name.trim().to_string();
2169                        if !var_name.is_empty() {
2170                            return Ok(Some(var_name));
2171                        }
2172                    }
2173                } else if grandparent.kind() == "assignment_expression" {
2174                    // Assignment: SomeClass = class { ... }
2175                    if let Some(left) = grandparent.child_by_field_name("left")
2176                        && let Ok(assign_name) = left.utf8_text(content)
2177                    {
2178                        let assign_name = assign_name.trim().to_string();
2179                        if !assign_name.is_empty() {
2180                            return Ok(Some(assign_name));
2181                        }
2182                    }
2183                }
2184            }
2185            // If anonymous and not assigned, return None
2186            // (Methods won't get JSDoc edges, but won't crash)
2187            return Ok(None);
2188        }
2189        current = parent;
2190    }
2191    Ok(None)
2192}
2193
2194/// Extract parameter names and AST indices from function/method parameter list
2195/// Returns Vec<(`ast_index`, `param_name`)> for mapping `JSDoc` tags to AST positions
2196fn extract_ast_parameters(func_node: Node, content: &[u8]) -> Vec<(usize, String)> {
2197    let Some(params_node) = func_node.child_by_field_name("parameters") else {
2198        return Vec::new();
2199    };
2200
2201    let mut cursor = params_node.walk();
2202    params_node
2203        .named_children(&mut cursor)
2204        .enumerate()
2205        .filter_map(|(ast_index, param)| {
2206            // Handle different parameter node types
2207            let param_name = match param.kind() {
2208                "identifier" => param
2209                    .utf8_text(content)
2210                    .ok()
2211                    .map(std::string::ToString::to_string),
2212                "required_parameter" | "optional_parameter" => {
2213                    // Get the pattern node (identifier)
2214                    param
2215                        .child_by_field_name("pattern")
2216                        .and_then(|p| p.utf8_text(content).ok())
2217                        .map(std::string::ToString::to_string)
2218                }
2219                "rest_pattern" => {
2220                    // Rest parameters: ...args
2221                    // Get identifier inside rest pattern
2222                    param
2223                        .named_child(0)
2224                        .and_then(|n| n.utf8_text(content).ok())
2225                        .map(|s| s.trim_start_matches("...").to_string())
2226                }
2227                "assignment_pattern" => {
2228                    // Default parameters: x = 10
2229                    // Get left side identifier
2230                    param
2231                        .child_by_field_name("left")
2232                        .filter(|left| left.kind() == "identifier")
2233                        .and_then(|left| left.utf8_text(content).ok())
2234                        .map(std::string::ToString::to_string)
2235                }
2236                _ => None,
2237            };
2238
2239            param_name.map(|name| (ast_index, name))
2240        })
2241        .collect()
2242}
2243
2244/// Helper: Check if a variable declaration is top-level (module-scope only)
2245/// Excludes variables inside functions, methods, AND block scopes (if, for, while, try, etc.)
2246fn is_top_level_variable(decl_node: Node) -> bool {
2247    let mut current = decl_node;
2248    while let Some(parent) = current.parent() {
2249        match parent.kind() {
2250            // Functions/methods - not top-level
2251            "function_declaration"
2252            | "generator_function_declaration"
2253            | "function_expression"
2254            | "arrow_function"
2255            | "method_definition" => return false,
2256
2257            // Block scopes - not top-level (Issue 2 fix)
2258            "statement_block" | "if_statement" | "for_statement" | "for_in_statement"
2259            | "for_of_statement" | "while_statement" | "do_statement" | "try_statement"
2260            | "catch_clause" | "finally_clause" | "switch_statement" | "switch_case"
2261            | "switch_default" | "class_body" | "class_static_block" | "with_statement" => {
2262                return false;
2263            }
2264
2265            // Program/module root - is top-level
2266            // Export statements are top-level
2267            "program" | "export_statement" => return true,
2268
2269            _ => {}
2270        }
2271        current = parent;
2272    }
2273    true
2274}
2275
2276// ========== FFI Detection ==========
2277
2278/// Build FFI edges for call expressions.
2279///
2280/// Detects:
2281/// - `WebAssembly.instantiate(buffer)` / `WebAssembly.instantiateStreaming(fetch(...))`
2282/// - `WebAssembly.compile(buffer)` / `WebAssembly.compileStreaming(fetch(...))`
2283/// - `require('./native.node')` - Node.js native addons
2284/// - `process.dlopen(module, filename)` - Node.js dynamic loading
2285///
2286/// Returns true if an FFI edge was created, false otherwise.
2287fn build_ffi_call_edge(
2288    ast_graph: &ASTGraph,
2289    call_node: Node<'_>,
2290    content: &[u8],
2291    helper: &mut GraphBuildHelper,
2292) -> GraphResult<bool> {
2293    let Some(callee_expr) = call_node.child_by_field_name("function") else {
2294        return Ok(false);
2295    };
2296
2297    let callee_text = callee_expr
2298        .utf8_text(content)
2299        .map_err(|_| GraphBuilderError::ParseError {
2300            span: span_from_node(call_node),
2301            reason: "failed to read call expression".to_string(),
2302        })?
2303        .trim();
2304
2305    // Check for WebAssembly API calls
2306    if callee_text.starts_with("WebAssembly.") {
2307        return Ok(build_webassembly_call_edge(
2308            ast_graph,
2309            call_node,
2310            content,
2311            callee_text,
2312            helper,
2313        ));
2314    }
2315
2316    // Check for Node.js native addon require
2317    if callee_text == "require" {
2318        return Ok(build_require_ffi_edge(
2319            ast_graph, call_node, content, helper,
2320        ));
2321    }
2322
2323    // Check for process.dlopen
2324    if callee_text == "process.dlopen" {
2325        return Ok(build_dlopen_edge(ast_graph, call_node, content, helper));
2326    }
2327
2328    Ok(false)
2329}
2330
2331/// Build FFI edges for new expressions (constructor calls).
2332///
2333/// Detects:
2334/// - `new WebAssembly.Module(buffer)`
2335/// - `new WebAssembly.Instance(module, imports)`
2336///
2337/// Returns true if an FFI edge was created, false otherwise.
2338fn build_ffi_new_edge(
2339    ast_graph: &ASTGraph,
2340    new_node: Node<'_>,
2341    content: &[u8],
2342    helper: &mut GraphBuildHelper,
2343) -> GraphResult<bool> {
2344    let Some(constructor_expr) = new_node.child_by_field_name("constructor") else {
2345        return Ok(false);
2346    };
2347
2348    let constructor_text = constructor_expr
2349        .utf8_text(content)
2350        .map_err(|_| GraphBuilderError::ParseError {
2351            span: span_from_node(new_node),
2352            reason: "failed to read constructor expression".to_string(),
2353        })?
2354        .trim();
2355
2356    // Check for WebAssembly constructors
2357    if constructor_text == "WebAssembly.Module" || constructor_text == "WebAssembly.Instance" {
2358        return Ok(build_webassembly_constructor_edge(
2359            ast_graph,
2360            new_node,
2361            content,
2362            constructor_text,
2363            helper,
2364        ));
2365    }
2366
2367    Ok(false)
2368}
2369
2370/// Build WebAssembly call edge for API calls like instantiate/compile.
2371fn build_webassembly_call_edge(
2372    ast_graph: &ASTGraph,
2373    call_node: Node<'_>,
2374    content: &[u8],
2375    callee_text: &str,
2376    helper: &mut GraphBuildHelper,
2377) -> bool {
2378    // Extract the method name
2379    let method_name = callee_text
2380        .strip_prefix("WebAssembly.")
2381        .unwrap_or(callee_text);
2382
2383    // Only handle known WebAssembly methods that load/instantiate WASM
2384    let is_wasm_load = matches!(
2385        method_name,
2386        "instantiate" | "instantiateStreaming" | "compile" | "compileStreaming" | "validate"
2387    );
2388
2389    if !is_wasm_load {
2390        return false;
2391    }
2392
2393    // Get caller context
2394    let caller_id = get_caller_node_id(ast_graph, call_node, content, helper);
2395
2396    // Try to extract module path from arguments (if it's a fetch() call or string literal)
2397    let wasm_module_name = extract_wasm_module_name(call_node, content)
2398        .unwrap_or_else(|| format!("wasm::{method_name}"));
2399
2400    // Create WASM module node with qualified name
2401    let wasm_node_id = helper.add_module(&wasm_module_name, Some(span_from_node(call_node)));
2402
2403    // Add WebAssembly edge
2404    helper.add_webassembly_edge(caller_id, wasm_node_id);
2405
2406    true
2407}
2408
2409/// Build WebAssembly edge for constructor calls (new WebAssembly.Module/Instance).
2410fn build_webassembly_constructor_edge(
2411    ast_graph: &ASTGraph,
2412    new_node: Node<'_>,
2413    content: &[u8],
2414    constructor_text: &str,
2415    helper: &mut GraphBuildHelper,
2416) -> bool {
2417    // Get caller context
2418    let caller_id = get_caller_node_id(ast_graph, new_node, content, helper);
2419
2420    // Determine module name
2421    let type_name = constructor_text
2422        .strip_prefix("WebAssembly.")
2423        .unwrap_or(constructor_text);
2424    let wasm_module_name = format!("wasm::{type_name}");
2425
2426    // Create WASM module node
2427    let wasm_node_id = helper.add_module(&wasm_module_name, Some(span_from_node(new_node)));
2428
2429    // Add WebAssembly edge
2430    helper.add_webassembly_edge(caller_id, wasm_node_id);
2431
2432    true
2433}
2434
2435/// Build Import edge for `CommonJS` `require()` calls, plus FFI edge for native addons.
2436///
2437/// Creates an Import edge for all `require()` calls (`CommonJS` module system).
2438/// Additionally creates an FFI edge if the module is a native addon.
2439fn build_require_ffi_edge(
2440    ast_graph: &ASTGraph,
2441    call_node: Node<'_>,
2442    content: &[u8],
2443    helper: &mut GraphBuildHelper,
2444) -> bool {
2445    // Get the first argument (module path)
2446    let Some(args) = call_node.child_by_field_name("arguments") else {
2447        return false;
2448    };
2449
2450    let mut cursor = args.walk();
2451    let first_arg = args
2452        .children(&mut cursor)
2453        .find(|child| !matches!(child.kind(), "(" | ")" | ","));
2454
2455    let Some(arg_node) = first_arg else {
2456        return false;
2457    };
2458
2459    // Extract the module path
2460    let module_path = extract_string_literal(&arg_node, content);
2461    let Some(path) = module_path else {
2462        return false;
2463    };
2464
2465    // Always create an Import edge for CommonJS require() calls
2466    let from_id = helper.add_module("<module>", None);
2467
2468    // Resolve the import path and create import node
2469    let resolved_path = if path.starts_with('.') {
2470        // Relative import - resolve against file path
2471        sqry_core::graph::resolve_import_path(std::path::Path::new(helper.file_path()), &path)
2472            .unwrap_or_else(|_| simple_name(&path).to_string())
2473    } else {
2474        // Package import - use as-is (simple name)
2475        simple_name(&path).to_string()
2476    };
2477
2478    let to_id = helper.add_import(&resolved_path, Some(span_from_node(call_node)));
2479    helper.add_import_edge(from_id, to_id);
2480
2481    // Check if this is a native addon (.node file or known native packages)
2482    let is_native_addon = std::path::Path::new(&path)
2483        .extension()
2484        .is_some_and(|ext| ext.eq_ignore_ascii_case("node"))
2485        || is_known_native_addon(&path);
2486
2487    if is_native_addon {
2488        // Get caller context
2489        let caller_id = get_caller_node_id(ast_graph, call_node, content, helper);
2490
2491        // Create FFI target node
2492        let ffi_name = format!("native::{}", simple_name(&path));
2493        let ffi_node_id = helper.add_module(&ffi_name, Some(span_from_node(call_node)));
2494
2495        // Add FFI edge with C convention (Node.js native addons use N-API/C ABI)
2496        helper.add_ffi_edge(caller_id, ffi_node_id, FfiConvention::C);
2497    }
2498
2499    true
2500}
2501
2502/// Build FFI edge for `process.dlopen()` calls.
2503fn build_dlopen_edge(
2504    ast_graph: &ASTGraph,
2505    call_node: Node<'_>,
2506    content: &[u8],
2507    helper: &mut GraphBuildHelper,
2508) -> bool {
2509    // Get caller context
2510    let caller_id = get_caller_node_id(ast_graph, call_node, content, helper);
2511
2512    // Try to extract filename from second argument
2513    let module_name = call_node
2514        .child_by_field_name("arguments")
2515        .and_then(|args| {
2516            let mut cursor = args.walk();
2517            args.children(&mut cursor)
2518                .filter(|child| !matches!(child.kind(), "(" | ")" | ","))
2519                .nth(1) // Second argument is the filename
2520        })
2521        .and_then(|node| extract_string_literal(&node, content))
2522        .map_or_else(
2523            || "native::dlopen".to_string(),
2524            |path| format!("native::{}", simple_name(&path)),
2525        );
2526
2527    // Create FFI target node
2528    let ffi_node_id = helper.add_module(&module_name, Some(span_from_node(call_node)));
2529
2530    // Add FFI edge
2531    helper.add_ffi_edge(caller_id, ffi_node_id, FfiConvention::C);
2532
2533    true
2534}
2535
2536/// Get the caller node ID from AST context.
2537fn get_caller_node_id(
2538    ast_graph: &ASTGraph,
2539    node: Node<'_>,
2540    content: &[u8],
2541    helper: &mut GraphBuildHelper,
2542) -> sqry_core::graph::unified::NodeId {
2543    let module_context;
2544    let call_context = if let Some(ctx) = ast_graph.get_callable_context(node.id()) {
2545        ctx
2546    } else {
2547        module_context = CallContext {
2548            name: Arc::from("<module>"),
2549            qualified_name: "<module>".to_string(),
2550            span: (0, content.len()),
2551            is_async: false,
2552        };
2553        &module_context
2554    };
2555
2556    ensure_caller_node(helper, call_context)
2557}
2558
2559fn ensure_caller_node(
2560    helper: &mut GraphBuildHelper,
2561    call_context: &CallContext,
2562) -> sqry_core::graph::unified::NodeId {
2563    let caller_span = Some(Span::from_bytes(call_context.span.0, call_context.span.1));
2564    let qualified_name = call_context.qualified_name();
2565    if qualified_name.contains('.') {
2566        helper.ensure_method(qualified_name, caller_span, call_context.is_async, false)
2567    } else {
2568        helper.ensure_function(qualified_name, caller_span, call_context.is_async, false)
2569    }
2570}
2571
2572/// Try to extract WASM module name from call arguments.
2573///
2574/// Handles patterns like:
2575/// - `WebAssembly.instantiate(fetch('./module.wasm'))` -> "./module.wasm"
2576/// - `WebAssembly.instantiate(buffer)` -> None (can't determine statically)
2577fn extract_wasm_module_name(call_node: Node<'_>, content: &[u8]) -> Option<String> {
2578    let args = call_node.child_by_field_name("arguments")?;
2579
2580    let mut cursor = args.walk();
2581    let first_arg = args
2582        .children(&mut cursor)
2583        .find(|child| !matches!(child.kind(), "(" | ")" | ","))?;
2584
2585    // Check if it's a fetch() call
2586    if first_arg.kind() == "call_expression"
2587        && let Some(func) = first_arg.child_by_field_name("function")
2588    {
2589        let func_text = func.utf8_text(content).ok()?.trim();
2590        if func_text == "fetch" {
2591            // Extract URL from fetch argument
2592            if let Some(fetch_args) = first_arg.child_by_field_name("arguments") {
2593                let mut fetch_cursor = fetch_args.walk();
2594                let url_arg = fetch_args
2595                    .children(&mut fetch_cursor)
2596                    .find(|child| !matches!(child.kind(), "(" | ")" | ","))?;
2597
2598                if let Some(url) = extract_string_literal(&url_arg, content) {
2599                    return Some(format!("wasm::{}", simple_name(&url)));
2600                }
2601            }
2602        }
2603    }
2604
2605    // Check if it's a string literal (file path)
2606    if let Some(path) = extract_string_literal(&first_arg, content) {
2607        return Some(format!("wasm::{}", simple_name(&path)));
2608    }
2609
2610    None
2611}
2612
2613/// Check if a package name is a known native addon.
2614fn is_known_native_addon(package_name: &str) -> bool {
2615    // Common native addon packages
2616    const NATIVE_PACKAGES: &[&str] = &[
2617        "better-sqlite3",
2618        "sqlite3",
2619        "bcrypt",
2620        "sharp",
2621        "canvas",
2622        "node-sass",
2623        "leveldown",
2624        "bufferutil",
2625        "utf-8-validate",
2626        "fsevents",
2627        "cpu-features",
2628        "node-gyp",
2629        "node-pre-gyp",
2630        "prebuild",
2631        "nan",
2632        "node-addon-api",
2633        "ref-napi",
2634        "ffi-napi",
2635    ];
2636
2637    NATIVE_PACKAGES
2638        .iter()
2639        .any(|&pkg| package_name.contains(pkg))
2640}
2641
2642#[cfg(test)]
2643mod shape_tests {
2644    use super::{cf_bucket_for_javascript_kind, javascript_shape_mapping};
2645    use sqry_core::graph::unified::build::shape::{
2646        CfBucket, ShapeBudget, ShapeMapping, compute_shape_descriptor,
2647    };
2648
2649    const SAMPLE: &str = include_str!(concat!(
2650        env!("CARGO_MANIFEST_DIR"),
2651        "/../test-fixtures/shape/reference/sample.js"
2652    ));
2653
2654    fn parse(src: &str) -> tree_sitter::Tree {
2655        let lang: tree_sitter::Language = tree_sitter_javascript::LANGUAGE.into();
2656        let mut p = tree_sitter::Parser::new();
2657        p.set_language(&lang).expect("load javascript grammar");
2658        p.parse(src, None).expect("parse")
2659    }
2660
2661    fn function_named<'t>(tree: &'t tree_sitter::Tree, name: &str) -> tree_sitter::Node<'t> {
2662        let root = tree.root_node();
2663        let mut stack = vec![root];
2664        while let Some(node) = stack.pop() {
2665            if node.kind() == "function_declaration"
2666                && node
2667                    .child_by_field_name("name")
2668                    .and_then(|n| n.utf8_text(SAMPLE.as_bytes()).ok())
2669                    == Some(name)
2670            {
2671                return node;
2672            }
2673            let mut c = node.walk();
2674            for ch in node.children(&mut c) {
2675                stack.push(ch);
2676            }
2677        }
2678        panic!("no function_declaration named {name}");
2679    }
2680
2681    #[test]
2682    fn cf_table_is_non_empty() {
2683        let mapping = javascript_shape_mapping();
2684        let lang: tree_sitter::Language = tree_sitter_javascript::LANGUAGE.into();
2685        let mut covered = 0;
2686        for id in 0..lang.node_kind_count() {
2687            if mapping.cf_bucket(id as u16).is_some() {
2688                covered += 1;
2689            }
2690        }
2691        assert!(
2692            covered >= 10,
2693            "expected many JS CF kinds mapped, got {covered}"
2694        );
2695    }
2696
2697    #[test]
2698    fn histogram_covers_real_control_flow() {
2699        let tree = parse(SAMPLE);
2700        let func = function_named(&tree, "classify");
2701        let d = compute_shape_descriptor(
2702            func,
2703            SAMPLE.as_bytes(),
2704            javascript_shape_mapping(),
2705            &ShapeBudget::default(),
2706        );
2707        assert!(!d.is_unhashable());
2708        for bucket in [
2709            CfBucket::Branch,
2710            CfBucket::Loop,
2711            CfBucket::Match,
2712            CfBucket::Try,
2713            CfBucket::Catch,
2714            CfBucket::Throw,
2715            CfBucket::Return,
2716            CfBucket::BreakContinue,
2717            CfBucket::Call,
2718            CfBucket::Assign,
2719            CfBucket::Closure,
2720        ] {
2721            assert!(
2722                d.cf_histogram[bucket.index()] >= 1,
2723                "classify must exercise {bucket:?}"
2724            );
2725        }
2726    }
2727
2728    #[test]
2729    fn async_body_covers_await() {
2730        let tree = parse(SAMPLE);
2731        let func = function_named(&tree, "fetchValue");
2732        let d = compute_shape_descriptor(
2733            func,
2734            SAMPLE.as_bytes(),
2735            javascript_shape_mapping(),
2736            &ShapeBudget::default(),
2737        );
2738        assert!(d.cf_histogram[CfBucket::Await.index()] >= 1, "await");
2739    }
2740
2741    #[test]
2742    fn signature_shape_reads_arity_defaults_varargs() {
2743        let tree = parse(SAMPLE);
2744        let func = function_named(&tree, "classify");
2745        let mapping = javascript_shape_mapping();
2746        let shape = mapping.signature_shape(func, SAMPLE.as_bytes());
2747        // classify(values, threshold = 0, ...extra)
2748        assert_eq!(shape.arity_positional, 2, "values + threshold = 0");
2749        assert!(shape.has_defaults, "threshold = 0");
2750        assert!(shape.has_varargs, "...extra");
2751        assert!(!shape.has_return_annotation, "JS has no return annotation");
2752    }
2753
2754    #[test]
2755    fn unknown_kind_maps_to_none() {
2756        assert!(cf_bucket_for_javascript_kind("program").is_none());
2757        assert!(cf_bucket_for_javascript_kind("identifier").is_none());
2758    }
2759}