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#[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
46fn infer_visibility(qualified_name: &str) -> &'static str {
49 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 let mut helper = GraphBuildHelper::new(staging, file, Language::JavaScript);
68 let file_arc = Arc::from(file.to_string_lossy().to_string());
69
70 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 for context in ast_graph.contexts() {
80 let span = Some(context.decl_span);
81 let visibility = infer_visibility(&context.qualified_name);
83
84 if context.qualified_name.contains('.') {
86 helper.add_method_with_visibility(
87 &context.qualified_name,
88 span,
89 context.is_async,
90 false, Some(visibility),
92 );
93 } else {
94 helper.add_function_with_visibility(
95 &context.qualified_name,
96 span,
97 context.is_async,
98 false, Some(visibility),
100 );
101 }
102 }
103
104 let mut scope_tree = local_scopes::build(tree.root_node(), content)?;
106
107 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 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
134pub struct JavaScriptShapeMapping {
141 cf_by_kind_id: Vec<Option<CfBucket>>,
142}
143
144impl JavaScriptShapeMapping {
145 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 "identifier" | "object_pattern" | "array_pattern" => {
181 shape.arity_positional = shape.arity_positional.saturating_add(1);
182 }
183 "assignment_pattern" => {
185 shape.arity_positional = shape.arity_positional.saturating_add(1);
186 shape.has_defaults = true;
187 }
188 "rest_pattern" => shape.has_varargs = true,
190 _ => {}
191 }
192 }
193 }
194 shape
196 }
197}
198
199fn 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#[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
231fn 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 let _ = build_http_request_edge(ast_graph, node, content, helper);
245 let _ = detect_route_endpoint(node, content, helper);
247 let is_ffi = build_ffi_call_edge(ast_graph, node, content, helper)?;
249 if !is_ffi {
250 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 let is_ffi = build_ffi_new_edge(ast_graph, node, content, helper)?;
267 if !is_ffi {
268 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 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 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
324fn 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 let module_context;
333 let call_context = if let Some(ctx) = ast_graph.get_callable_context(call_node.id()) {
334 ctx
335 } else {
336 module_context = CallContext {
338 qualified_name: "<module>".to_string(),
339 decl_span: Span::default(),
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 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 let caller_qname = call_context.qualified_name();
377 let target_qname = if let Some(method_name) = callee_text.strip_prefix("this.") {
378 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 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, 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
430fn detect_route_endpoint(
444 call_node: Node<'_>,
445 content: &[u8],
446 helper: &mut GraphBuildHelper,
447) -> bool {
448 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 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 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 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 let Some(path) = extract_string_literal(&first_arg, content) else {
494 return false;
495 };
496
497 let qualified_name = format!("route::{method_str}::{path}");
499
500 let endpoint_id = helper.add_endpoint(&qualified_name, Some(span_from_node(call_node)));
502
503 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
680fn 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 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 qualified_name: "<module>".to_string(),
694 decl_span: Span::default(),
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
730fn 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 let resolved_path =
762 sqry_core::graph::resolve_import_path(std::path::Path::new(file.as_ref()), &source_text)?;
763
764 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#[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 let module_id = helper.add_module("<module>", None);
790
791 let source_node = export_node.child_by_field_name("source");
793 let is_reexport = source_node.is_some();
794
795 let has_default = export_node
797 .children(&mut export_node.walk())
798 .any(|child| child.kind() == "default");
799
800 let namespace_export = export_node
802 .children(&mut export_node.walk())
803 .find(|child| child.kind() == "namespace_export");
804
805 let has_wildcard = export_node
807 .children(&mut export_node.walk())
808 .any(|child| child.kind() == "*");
809
810 let export_clause = export_node
812 .children(&mut export_node.walk())
813 .find(|child| child.kind() == "export_clause");
814
815 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 let exported_name = if let Some(ref decl) = declaration {
831 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_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 if declaration
846 .as_ref()
847 .is_some_and(|decl| matches!(decl.kind(), "function_declaration" | "class_declaration"))
848 {
849 helper.mark_definition(exported_id);
850 }
851 helper.add_export_edge_full(module_id, exported_id, ExportKind::Default, None);
852 } else if let Some(ns_export) = namespace_export {
853 let alias = ns_export
856 .children(&mut ns_export.walk())
857 .find(|child| child.kind() == "identifier")
858 .and_then(|n| n.utf8_text(content).ok())
859 .map(|s| s.trim().to_string());
860
861 let source_path = source_node
863 .and_then(|s| s.utf8_text(content).ok())
864 .map_or_else(
865 || "<unknown>".to_string(),
866 |s| s.trim().trim_matches(|c| c == '"' || c == '\'').to_string(),
867 );
868
869 let resolved_path = sqry_core::graph::resolve_import_path(
870 std::path::Path::new(file.as_ref()),
871 &source_path,
872 )
873 .unwrap_or(source_path);
874
875 let source_module_id = helper.add_module(&resolved_path, None);
876 helper.add_export_edge_full(
877 module_id,
878 source_module_id,
879 ExportKind::Namespace,
880 alias.as_deref(),
881 );
882 } else if has_wildcard && is_reexport {
883 let source_path = source_node
885 .and_then(|s| s.utf8_text(content).ok())
886 .map_or_else(
887 || "<unknown>".to_string(),
888 |s| s.trim().trim_matches(|c| c == '"' || c == '\'').to_string(),
889 );
890
891 let resolved_path = sqry_core::graph::resolve_import_path(
892 std::path::Path::new(file.as_ref()),
893 &source_path,
894 )
895 .unwrap_or(source_path);
896
897 let source_module_id = helper.add_module(&resolved_path, None);
898 helper.add_export_edge_full(module_id, source_module_id, ExportKind::Reexport, None);
900 } else if let Some(clause) = export_clause {
901 let mut cursor = clause.walk();
903 for child in clause.children(&mut cursor) {
904 if child.kind() == "export_specifier" {
905 let identifiers: Vec<_> = child
908 .children(&mut child.walk())
909 .filter(|n| n.kind() == "identifier")
910 .collect();
911
912 if let Some(first_ident) = identifiers.first() {
913 let local_name = first_ident
914 .utf8_text(content)
915 .ok()
916 .map(|s| s.trim().to_string())
917 .unwrap_or_default();
918
919 if local_name.is_empty() {
920 continue;
921 }
922
923 let alias = identifiers.get(1).and_then(|n| {
925 n.utf8_text(content)
926 .ok()
927 .map(|s| s.trim().to_string())
928 .filter(|s| !s.is_empty())
929 });
930
931 let exported_id = helper.add_function(&local_name, None, false, false);
932
933 let kind = if is_reexport {
934 ExportKind::Reexport
935 } else {
936 ExportKind::Direct
937 };
938
939 helper.add_export_edge_full(module_id, exported_id, kind, alias.as_deref());
940 }
941 }
942 }
943 } else if let Some(decl) = declaration {
944 match decl.kind() {
946 "function_declaration" | "generator_function_declaration" => {
947 if let Some(name_node) = decl.child_by_field_name("name")
948 && let Ok(name) = name_node.utf8_text(content)
949 {
950 let name = name.trim().to_string();
951 if !name.is_empty() {
952 let exported_id = helper.add_function(&name, None, false, false);
953 helper.mark_definition(exported_id);
954 helper.add_export_edge_full(
955 module_id,
956 exported_id,
957 ExportKind::Direct,
958 None,
959 );
960 }
961 }
962 }
963 "class_declaration" => {
964 if let Some(name_node) = decl.child_by_field_name("name")
965 && let Ok(name) = name_node.utf8_text(content)
966 {
967 let name = name.trim().to_string();
968 if !name.is_empty() {
969 let exported_id = helper.add_class(&name, None);
970 helper.mark_definition(exported_id);
971 helper.add_export_edge_full(
972 module_id,
973 exported_id,
974 ExportKind::Direct,
975 None,
976 );
977 }
978 }
979 }
980 "lexical_declaration" | "variable_declaration" => {
981 let mut cursor = decl.walk();
983 for child in decl.children(&mut cursor) {
984 if child.kind() == "variable_declarator"
985 && let Some(name_node) = child.child_by_field_name("name")
986 && let Ok(name) = name_node.utf8_text(content)
987 {
988 let name = name.trim().to_string();
989 if !name.is_empty() {
990 let exported_id = helper.add_variable(&name, None);
991 helper.mark_definition(exported_id);
992 helper.add_export_edge_full(
993 module_id,
994 exported_id,
995 ExportKind::Direct,
996 None,
997 );
998 }
999 }
1000 }
1001 }
1002 _ => {}
1003 }
1004 }
1005}
1006
1007fn build_commonjs_export_edges(
1015 expr_stmt_node: Node<'_>,
1016 content: &[u8],
1017 helper: &mut GraphBuildHelper,
1018) {
1019 let Some(assignment) = expr_stmt_node
1021 .children(&mut expr_stmt_node.walk())
1022 .find(|child| child.kind() == "assignment_expression")
1023 else {
1024 return;
1025 };
1026
1027 let Some(left) = assignment.child_by_field_name("left") else {
1028 return;
1029 };
1030 let Some(right) = assignment.child_by_field_name("right") else {
1031 return;
1032 };
1033
1034 let left_text = left.utf8_text(content).ok().map(|s| s.trim().to_string());
1035 let Some(left_text) = left_text else {
1036 return;
1037 };
1038
1039 let module_id = helper.add_module("<module>", None);
1040
1041 if left_text == "module.exports" {
1043 if right.kind() == "object" {
1044 let mut cursor = right.walk();
1046 for child in right.children(&mut cursor) {
1047 if child.kind() == "shorthand_property_identifier" {
1048 if let Ok(name) = child.utf8_text(content) {
1050 let name = name.trim();
1051 if !name.is_empty() {
1052 let exported_id = helper.add_function(name, None, false, false);
1053 helper.add_export_edge_full(
1054 module_id,
1055 exported_id,
1056 ExportKind::Direct,
1057 None,
1058 );
1059 }
1060 }
1061 } else if child.kind() == "pair" {
1062 if let Some(key_node) = child.child_by_field_name("key")
1064 && let Ok(export_name) = key_node.utf8_text(content)
1065 {
1066 let export_name = export_name.trim();
1067 if !export_name.is_empty() {
1068 let exported_id = helper.add_function(export_name, None, false, false);
1069 helper.add_export_edge_full(
1070 module_id,
1071 exported_id,
1072 ExportKind::Direct,
1073 None,
1074 );
1075 }
1076 }
1077 } else if child.kind() == "spread_element" {
1078 }
1080 }
1081 } else if right.kind() == "identifier" || right.kind() == "member_expression" {
1082 let export_name = right
1084 .utf8_text(content)
1085 .ok()
1086 .map_or_else(|| "default".to_string(), |s| s.trim().to_string());
1087
1088 if !export_name.is_empty() {
1089 let exported_id = helper.add_function(&export_name, None, false, false);
1090 helper.add_export_edge_full(module_id, exported_id, ExportKind::Default, None);
1091 }
1092 } else if matches!(
1093 right.kind(),
1094 "function_expression"
1095 | "arrow_function"
1096 | "class"
1097 | "call_expression"
1098 | "new_expression"
1099 ) {
1100 let exported_id = helper.add_function("default", None, false, false);
1102 helper.mark_definition(exported_id);
1103 helper.add_export_edge_full(module_id, exported_id, ExportKind::Default, None);
1104 }
1105 }
1106 else if left_text.starts_with("exports.") || left_text.starts_with("module.exports.") {
1108 let export_name = if let Some(name) = left_text.strip_prefix("module.exports.") {
1110 name
1111 } else if let Some(name) = left_text.strip_prefix("exports.") {
1112 name
1113 } else {
1114 return;
1115 };
1116
1117 if !export_name.is_empty() {
1118 let exported_id = helper.add_function(export_name, None, false, false);
1119 helper.add_export_edge_full(module_id, exported_id, ExportKind::Direct, None);
1120 }
1121 }
1122}
1123
1124fn build_inherits_edge_with_helper(
1131 class_node: Node<'_>,
1132 content: &[u8],
1133 helper: &mut GraphBuildHelper,
1134) {
1135 let heritage = class_node
1137 .children(&mut class_node.walk())
1138 .find(|child| child.kind() == "class_heritage");
1139
1140 let Some(heritage_node) = heritage else {
1141 return; };
1143
1144 let class_name = if class_node.kind() == "class_declaration" {
1146 class_node
1147 .child_by_field_name("name")
1148 .and_then(|n| n.utf8_text(content).ok())
1149 .map(|s| s.trim().to_string())
1150 } else {
1151 class_node
1153 .parent()
1154 .filter(|p| p.kind() == "variable_declarator")
1155 .and_then(|p| p.child_by_field_name("name"))
1156 .and_then(|n| n.utf8_text(content).ok())
1157 .map(|s| s.trim().to_string())
1158 .or_else(|| {
1159 Some(SyntheticNameBuilder::from_node_with_hash(
1161 &class_node,
1162 content,
1163 "class",
1164 ))
1165 })
1166 };
1167
1168 let parent_name = extract_parent_class_name(heritage_node, content);
1171
1172 if let (Some(child_name), Some(parent_name)) = (class_name, parent_name)
1174 && !child_name.is_empty()
1175 && !parent_name.is_empty()
1176 {
1177 let child_id = helper.add_class(&child_name, None);
1178 let parent_id = helper.add_class(&parent_name, None);
1179 helper.add_inherits_edge(child_id, parent_id);
1180 }
1181}
1182
1183fn extract_parent_class_name(heritage_node: Node<'_>, content: &[u8]) -> Option<String> {
1198 let mut cursor = heritage_node.walk();
1199 for child in heritage_node.children(&mut cursor) {
1200 match child.kind() {
1201 "identifier" => {
1202 return child.utf8_text(content).ok().map(|s| s.trim().to_string());
1204 }
1205 "member_expression" => {
1206 return child.utf8_text(content).ok().map(|s| s.trim().to_string());
1209 }
1210 "call_expression" => {
1211 return child.utf8_text(content).ok().map(|s| s.trim().to_string());
1216 }
1217 _ => {}
1218 }
1219 }
1220 None
1221}
1222
1223fn simple_name(name: &str) -> &str {
1224 name.rsplit(['.', '/']).next().unwrap_or(name)
1227}
1228
1229fn normalize_optional_chain(text: &str) -> String {
1233 text.replace("?.", ".")
1234 .trim()
1235 .trim_end_matches('.')
1236 .to_string()
1237}
1238
1239fn check_uses_await(call_node: Node<'_>) -> bool {
1240 let mut current = call_node;
1242 for _ in 0..2 {
1243 if let Some(parent) = current.parent() {
1245 if parent.kind() == "await_expression" {
1246 return true;
1247 }
1248 current = parent;
1249 } else {
1250 break;
1251 }
1252 }
1253 false
1254}
1255
1256fn count_arguments(node: Node<'_>) -> usize {
1257 node.child_by_field_name("arguments").map_or(0, |args| {
1258 let mut count = 0;
1259 let mut cursor = args.walk();
1260 for child in args.children(&mut cursor) {
1261 if !matches!(child.kind(), "(" | ")" | ",") {
1262 count += 1;
1263 }
1264 }
1265 count
1266 })
1267}
1268
1269fn span_from_node(node: Node<'_>) -> Span {
1270 let start = node.start_position();
1271 let end = node.end_position();
1272 Span::new(
1273 Position::new(start.row, start.column),
1274 Position::new(end.row, end.column),
1275 )
1276}
1277
1278fn extract_string_literal(node: &Node, content: &[u8]) -> Option<String> {
1279 let text = node.utf8_text(content).ok()?;
1280 let trimmed = text.trim();
1281
1282 trimmed
1284 .strip_prefix('"')
1285 .and_then(|s| s.strip_suffix('"'))
1286 .or_else(|| {
1287 trimmed
1288 .strip_prefix('\'')
1289 .and_then(|s| s.strip_suffix('\''))
1290 })
1291 .or_else(|| trimmed.strip_prefix('`').and_then(|s| s.strip_suffix('`')))
1292 .map(std::string::ToString::to_string)
1293}
1294
1295#[derive(Debug, Clone)]
1298pub struct CallContext {
1299 pub qualified_name: String,
1300 pub decl_span: Span,
1302 pub is_async: bool,
1303}
1304
1305impl CallContext {
1306 pub fn qualified_name(&self) -> &str {
1307 &self.qualified_name
1308 }
1309}
1310
1311pub struct ASTGraph {
1312 callable_map: HashMap<usize, usize>,
1314 context_map: HashMap<usize, CallContext>,
1316}
1317
1318impl ASTGraph {
1319 pub fn from_tree(tree: &Tree, content: &[u8], max_scope_depth: usize) -> Result<Self, String> {
1321 let mut builder = ASTGraphBuilder::new(content, max_scope_depth);
1322
1323 let recursion_limits = sqry_core::config::RecursionLimits::load_or_default()
1325 .map_err(|e| format!("Failed to load recursion limits: {e}"))?;
1326 let file_ops_depth = recursion_limits
1327 .effective_file_ops_depth()
1328 .map_err(|e| format!("Invalid file_ops_depth configuration: {e}"))?;
1329 let mut guard = sqry_core::query::security::RecursionGuard::new(file_ops_depth)
1330 .map_err(|e| format!("Failed to create recursion guard: {e}"))?;
1331
1332 builder
1333 .visit(tree.root_node(), None, &mut guard)
1334 .map_err(|e| format!("JavaScript AST traversal hit recursion limit: {e}"))?;
1335 Ok(builder.build())
1336 }
1337
1338 pub fn get_callable_context(&self, node_id: usize) -> Option<&CallContext> {
1340 let callable_id = self.callable_map.get(&node_id)?;
1341 self.context_map.get(callable_id)
1342 }
1343
1344 pub fn contexts(&self) -> impl Iterator<Item = &CallContext> {
1346 self.context_map.values()
1347 }
1348}
1349
1350struct ASTGraphBuilder<'a> {
1351 content: &'a [u8],
1352 max_scope_depth: usize,
1353 callable_map: HashMap<usize, usize>,
1354 context_map: HashMap<usize, CallContext>,
1355 current_scope: Vec<Arc<str>>,
1356}
1357
1358impl<'a> ASTGraphBuilder<'a> {
1359 fn new(content: &'a [u8], max_scope_depth: usize) -> Self {
1360 Self {
1361 content,
1362 max_scope_depth,
1363 callable_map: HashMap::new(),
1364 context_map: HashMap::new(),
1365 current_scope: Vec::new(),
1366 }
1367 }
1368
1369 fn build(self) -> ASTGraph {
1370 ASTGraph {
1371 callable_map: self.callable_map,
1372 context_map: self.context_map,
1373 }
1374 }
1375
1376 fn visit(
1380 &mut self,
1381 node: Node<'_>,
1382 parent_callable: Option<usize>,
1383 guard: &mut sqry_core::query::security::RecursionGuard,
1384 ) -> Result<(), sqry_core::query::security::RecursionError> {
1385 guard.enter()?;
1386
1387 let node_id = node.id();
1388
1389 let callable_name = callable_node_name(node, self.content);
1391
1392 let new_callable = if let Some(name) = callable_name {
1393 let is_async = is_async_function(node, self.content);
1395
1396 let qualified_name = if self.current_scope.is_empty() {
1397 name.clone()
1398 } else if self.current_scope.len() <= self.max_scope_depth {
1399 format!("{}.{}", self.current_scope.join("."), name)
1400 } else {
1401 let truncated = &self.current_scope[..self.max_scope_depth];
1403 format!("{}.{}", truncated.join("."), name)
1404 };
1405
1406 let context = CallContext {
1407 qualified_name,
1408 decl_span: Span::from_node(&node),
1409 is_async,
1410 };
1411
1412 self.context_map.insert(node_id, context);
1413 Some(node_id)
1414 } else {
1415 None
1416 };
1417
1418 let effective_callable = new_callable.or(parent_callable);
1420
1421 if let Some(callable_id) = effective_callable {
1423 self.callable_map.insert(node_id, callable_id);
1424 }
1425
1426 let scope_name = scope_node_name(node, self.content);
1428 let pushed_scope = if let Some(name) = scope_name {
1429 self.current_scope.push(Arc::from(name));
1430 true
1431 } else {
1432 false
1433 };
1434
1435 let mut cursor = node.walk();
1437 for child in node.children(&mut cursor) {
1438 self.visit(child, effective_callable, guard)?;
1439 }
1440
1441 if pushed_scope {
1443 self.current_scope.pop();
1444 }
1445
1446 guard.exit();
1447 Ok(())
1448 }
1449}
1450
1451fn callable_node_name(node: Node<'_>, content: &[u8]) -> Option<String> {
1453 match node.kind() {
1454 "function_declaration" | "generator_function_declaration" => node
1455 .child_by_field_name("name")
1456 .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string())),
1457 "function_expression" | "generator_function" => {
1458 node.child_by_field_name("name")
1460 .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string()))
1461 .or_else(|| {
1462 Some(SyntheticNameBuilder::from_node_with_hash(
1463 &node, content, "function",
1464 ))
1465 })
1466 }
1467 "arrow_function" => {
1468 if let Some(parent) = node.parent()
1472 && parent.kind() == "variable_declarator"
1473 && let Some(name_node) = parent.child_by_field_name("name")
1474 && let Ok(name) = name_node.utf8_text(content)
1475 {
1476 let trimmed = name.trim();
1477 if !trimmed.is_empty() {
1478 return Some(trimmed.to_string());
1479 }
1480 }
1481 Some(SyntheticNameBuilder::from_node_with_hash(
1484 &node, content, "arrow",
1485 ))
1486 }
1487 "method_definition" => node
1488 .child_by_field_name("name")
1489 .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string())),
1490 _ => None,
1491 }
1492}
1493
1494fn scope_node_name(node: Node<'_>, content: &[u8]) -> Option<String> {
1495 match node.kind() {
1496 "class_declaration" | "class" => node
1497 .child_by_field_name("name")
1498 .and_then(|child| child.utf8_text(content).ok().map(|s| s.trim().to_string()))
1499 .or_else(|| {
1500 Some(SyntheticNameBuilder::from_node_with_hash(
1501 &node, content, "class",
1502 ))
1503 }),
1504 _ => None,
1505 }
1506}
1507
1508fn is_async_function(node: Node<'_>, _content: &[u8]) -> bool {
1509 let mut cursor = node.walk();
1511 node.children(&mut cursor)
1512 .any(|child| child.kind() == "async")
1513}
1514
1515fn process_jsdoc_annotations(
1520 node: Node,
1521 content: &[u8],
1522 helper: &mut GraphBuildHelper,
1523) -> GraphResult<()> {
1524 match node.kind() {
1526 "function_declaration" | "generator_function_declaration" => {
1527 process_function_jsdoc(node, content, helper)?;
1528 }
1529 "method_definition" => {
1530 process_method_jsdoc(node, content, helper)?;
1531 }
1532 "lexical_declaration" | "variable_declaration" => {
1533 process_variable_jsdoc(node, content, helper)?;
1534 }
1535 "class_declaration" | "class" => {
1536 process_class_fields(node, content, helper)?;
1537 process_constructor_this_assignments(node, content, helper)?;
1538 }
1539 _ => {}
1540 }
1541
1542 let mut cursor = node.walk();
1544 for child in node.children(&mut cursor) {
1545 process_jsdoc_annotations(child, content, helper)?;
1546 }
1547
1548 Ok(())
1549}
1550
1551fn process_function_jsdoc(
1553 func_node: Node,
1554 content: &[u8],
1555 helper: &mut GraphBuildHelper,
1556) -> GraphResult<()> {
1557 let Some(jsdoc_text) = extract_jsdoc_comment(func_node, content) else {
1559 return Ok(());
1560 };
1561
1562 let tags = parse_jsdoc_tags(&jsdoc_text);
1564
1565 let Some(name_node) = func_node.child_by_field_name("name") else {
1567 return Ok(());
1568 };
1569
1570 let function_name = name_node
1571 .utf8_text(content)
1572 .map_err(|_| GraphBuilderError::ParseError {
1573 span: span_from_node(func_node),
1574 reason: "failed to read function name".to_string(),
1575 })?
1576 .trim()
1577 .to_string();
1578
1579 if function_name.is_empty() {
1580 return Ok(());
1581 }
1582
1583 let func_node_id = helper.ensure_callee(
1585 &function_name,
1586 span_from_node(func_node),
1587 CalleeKindHint::Function,
1588 );
1589
1590 let ast_params = extract_ast_parameters(func_node, content);
1593 let ast_param_map: HashMap<&str, usize> = ast_params
1594 .iter()
1595 .map(|(idx, name)| (name.as_str(), *idx))
1596 .collect();
1597
1598 for param_tag in &tags.params {
1600 let mut normalized_name = param_tag
1603 .name
1604 .trim_start_matches("...")
1605 .trim_matches(|c| c == '[' || c == ']');
1606
1607 if let Some(base_name) = normalized_name.split('.').next() {
1610 normalized_name = base_name;
1611 }
1612
1613 let Some(&ast_index) = ast_param_map.get(normalized_name) else {
1614 continue;
1616 };
1617
1618 let canonical_type = canonical_type_string(¶m_tag.type_str);
1620 let type_node_id = helper.add_type(&canonical_type, None);
1621 helper.add_typeof_edge_with_context(
1622 func_node_id,
1623 type_node_id,
1624 Some(TypeOfContext::Parameter),
1625 ast_index.try_into().ok(), Some(¶m_tag.name),
1627 );
1628
1629 let type_names = extract_type_names(¶m_tag.type_str);
1631 for type_name in type_names {
1632 let ref_type_id = helper.add_type(&type_name, None);
1633 helper.add_reference_edge(func_node_id, ref_type_id);
1634 }
1635 }
1636
1637 if let Some(return_type) = &tags.returns {
1639 let canonical_type = canonical_type_string(return_type);
1640 let type_node_id = helper.add_type(&canonical_type, None);
1641 helper.add_typeof_edge_with_context(
1642 func_node_id,
1643 type_node_id,
1644 Some(TypeOfContext::Return),
1645 Some(0),
1646 None,
1647 );
1648
1649 let type_names = extract_type_names(return_type);
1651 for type_name in type_names {
1652 let ref_type_id = helper.add_type(&type_name, None);
1653 helper.add_reference_edge(func_node_id, ref_type_id);
1654 }
1655 }
1656
1657 Ok(())
1658}
1659
1660fn process_method_jsdoc(
1662 method_node: Node,
1663 content: &[u8],
1664 helper: &mut GraphBuildHelper,
1665) -> GraphResult<()> {
1666 let Some(jsdoc_text) = extract_jsdoc_comment(method_node, content) else {
1668 return Ok(());
1669 };
1670
1671 let tags = parse_jsdoc_tags(&jsdoc_text);
1673
1674 let Some(name_node) = method_node.child_by_field_name("name") else {
1676 return Ok(());
1677 };
1678
1679 let method_name = name_node
1680 .utf8_text(content)
1681 .map_err(|_| GraphBuilderError::ParseError {
1682 span: span_from_node(method_node),
1683 reason: "failed to read method name".to_string(),
1684 })?
1685 .trim()
1686 .to_string();
1687
1688 if method_name.is_empty() {
1689 return Ok(());
1690 }
1691
1692 let class_name = get_enclosing_class_name(method_node, content)?;
1694 let Some(class_name) = class_name else {
1695 return Ok(());
1696 };
1697
1698 let qualified_name = format!("{class_name}.{method_name}");
1700
1701 let method_node_id = helper.ensure_method(&qualified_name, None, false, false);
1704
1705 let ast_params = extract_ast_parameters(method_node, content);
1708 let ast_param_map: HashMap<&str, usize> = ast_params
1709 .iter()
1710 .map(|(idx, name)| (name.as_str(), *idx))
1711 .collect();
1712
1713 for param_tag in &tags.params {
1715 let mut normalized_name = param_tag
1718 .name
1719 .trim_start_matches("...")
1720 .trim_matches(|c| c == '[' || c == ']');
1721
1722 if let Some(base_name) = normalized_name.split('.').next() {
1725 normalized_name = base_name;
1726 }
1727
1728 let Some(&ast_index) = ast_param_map.get(normalized_name) else {
1729 continue;
1731 };
1732
1733 let canonical_type = canonical_type_string(¶m_tag.type_str);
1734 let type_node_id = helper.add_type(&canonical_type, None);
1735 helper.add_typeof_edge_with_context(
1736 method_node_id,
1737 type_node_id,
1738 Some(TypeOfContext::Parameter),
1739 ast_index.try_into().ok(), Some(¶m_tag.name),
1741 );
1742
1743 let type_names = extract_type_names(¶m_tag.type_str);
1745 for type_name in type_names {
1746 let ref_type_id = helper.add_type(&type_name, None);
1747 helper.add_reference_edge(method_node_id, ref_type_id);
1748 }
1749 }
1750
1751 if let Some(return_type) = &tags.returns {
1753 let canonical_type = canonical_type_string(return_type);
1754 let type_node_id = helper.add_type(&canonical_type, None);
1755 helper.add_typeof_edge_with_context(
1756 method_node_id,
1757 type_node_id,
1758 Some(TypeOfContext::Return),
1759 Some(0),
1760 None,
1761 );
1762
1763 let type_names = extract_type_names(return_type);
1765 for type_name in type_names {
1766 let ref_type_id = helper.add_type(&type_name, None);
1767 helper.add_reference_edge(method_node_id, ref_type_id);
1768 }
1769 }
1770
1771 Ok(())
1772}
1773
1774fn process_variable_jsdoc(
1776 decl_node: Node,
1777 content: &[u8],
1778 helper: &mut GraphBuildHelper,
1779) -> GraphResult<()> {
1780 if !is_top_level_variable(decl_node) {
1782 return Ok(());
1783 }
1784
1785 let Some(jsdoc_text) = extract_jsdoc_comment(decl_node, content) else {
1787 return Ok(());
1788 };
1789
1790 let tags = parse_jsdoc_tags(&jsdoc_text);
1792
1793 let Some(type_annotation) = &tags.type_annotation else {
1795 return Ok(());
1796 };
1797
1798 let mut cursor = decl_node.walk();
1800 for child in decl_node.children(&mut cursor) {
1801 if child.kind() == "variable_declarator"
1802 && let Some(name_node) = child.child_by_field_name("name")
1803 {
1804 let var_name = name_node
1805 .utf8_text(content)
1806 .map_err(|_| GraphBuilderError::ParseError {
1807 span: span_from_node(child),
1808 reason: "failed to read variable name".to_string(),
1809 })?
1810 .trim()
1811 .to_string();
1812
1813 if !var_name.is_empty() {
1814 let var_node_id = helper.add_variable(&var_name, None);
1816
1817 let canonical_type = canonical_type_string(type_annotation);
1819 let type_node_id = helper.add_type(&canonical_type, None);
1820 helper.add_typeof_edge_with_context(
1821 var_node_id,
1822 type_node_id,
1823 Some(TypeOfContext::Variable),
1824 None,
1825 None,
1826 );
1827
1828 let type_names = extract_type_names(type_annotation);
1830 for type_name in type_names {
1831 let ref_type_id = helper.add_type(&type_name, None);
1832 helper.add_reference_edge(var_node_id, ref_type_id);
1833 }
1834 }
1835 }
1836 }
1837
1838 Ok(())
1839}
1840
1841fn resolve_class_name_for_fields(
1852 class_node: Node<'_>,
1853 content: &[u8],
1854) -> GraphResult<Option<String>> {
1855 if let Some(name_node) = class_node.child_by_field_name("name") {
1856 let name = name_node
1857 .utf8_text(content)
1858 .map_err(|_| GraphBuilderError::ParseError {
1859 span: span_from_node(class_node),
1860 reason: "failed to read class name".to_string(),
1861 })?
1862 .trim()
1863 .to_string();
1864 if name.is_empty() {
1865 return Ok(None);
1866 }
1867 return Ok(Some(name));
1868 }
1869
1870 let Some(parent) = class_node.parent() else {
1872 return Ok(None);
1873 };
1874
1875 match parent.kind() {
1876 "variable_declarator" => {
1877 if let Some(name_node) = parent.child_by_field_name("name")
1878 && let Ok(var_name) = name_node.utf8_text(content)
1879 {
1880 let var_name = var_name.trim().to_string();
1881 if var_name.is_empty() {
1882 return Ok(None);
1883 }
1884 return Ok(Some(var_name));
1885 }
1886 Ok(None)
1887 }
1888 "assignment_expression" => {
1889 if let Some(left) = parent.child_by_field_name("left")
1890 && let Ok(assign_name) = left.utf8_text(content)
1891 {
1892 let assign_name = assign_name.trim().to_string();
1893 if assign_name.is_empty() {
1894 return Ok(None);
1895 }
1896 return Ok(Some(assign_name));
1897 }
1898 Ok(None)
1899 }
1900 _ => Ok(None),
1901 }
1902}
1903
1904fn process_class_fields(
1920 class_node: Node<'_>,
1921 content: &[u8],
1922 helper: &mut GraphBuildHelper,
1923) -> GraphResult<()> {
1924 let Some(class_name) = resolve_class_name_for_fields(class_node, content)? else {
1925 return Ok(());
1926 };
1927
1928 let Some(body_node) = class_node.child_by_field_name("body") else {
1929 return Ok(());
1930 };
1931
1932 let mut cursor = body_node.walk();
1933 for child in body_node.children(&mut cursor) {
1934 if child.kind() != "field_definition" {
1935 continue;
1936 }
1937 emit_class_field_node(child, content, helper, &class_name)?;
1938 }
1939
1940 Ok(())
1941}
1942
1943fn emit_class_field_node(
1946 field_node: Node<'_>,
1947 content: &[u8],
1948 helper: &mut GraphBuildHelper,
1949 class_name: &str,
1950) -> GraphResult<()> {
1951 let Some(name_node) = field_node.child_by_field_name("property") else {
1955 return Ok(());
1956 };
1957
1958 let raw_name = name_node
1959 .utf8_text(content)
1960 .map_err(|_| GraphBuilderError::ParseError {
1961 span: span_from_node(field_node),
1962 reason: "failed to read field name".to_string(),
1963 })?
1964 .trim()
1965 .to_string();
1966
1967 if raw_name.is_empty() {
1968 return Ok(());
1969 }
1970
1971 let is_hash_private = name_node.kind() == "private_property_identifier";
1972
1973 let mut is_static = false;
1978 let mut mod_cursor = field_node.walk();
1979 for modifier in field_node.children(&mut mod_cursor) {
1980 if modifier.kind() == "static" {
1981 is_static = true;
1982 }
1983 }
1984
1985 let visibility: Option<&str> = if is_hash_private {
1991 Some("private")
1992 } else {
1993 Some("public")
1994 };
1995
1996 let qualified_name = format!("{class_name}.{raw_name}");
1997 let span = Some(span_from_node(field_node));
1998
1999 let field_id = helper.add_property_with_static_and_visibility(
2000 &qualified_name,
2001 span,
2002 is_static,
2003 visibility,
2004 );
2005
2006 if let Some(jsdoc_text) = extract_jsdoc_comment(field_node, content) {
2010 let tags = parse_jsdoc_tags(&jsdoc_text);
2011 if let Some(type_annotation) = &tags.type_annotation {
2012 let canonical_type = canonical_type_string(type_annotation);
2013 let type_node_id = helper.add_type(&canonical_type, None);
2014 helper.add_typeof_edge_with_context(
2015 field_id,
2016 type_node_id,
2017 Some(TypeOfContext::Field),
2018 None,
2019 Some(&raw_name),
2020 );
2021
2022 let type_names = extract_type_names(type_annotation);
2023 for type_name in type_names {
2024 let ref_type_id = helper.add_type(&type_name, None);
2025 helper.add_reference_edge(field_id, ref_type_id);
2026 }
2027 }
2028 }
2029
2030 Ok(())
2031}
2032
2033fn process_constructor_this_assignments(
2045 class_node: Node<'_>,
2046 content: &[u8],
2047 helper: &mut GraphBuildHelper,
2048) -> GraphResult<()> {
2049 let Some(class_name) = resolve_class_name_for_fields(class_node, content)? else {
2050 return Ok(());
2051 };
2052
2053 let Some(body_node) = class_node.child_by_field_name("body") else {
2054 return Ok(());
2055 };
2056
2057 let mut cursor = body_node.walk();
2058 for child in body_node.children(&mut cursor) {
2059 if child.kind() != "method_definition" {
2060 continue;
2061 }
2062
2063 let Some(name_node) = child.child_by_field_name("name") else {
2068 continue;
2069 };
2070 let Ok(method_name) = name_node.utf8_text(content) else {
2071 continue;
2072 };
2073 if method_name.trim() != "constructor" {
2074 continue;
2075 }
2076
2077 let Some(method_body) = child.child_by_field_name("body") else {
2078 continue;
2079 };
2080
2081 walk_for_this_assignments(method_body, content, helper, &class_name);
2082 }
2083
2084 Ok(())
2085}
2086
2087fn walk_for_this_assignments(
2091 node: Node<'_>,
2092 content: &[u8],
2093 helper: &mut GraphBuildHelper,
2094 class_name: &str,
2095) {
2096 if node.kind() == "assignment_expression"
2097 && let Some(left) = node.child_by_field_name("left")
2098 && left.kind() == "member_expression"
2099 && let Some(object) = left.child_by_field_name("object")
2100 && object.kind() == "this"
2101 && let Some(property) = left.child_by_field_name("property")
2102 && property.kind() == "property_identifier"
2103 && let Ok(field_name) = property.utf8_text(content)
2104 {
2105 let field_name = field_name.trim();
2106 if !field_name.is_empty() {
2107 let qualified_name = format!("{class_name}.{field_name}");
2108 let _ = helper.add_property_with_static_and_visibility(
2118 &qualified_name,
2119 Some(span_from_node(left)),
2120 false,
2121 Some("public"),
2122 );
2123 }
2124 }
2125
2126 let mut cursor = node.walk();
2134 for child in node.children(&mut cursor) {
2135 walk_for_this_assignments(child, content, helper, class_name);
2136 }
2137}
2138
2139fn get_enclosing_class_name(method_node: Node, content: &[u8]) -> GraphResult<Option<String>> {
2143 let mut current = method_node;
2145 while let Some(parent) = current.parent() {
2146 if parent.kind() == "class_declaration" {
2147 if let Some(name_node) = parent.child_by_field_name("name") {
2149 let class_name = name_node
2150 .utf8_text(content)
2151 .map_err(|_| GraphBuilderError::ParseError {
2152 span: span_from_node(parent),
2153 reason: "failed to read class name".to_string(),
2154 })?
2155 .trim()
2156 .to_string();
2157
2158 if !class_name.is_empty() {
2159 return Ok(Some(class_name));
2160 }
2161 }
2162 } else if parent.kind() == "class" {
2163 if let Some(grandparent) = parent.parent() {
2166 if grandparent.kind() == "variable_declarator" {
2167 if let Some(name_node) = grandparent.child_by_field_name("name")
2169 && let Ok(var_name) = name_node.utf8_text(content)
2170 {
2171 let var_name = var_name.trim().to_string();
2172 if !var_name.is_empty() {
2173 return Ok(Some(var_name));
2174 }
2175 }
2176 } else if grandparent.kind() == "assignment_expression" {
2177 if let Some(left) = grandparent.child_by_field_name("left")
2179 && let Ok(assign_name) = left.utf8_text(content)
2180 {
2181 let assign_name = assign_name.trim().to_string();
2182 if !assign_name.is_empty() {
2183 return Ok(Some(assign_name));
2184 }
2185 }
2186 }
2187 }
2188 return Ok(None);
2191 }
2192 current = parent;
2193 }
2194 Ok(None)
2195}
2196
2197fn extract_ast_parameters(func_node: Node, content: &[u8]) -> Vec<(usize, String)> {
2200 let Some(params_node) = func_node.child_by_field_name("parameters") else {
2201 return Vec::new();
2202 };
2203
2204 let mut cursor = params_node.walk();
2205 params_node
2206 .named_children(&mut cursor)
2207 .enumerate()
2208 .filter_map(|(ast_index, param)| {
2209 let param_name = match param.kind() {
2211 "identifier" => param
2212 .utf8_text(content)
2213 .ok()
2214 .map(std::string::ToString::to_string),
2215 "required_parameter" | "optional_parameter" => {
2216 param
2218 .child_by_field_name("pattern")
2219 .and_then(|p| p.utf8_text(content).ok())
2220 .map(std::string::ToString::to_string)
2221 }
2222 "rest_pattern" => {
2223 param
2226 .named_child(0)
2227 .and_then(|n| n.utf8_text(content).ok())
2228 .map(|s| s.trim_start_matches("...").to_string())
2229 }
2230 "assignment_pattern" => {
2231 param
2234 .child_by_field_name("left")
2235 .filter(|left| left.kind() == "identifier")
2236 .and_then(|left| left.utf8_text(content).ok())
2237 .map(std::string::ToString::to_string)
2238 }
2239 _ => None,
2240 };
2241
2242 param_name.map(|name| (ast_index, name))
2243 })
2244 .collect()
2245}
2246
2247fn is_top_level_variable(decl_node: Node) -> bool {
2250 let mut current = decl_node;
2251 while let Some(parent) = current.parent() {
2252 match parent.kind() {
2253 "function_declaration"
2255 | "generator_function_declaration"
2256 | "function_expression"
2257 | "arrow_function"
2258 | "method_definition" => return false,
2259
2260 "statement_block" | "if_statement" | "for_statement" | "for_in_statement"
2262 | "for_of_statement" | "while_statement" | "do_statement" | "try_statement"
2263 | "catch_clause" | "finally_clause" | "switch_statement" | "switch_case"
2264 | "switch_default" | "class_body" | "class_static_block" | "with_statement" => {
2265 return false;
2266 }
2267
2268 "program" | "export_statement" => return true,
2271
2272 _ => {}
2273 }
2274 current = parent;
2275 }
2276 true
2277}
2278
2279fn build_ffi_call_edge(
2291 ast_graph: &ASTGraph,
2292 call_node: Node<'_>,
2293 content: &[u8],
2294 helper: &mut GraphBuildHelper,
2295) -> GraphResult<bool> {
2296 let Some(callee_expr) = call_node.child_by_field_name("function") else {
2297 return Ok(false);
2298 };
2299
2300 let callee_text = callee_expr
2301 .utf8_text(content)
2302 .map_err(|_| GraphBuilderError::ParseError {
2303 span: span_from_node(call_node),
2304 reason: "failed to read call expression".to_string(),
2305 })?
2306 .trim();
2307
2308 if callee_text.starts_with("WebAssembly.") {
2310 return Ok(build_webassembly_call_edge(
2311 ast_graph,
2312 call_node,
2313 content,
2314 callee_text,
2315 helper,
2316 ));
2317 }
2318
2319 if callee_text == "require" {
2321 return Ok(build_require_ffi_edge(
2322 ast_graph, call_node, content, helper,
2323 ));
2324 }
2325
2326 if callee_text == "process.dlopen" {
2328 return Ok(build_dlopen_edge(ast_graph, call_node, content, helper));
2329 }
2330
2331 Ok(false)
2332}
2333
2334fn build_ffi_new_edge(
2342 ast_graph: &ASTGraph,
2343 new_node: Node<'_>,
2344 content: &[u8],
2345 helper: &mut GraphBuildHelper,
2346) -> GraphResult<bool> {
2347 let Some(constructor_expr) = new_node.child_by_field_name("constructor") else {
2348 return Ok(false);
2349 };
2350
2351 let constructor_text = constructor_expr
2352 .utf8_text(content)
2353 .map_err(|_| GraphBuilderError::ParseError {
2354 span: span_from_node(new_node),
2355 reason: "failed to read constructor expression".to_string(),
2356 })?
2357 .trim();
2358
2359 if constructor_text == "WebAssembly.Module" || constructor_text == "WebAssembly.Instance" {
2361 return Ok(build_webassembly_constructor_edge(
2362 ast_graph,
2363 new_node,
2364 constructor_text,
2365 helper,
2366 ));
2367 }
2368
2369 Ok(false)
2370}
2371
2372fn build_webassembly_call_edge(
2374 ast_graph: &ASTGraph,
2375 call_node: Node<'_>,
2376 content: &[u8],
2377 callee_text: &str,
2378 helper: &mut GraphBuildHelper,
2379) -> bool {
2380 let method_name = callee_text
2382 .strip_prefix("WebAssembly.")
2383 .unwrap_or(callee_text);
2384
2385 let is_wasm_load = matches!(
2387 method_name,
2388 "instantiate" | "instantiateStreaming" | "compile" | "compileStreaming" | "validate"
2389 );
2390
2391 if !is_wasm_load {
2392 return false;
2393 }
2394
2395 let caller_id = get_caller_node_id(ast_graph, call_node, helper);
2397
2398 let wasm_module_name = extract_wasm_module_name(call_node, content)
2400 .unwrap_or_else(|| format!("wasm::{method_name}"));
2401
2402 let wasm_node_id = helper.add_module(&wasm_module_name, Some(span_from_node(call_node)));
2404
2405 helper.add_webassembly_edge(caller_id, wasm_node_id);
2407
2408 true
2409}
2410
2411fn build_webassembly_constructor_edge(
2413 ast_graph: &ASTGraph,
2414 new_node: Node<'_>,
2415 constructor_text: &str,
2416 helper: &mut GraphBuildHelper,
2417) -> bool {
2418 let caller_id = get_caller_node_id(ast_graph, new_node, helper);
2420
2421 let type_name = constructor_text
2423 .strip_prefix("WebAssembly.")
2424 .unwrap_or(constructor_text);
2425 let wasm_module_name = format!("wasm::{type_name}");
2426
2427 let wasm_node_id = helper.add_module(&wasm_module_name, Some(span_from_node(new_node)));
2429
2430 helper.add_webassembly_edge(caller_id, wasm_node_id);
2432
2433 true
2434}
2435
2436fn build_require_ffi_edge(
2441 ast_graph: &ASTGraph,
2442 call_node: Node<'_>,
2443 content: &[u8],
2444 helper: &mut GraphBuildHelper,
2445) -> bool {
2446 let Some(args) = call_node.child_by_field_name("arguments") else {
2448 return false;
2449 };
2450
2451 let mut cursor = args.walk();
2452 let first_arg = args
2453 .children(&mut cursor)
2454 .find(|child| !matches!(child.kind(), "(" | ")" | ","));
2455
2456 let Some(arg_node) = first_arg else {
2457 return false;
2458 };
2459
2460 let module_path = extract_string_literal(&arg_node, content);
2462 let Some(path) = module_path else {
2463 return false;
2464 };
2465
2466 let from_id = helper.add_module("<module>", None);
2468
2469 let resolved_path = if path.starts_with('.') {
2471 sqry_core::graph::resolve_import_path(std::path::Path::new(helper.file_path()), &path)
2473 .unwrap_or_else(|_| simple_name(&path).to_string())
2474 } else {
2475 simple_name(&path).to_string()
2477 };
2478
2479 let to_id = helper.add_import(&resolved_path, Some(span_from_node(call_node)));
2480 helper.add_import_edge(from_id, to_id);
2481
2482 let is_native_addon = std::path::Path::new(&path)
2484 .extension()
2485 .is_some_and(|ext| ext.eq_ignore_ascii_case("node"))
2486 || is_known_native_addon(&path);
2487
2488 if is_native_addon {
2489 let caller_id = get_caller_node_id(ast_graph, call_node, helper);
2491
2492 let ffi_name = format!("native::{}", simple_name(&path));
2494 let ffi_node_id = helper.add_module(&ffi_name, Some(span_from_node(call_node)));
2495
2496 helper.add_ffi_edge(caller_id, ffi_node_id, FfiConvention::C);
2498 }
2499
2500 true
2501}
2502
2503fn build_dlopen_edge(
2505 ast_graph: &ASTGraph,
2506 call_node: Node<'_>,
2507 content: &[u8],
2508 helper: &mut GraphBuildHelper,
2509) -> bool {
2510 let caller_id = get_caller_node_id(ast_graph, call_node, helper);
2512
2513 let module_name = call_node
2515 .child_by_field_name("arguments")
2516 .and_then(|args| {
2517 let mut cursor = args.walk();
2518 args.children(&mut cursor)
2519 .filter(|child| !matches!(child.kind(), "(" | ")" | ","))
2520 .nth(1) })
2522 .and_then(|node| extract_string_literal(&node, content))
2523 .map_or_else(
2524 || "native::dlopen".to_string(),
2525 |path| format!("native::{}", simple_name(&path)),
2526 );
2527
2528 let ffi_node_id = helper.add_module(&module_name, Some(span_from_node(call_node)));
2530
2531 helper.add_ffi_edge(caller_id, ffi_node_id, FfiConvention::C);
2533
2534 true
2535}
2536
2537fn get_caller_node_id(
2539 ast_graph: &ASTGraph,
2540 node: Node<'_>,
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 qualified_name: "<module>".to_string(),
2549 decl_span: Span::default(),
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(call_context.decl_span);
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
2572fn 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 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 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 if let Some(path) = extract_string_literal(&first_arg, content) {
2607 return Some(format!("wasm::{}", simple_name(&path)));
2608 }
2609
2610 None
2611}
2612
2613fn is_known_native_addon(package_name: &str) -> bool {
2615 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 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}