1use std::path::Path;
13use std::sync::LazyLock;
14
15use oxc_allocator::Allocator;
16use oxc_ast_visit::Visit;
17use oxc_parser::Parser;
18use oxc_span::SourceType;
19use rustc_hash::{FxHashMap, FxHashSet};
20
21use crate::asset_url::normalize_asset_url;
22use crate::parse::compute_import_binding_usage;
23use crate::sfc_template::{SfcKind, collect_template_usage_with_bound_targets};
24use crate::source_map::ExtractionResult;
25use crate::visitor::ModuleInfoExtractor;
26use crate::{ImportInfo, ImportedName, ModuleInfo};
27use fallow_types::discover::FileId;
28use fallow_types::extract::{FunctionComplexity, byte_offset_to_line_col, compute_line_offsets};
29use oxc_span::Span;
30
31static SCRIPT_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
34 crate::static_regex(
35 r#"(?is)<script\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</script>"#,
36 )
37});
38
39static LANG_ATTR_RE: LazyLock<regex::Regex> =
41 LazyLock::new(|| crate::static_regex(r#"lang\s*=\s*["'](\w+)["']"#));
42
43static SRC_ATTR_RE: LazyLock<regex::Regex> =
46 LazyLock::new(|| crate::static_regex(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#));
47
48static SETUP_ATTR_RE: LazyLock<regex::Regex> =
50 LazyLock::new(|| crate::static_regex(r"(?:^|\s)setup(?:\s|$)"));
51
52static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
54 LazyLock::new(|| crate::static_regex(r#"context\s*=\s*["']module["']"#));
55
56static SVELTE_MODULE_ATTR_RE: LazyLock<regex::Regex> =
61 LazyLock::new(|| crate::static_regex(r"(?:^|\s)module(?:\s|$|=)"));
62
63static VUE_GENERIC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
67 crate::static_regex(r#"(?:^|\s)generic\s*=\s*"([^"]*)"|(?:^|\s)generic\s*=\s*'([^']*)'"#)
68});
69
70static SVELTE_GENERICS_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
73 crate::static_regex(r#"(?:^|\s)generics\s*=\s*"([^"]*)"|(?:^|\s)generics\s*=\s*'([^']*)'"#)
74});
75
76static HTML_COMMENT_RE: LazyLock<regex::Regex> =
78 LazyLock::new(|| crate::static_regex(r"(?s)<!--.*?-->"));
79
80static PROPS_ATTRS_SPREAD_RE: LazyLock<regex::Regex> =
85 LazyLock::new(|| crate::static_regex(r#"v-bind\s*=\s*["'](?:\$attrs|\$props|props)["']"#));
86
87static SVELTE_TEMPLATE_DATA_WHOLE_USE_RE: LazyLock<regex::Regex> =
95 LazyLock::new(|| crate::static_regex(r"(?:=\s*\{\s*data\s*\}|\{\s*\.\.\.\s*data\s*\})"));
96
97static TEMPLATE_EMIT_CALL_RE: LazyLock<regex::Regex> =
107 LazyLock::new(|| crate::static_regex(r#"([\w$]+)\s*\(\s*(?:'([\w:-]*)'|"([\w:-]*)"|(\S))"#));
108
109static STYLE_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
113 crate::static_regex(
114 r#"(?is)<style\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</style>"#,
115 )
116});
117
118static TEMPLATE_ASSET_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
133 crate::static_regex(
134 r#"(?si)<(?:img|source|video|audio|track|embed)\b(?:[^>"']|"[^"]*"|'[^']*')*?\s(?:src|poster)\s*=\s*(?:"((?:\./|\.\./)[^"<>{}?#\s]*)"|'((?:\./|\.\./)[^'<>{}?#\s]*)')"#,
135 )
136});
137
138fn mask_non_markup_regions(source: &str) -> String {
142 let mut masked = source.to_string();
143 for re in [&*SCRIPT_BLOCK_RE, &*STYLE_BLOCK_RE, &*HTML_COMMENT_RE] {
144 masked = re
145 .replace_all(&masked, |caps: ®ex::Captures<'_>| {
146 " ".repeat(caps[0].len())
147 })
148 .into_owned();
149 }
150 masked
151}
152
153fn collect_template_asset_refs(source: &str) -> Vec<(String, Span)> {
156 let masked = mask_non_markup_regions(source);
157 let mut refs = Vec::new();
158 for caps in TEMPLATE_ASSET_RE.captures_iter(&masked) {
159 let Some(value) = caps.get(1).or_else(|| caps.get(2)) else {
160 continue;
161 };
162 let raw = value.as_str();
163 if raw.is_empty() {
164 continue;
165 }
166 refs.push((
167 normalize_asset_url(raw),
168 Span::new(value.start() as u32, value.end() as u32),
169 ));
170 }
171 refs
172}
173
174pub struct SfcScript {
176 pub body: String,
178 pub is_typescript: bool,
180 pub is_jsx: bool,
182 pub byte_offset: usize,
184 pub src: Option<String>,
186 pub src_span: Option<Span>,
188 pub is_setup: bool,
190 pub is_context_module: bool,
192 pub generic_attr: Option<String>,
196}
197
198pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
200 let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
201 .find_iter(source)
202 .map(|m| (m.start(), m.end()))
203 .collect();
204
205 SCRIPT_BLOCK_RE
206 .captures_iter(source)
207 .filter(|cap| {
208 let start = cap.get(0).map_or(0, |m| m.start());
209 !comment_ranges
210 .iter()
211 .any(|&(cs, ce)| start >= cs && start < ce)
212 })
213 .map(|cap| {
214 let attrs = cap.name("attrs").map_or("", |m| m.as_str());
215 let body_match = cap.name("body");
216 let byte_offset = body_match.map_or(0, |m| m.start());
217 let body = body_match.map_or("", |m| m.as_str()).to_string();
218 let lang = LANG_ATTR_RE
219 .captures(attrs)
220 .and_then(|c| c.get(1))
221 .map(|m| m.as_str());
222 let is_typescript = matches!(lang, Some("ts" | "tsx"));
223 let is_jsx = matches!(lang, Some("tsx" | "jsx"));
224 let src = SRC_ATTR_RE
225 .captures(attrs)
226 .and_then(|c| c.get(1))
227 .map(|m| m.as_str().to_string());
228 let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
229 let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
230 Span::new(
231 (attrs_start + m.start()) as u32,
232 (attrs_start + m.end()) as u32,
233 )
234 });
235 let is_setup = SETUP_ATTR_RE.is_match(attrs);
236 let is_context_module =
241 CONTEXT_MODULE_ATTR_RE.is_match(attrs) || SVELTE_MODULE_ATTR_RE.is_match(attrs);
242 let generic_attr = VUE_GENERIC_ATTR_RE
243 .captures(attrs)
244 .or_else(|| SVELTE_GENERICS_ATTR_RE.captures(attrs))
245 .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
246 .map(|m| m.as_str().to_string())
247 .filter(|value| !value.trim().is_empty());
248 SfcScript {
249 body,
250 is_typescript,
251 is_jsx,
252 byte_offset,
253 src,
254 src_span,
255 is_setup,
256 is_context_module,
257 generic_attr,
258 }
259 })
260 .collect()
261}
262
263pub struct SfcStyle {
265 pub body: String,
267 pub lang: Option<String>,
270 pub src: Option<String>,
272 pub src_span: Option<Span>,
274 pub byte_offset: usize,
276}
277
278pub struct SourceRegion {
281 pub body: String,
283 pub byte_offset: usize,
285}
286
287#[must_use]
293pub fn extract_sfc_template_regions(source: &str) -> Vec<SourceRegion> {
294 let mut ranges: Vec<(usize, usize)> = SCRIPT_BLOCK_RE
295 .find_iter(source)
296 .chain(STYLE_BLOCK_RE.find_iter(source))
297 .chain(HTML_COMMENT_RE.find_iter(source))
298 .map(|m| (m.start(), m.end()))
299 .collect();
300 ranges.sort_unstable_by_key(|(start, _)| *start);
301 ranges_to_gaps(source, &ranges)
302}
303
304pub fn extract_sfc_styles(source: &str) -> Vec<SfcStyle> {
311 let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
312 .find_iter(source)
313 .map(|m| (m.start(), m.end()))
314 .collect();
315
316 STYLE_BLOCK_RE
317 .captures_iter(source)
318 .filter(|cap| {
319 let start = cap.get(0).map_or(0, |m| m.start());
320 !comment_ranges
321 .iter()
322 .any(|&(cs, ce)| start >= cs && start < ce)
323 })
324 .map(|cap| {
325 let attrs = cap.name("attrs").map_or("", |m| m.as_str());
326 let body = cap.name("body").map_or("", |m| m.as_str()).to_string();
327 let byte_offset = cap.name("body").map_or(0, |m| m.start());
328 let lang = LANG_ATTR_RE
329 .captures(attrs)
330 .and_then(|c| c.get(1))
331 .map(|m| m.as_str().to_string());
332 let src = SRC_ATTR_RE
333 .captures(attrs)
334 .and_then(|c| c.get(1))
335 .map(|m| m.as_str().to_string());
336 let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
337 let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
338 Span::new(
339 (attrs_start + m.start()) as u32,
340 (attrs_start + m.end()) as u32,
341 )
342 });
343 SfcStyle {
344 body,
345 lang,
346 src,
347 src_span,
348 byte_offset,
349 }
350 })
351 .collect()
352}
353
354pub(crate) fn ranges_to_gaps(source: &str, ranges: &[(usize, usize)]) -> Vec<SourceRegion> {
358 let mut regions = Vec::new();
359 let mut cursor = 0;
360 for &(start, end) in ranges {
361 if start > cursor {
362 push_region(source, cursor, start, &mut regions);
363 }
364 cursor = cursor.max(end);
365 }
366 if cursor < source.len() {
367 push_region(source, cursor, source.len(), &mut regions);
368 }
369 regions
370}
371
372fn push_region(source: &str, start: usize, end: usize, regions: &mut Vec<SourceRegion>) {
373 let Some(body) = source.get(start..end) else {
374 return;
375 };
376 if body.trim().is_empty() {
377 return;
378 }
379 regions.push(SourceRegion {
380 body: body.to_string(),
381 byte_offset: start,
382 });
383}
384
385#[must_use]
387pub fn is_sfc_file(path: &Path) -> bool {
388 path.extension()
389 .and_then(|e| e.to_str())
390 .is_some_and(|ext| ext == "vue" || ext == "svelte")
391}
392
393pub(crate) fn parse_sfc_to_module(
395 file_id: FileId,
396 path: &Path,
397 source: &str,
398 content_hash: u64,
399 need_complexity: bool,
400) -> ModuleInfo {
401 let scripts = extract_sfc_scripts(source);
402 let styles = extract_sfc_styles(source);
403 let kind = sfc_kind(path);
404 let mut combined = empty_sfc_module(file_id, source, content_hash);
405 let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
406 let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
407 let mut template_visible_iterable_types: FxHashMap<String, String> = FxHashMap::default();
408 let mut props_return_binding: Option<String> = None;
409 let mut emit_return_binding: Option<String> = None;
410
411 for script in &scripts {
412 merge_script_into_module(&mut SfcScriptMergeInput {
413 kind,
414 script,
415 combined: &mut combined,
416 template_visible_imports: &mut template_visible_imports,
417 template_visible_bound_targets: &mut template_visible_bound_targets,
418 template_visible_iterable_types: &mut template_visible_iterable_types,
419 props_return_binding: &mut props_return_binding,
420 emit_return_binding: &mut emit_return_binding,
421 need_complexity,
422 });
423 }
424
425 for style in &styles {
426 merge_style_into_module(style, &mut combined);
427 }
428
429 if kind == SfcKind::Vue
433 && !combined.component_props.is_empty()
434 && PROPS_ATTRS_SPREAD_RE.is_match(source)
435 {
436 combined.has_props_attrs_fallthrough = true;
437 }
438
439 apply_template_usage(TemplateUsageInput {
440 kind,
441 source,
442 template_visible_imports,
443 template_visible_bound_targets,
444 template_visible_iterable_types: &template_visible_iterable_types,
445 props_return_binding: props_return_binding.as_deref(),
446 credit_load_data: kind == SfcKind::Svelte && is_sveltekit_route_data_component(path),
447 combined: &mut combined,
448 });
449
450 if need_complexity {
451 append_template_complexity(kind, source, &mut combined);
452 }
453
454 if kind == SfcKind::Vue && !combined.component_emits.is_empty() {
458 apply_template_emit_usage(source, emit_return_binding.as_deref(), &mut combined);
459 }
460
461 if kind == SfcKind::Svelte {
465 combined.svelte_listened_events =
466 crate::sfc_template::collect_svelte_listened_events(source);
467 }
468
469 append_template_asset_imports(source, &mut combined);
470 dedup_import_binding_lists(&mut combined);
471
472 combined
473}
474
475fn append_template_complexity(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
483 match kind {
484 SfcKind::Vue => {
485 combined.complexity.extend(
486 crate::template_complexity::compute_vue_template_complexity(source),
487 );
488 }
489 SfcKind::Svelte => combined
492 .complexity
493 .extend(crate::template_complexity::compute_svelte_template_complexity(source)),
494 }
495}
496
497fn append_template_asset_imports(source: &str, combined: &mut ModuleInfo) {
501 for (specifier, span) in collect_template_asset_refs(source) {
502 combined.imports.push(ImportInfo {
503 source: specifier,
504 imported_name: ImportedName::SideEffect,
505 local_name: String::new(),
506 is_type_only: false,
507 is_type_only_star: false,
508 from_style: false,
509 span,
510 source_span: span,
511 });
512 }
513}
514
515fn dedup_import_binding_lists(combined: &mut ModuleInfo) {
518 combined.unused_import_bindings.sort_unstable();
519 combined.unused_import_bindings.dedup();
520 combined.type_referenced_import_bindings.sort_unstable();
521 combined.type_referenced_import_bindings.dedup();
522 combined.value_referenced_import_bindings.sort_unstable();
523 combined.value_referenced_import_bindings.dedup();
524 combined.auto_import_candidates.sort_unstable();
525 combined.auto_import_candidates.dedup();
526}
527
528fn sfc_kind(path: &Path) -> SfcKind {
529 if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
530 SfcKind::Vue
531 } else {
532 SfcKind::Svelte
533 }
534}
535
536fn is_sveltekit_route_data_component(path: &Path) -> bool {
547 let Some(stem) = path
548 .file_name()
549 .and_then(|name| name.to_str())
550 .and_then(|name| name.strip_suffix(".svelte"))
551 else {
552 return false;
553 };
554 ["+page", "+layout"].iter().any(|prefix| {
555 stem.strip_prefix(prefix)
556 .is_some_and(|rest| rest.is_empty() || rest.starts_with('@'))
557 })
558}
559
560fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
561 let parsed = crate::suppress::parse_suppressions_from_source(source);
562
563 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
564 file_id,
565 content_hash,
566 source,
567 parsed_suppressions: parsed,
568 imports: Vec::new(),
569 exports: Vec::new(),
570 })
571}
572
573struct SfcScriptMergeInput<'a> {
574 kind: SfcKind,
575 script: &'a SfcScript,
576 combined: &'a mut ModuleInfo,
577 template_visible_imports: &'a mut FxHashSet<String>,
578 template_visible_bound_targets: &'a mut FxHashMap<String, String>,
579 template_visible_iterable_types: &'a mut FxHashMap<String, String>,
580 props_return_binding: &'a mut Option<String>,
581 emit_return_binding: &'a mut Option<String>,
582 need_complexity: bool,
583}
584
585fn merge_script_into_module(input: &mut SfcScriptMergeInput<'_>) {
586 if input.kind == SfcKind::Vue
587 && let Some(src) = &input.script.src
588 {
589 add_script_src_import(input.combined, src, input.script.src_span);
590 }
591
592 let allocator = Allocator::default();
593 let parser_return = Parser::new(
594 &allocator,
595 &input.script.body,
596 source_type_for_script(input.script),
597 )
598 .parse();
599 let mut extractor = ModuleInfoExtractor::new();
600 extractor.set_top_level_is_component_body(is_template_visible_script(input.kind, input.script));
601 extractor.visit_program(&parser_return.program);
602 let empty_template_used = FxHashSet::default();
603 let semantic_usage = crate::parse::compute_semantic_usage_for_extractor(
604 &parser_return.program,
605 &mut extractor,
606 &empty_template_used,
607 );
608 let extraction = ExtractionResult::contiguous(&input.script.body, input.script.byte_offset);
609 extractor.remap_spans_with(|span| extraction.remap_span(span));
610 extractor.resolve_typed_destructure_bindings();
611
612 merge_script_binding_usage(
613 input,
614 &allocator,
615 &extractor.imports,
616 &extractor.import_equals_bindings,
617 semantic_usage,
618 );
619 if input.need_complexity {
620 input
621 .combined
622 .complexity
623 .extend(translate_script_complexity(
624 input.script,
625 &parser_return.program,
626 &input.combined.line_offsets,
627 ));
628 }
629
630 if input.kind == SfcKind::Vue {
634 merge_vue_props_emits_into(input, &parser_return.program, &mut extractor);
635 }
636
637 if input.kind == SfcKind::Svelte && is_template_visible_script(input.kind, input.script) {
642 merge_svelte_props_into(
643 input.combined,
644 &parser_return.program,
645 input.script.byte_offset,
646 );
647 }
648
649 if is_template_visible_script(input.kind, input.script) {
650 harvest_template_visible_bindings(input, &extractor);
651 }
652
653 let dispatch_base = input.combined.svelte_dispatched_events.len();
658 extractor.merge_into(input.combined);
659 for event in &mut input.combined.svelte_dispatched_events[dispatch_base..] {
660 event.span_start += input.script.byte_offset as u32;
661 }
662}
663
664fn merge_script_binding_usage(
675 input: &mut SfcScriptMergeInput<'_>,
676 allocator: &Allocator,
677 imports: &[ImportInfo],
678 import_equals_bindings: &[String],
679 semantic_usage: crate::parse::SemanticUsage,
680) {
681 let augmented_body = build_generic_attr_probe_source(input.script);
682 let empty_template_used = FxHashSet::default();
683 let (binding_usage, auto_import_candidates) = if let Some(augmented) = augmented_body.as_deref()
684 {
685 let augmented_return =
686 Parser::new(allocator, augmented, source_type_for_script(input.script)).parse();
687 (
688 compute_import_binding_usage(
689 &augmented_return.program,
690 imports,
691 import_equals_bindings,
692 &empty_template_used,
693 ),
694 semantic_usage.auto_import_candidates,
695 )
696 } else {
697 (
698 semantic_usage.import_binding_usage,
699 semantic_usage.auto_import_candidates,
700 )
701 };
702 crate::parse::append_declaration_merge_facts(
703 &mut input.combined.semantic_facts,
704 semantic_usage.declaration_merges,
705 input.script.byte_offset as u32,
706 );
707 input
708 .combined
709 .unused_import_bindings
710 .extend(binding_usage.unused.iter().cloned());
711 input
712 .combined
713 .type_referenced_import_bindings
714 .extend(binding_usage.type_referenced.iter().cloned());
715 input
716 .combined
717 .value_referenced_import_bindings
718 .extend(binding_usage.value_referenced.iter().cloned());
719 input
720 .combined
721 .auto_import_candidates
722 .extend(auto_import_candidates);
723}
724
725fn harvest_template_visible_bindings(
729 input: &mut SfcScriptMergeInput<'_>,
730 extractor: &ModuleInfoExtractor,
731) {
732 input.template_visible_imports.extend(
733 extractor
734 .imports
735 .iter()
736 .filter(|import| !import.local_name.is_empty())
737 .map(|import| import.local_name.clone()),
738 );
739 input.template_visible_bound_targets.extend(
740 extractor
741 .binding_target_names()
742 .iter()
743 .filter(|(local, _)| !local.starts_with("this."))
744 .filter_map(|(local, target)| {
745 target
746 .class_name()
747 .map(|class_name| (local.clone(), class_name.to_string()))
748 }),
749 );
750 input.template_visible_iterable_types.extend(
754 extractor
755 .array_binding_element_types()
756 .iter()
757 .filter(|(local, _)| !local.starts_with("this."))
758 .map(|(local, element)| (local.clone(), element.clone())),
759 );
760}
761
762fn merge_svelte_props_into(
766 combined: &mut ModuleInfo,
767 program: &oxc_ast::ast::Program<'_>,
768 byte_offset: usize,
769) {
770 let harvest = crate::sfc_props::harvest_svelte_props(program);
771 if harvest.has_unharvestable_props {
772 combined.has_unharvestable_props = true;
773 }
774 if harvest.has_props_attrs_fallthrough {
775 combined.has_props_attrs_fallthrough = true;
776 }
777 for mut prop in harvest.props {
778 prop.span_start += byte_offset as u32;
779 combined.component_props.push(prop);
780 }
781}
782
783fn merge_vue_props_emits_into(
790 input: &mut SfcScriptMergeInput<'_>,
791 program: &oxc_ast::ast::Program<'_>,
792 extractor: &mut ModuleInfoExtractor,
793) {
794 let byte_offset = input.script.byte_offset as u32;
795 if input.script.is_setup {
796 apply_props_harvest(
797 input,
798 crate::sfc_props::harvest_define_props(program),
799 byte_offset,
800 extractor,
801 );
802 apply_emits_harvest(
803 input,
804 crate::sfc_props::harvest_define_emits(program),
805 byte_offset,
806 );
807 } else {
808 apply_props_harvest(
809 input,
810 crate::sfc_props::harvest_options_api_props(program),
811 byte_offset,
812 extractor,
813 );
814 apply_emits_harvest(
815 input,
816 crate::sfc_props::harvest_options_api_emits(program),
817 byte_offset,
818 );
819 }
820}
821
822fn apply_props_harvest(
828 input: &mut SfcScriptMergeInput<'_>,
829 harvest: crate::sfc_props::DefinePropsHarvest,
830 byte_offset: u32,
831 extractor: &mut ModuleInfoExtractor,
832) {
833 if harvest.has_unharvestable_props {
834 input.combined.has_unharvestable_props = true;
835 }
836 if harvest.has_props_attrs_fallthrough {
837 input.combined.has_props_attrs_fallthrough = true;
838 }
839 if harvest.has_define_expose {
840 input.combined.has_define_expose = true;
841 }
842 if harvest.has_define_model {
843 input.combined.has_define_model = true;
844 }
845 if let Some(binding) = harvest.props_return_binding {
846 *input.props_return_binding = Some(binding);
847 }
848 for (field_name, element_type) in harvest.props_array_element_types {
856 extractor
857 .array_binding_element_types_mut()
858 .insert(format!("props.{field_name}"), element_type);
859 }
860 for mut prop in harvest.props {
861 prop.span_start += byte_offset;
862 input.combined.component_props.push(prop);
863 }
864}
865
866fn apply_emits_harvest(
872 input: &mut SfcScriptMergeInput<'_>,
873 harvest: crate::sfc_props::DefineEmitsHarvest,
874 byte_offset: u32,
875) {
876 if harvest.has_unharvestable_emits {
877 input.combined.has_unharvestable_emits = true;
878 }
879 if harvest.has_dynamic_emit {
880 input.combined.has_dynamic_emit = true;
881 }
882 if harvest.has_emit_whole_object_use {
883 input.combined.has_emit_whole_object_use = true;
884 }
885 if let Some(binding) = harvest.emit_binding {
886 *input.emit_return_binding = Some(binding);
887 }
888 for mut emit in harvest.emits {
889 emit.span_start += byte_offset;
890 input.combined.component_emits.push(emit);
891 }
892}
893
894pub(crate) fn translate_script_complexity(
898 script: &SfcScript,
899 program: &oxc_ast::ast::Program<'_>,
900 sfc_line_offsets: &[u32],
901) -> Vec<FunctionComplexity> {
902 let script_line_offsets = compute_line_offsets(&script.body);
903 let mut complexity =
904 crate::complexity::compute_complexity(program, &script.body, &script_line_offsets);
905 let (body_start_line, body_start_col) = byte_offset_to_line_col(
906 sfc_line_offsets,
907 u32::try_from(script.byte_offset).unwrap_or(u32::MAX),
908 );
909
910 for function in &mut complexity {
911 function.line = body_start_line + function.line.saturating_sub(1);
912 if function.line == body_start_line {
913 function.col += body_start_col;
914 }
915 }
916
917 complexity
918}
919
920fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
921 let span = source_span.unwrap_or_default();
922 module.imports.push(ImportInfo {
923 source: normalize_asset_url(source),
924 imported_name: ImportedName::SideEffect,
925 local_name: String::new(),
926 is_type_only: false,
927 is_type_only_star: false,
928 from_style: false,
929 span,
930 source_span: span,
931 });
932}
933
934fn style_lang_is_scss(lang: Option<&str>) -> bool {
940 matches!(lang, Some("scss" | "sass"))
941}
942
943fn style_lang_is_css_like(lang: Option<&str>) -> bool {
944 lang.is_none() || matches!(lang, Some("css"))
945}
946
947fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
948 if let Some(src) = &style.src {
949 let span = style.src_span.unwrap_or_default();
950 combined.imports.push(ImportInfo {
951 source: normalize_asset_url(src),
952 imported_name: ImportedName::SideEffect,
953 local_name: String::new(),
954 is_type_only: false,
955 is_type_only_star: false,
956 from_style: true,
957 span,
958 source_span: span,
959 });
960 }
961
962 let lang = style.lang.as_deref();
963 let is_scss = style_lang_is_scss(lang);
964 let is_css_like = style_lang_is_css_like(lang);
965 if !is_scss && !is_css_like {
966 return;
967 }
968
969 for source in crate::css::extract_css_import_sources(&style.body, is_scss) {
970 let source_span = Span::new(
971 style.byte_offset as u32 + source.span.start,
972 style.byte_offset as u32 + source.span.end,
973 );
974 combined.imports.push(ImportInfo {
975 source: source.normalized,
976 imported_name: if source.is_plugin {
977 ImportedName::Default
978 } else {
979 ImportedName::SideEffect
980 },
981 local_name: String::new(),
982 is_type_only: false,
983 is_type_only_star: false,
984 from_style: true,
985 span: source_span,
986 source_span,
987 });
988 }
989}
990
991pub(crate) fn source_type_for_script(script: &SfcScript) -> SourceType {
992 match (script.is_typescript, script.is_jsx) {
993 (true, true) => SourceType::tsx(),
994 (true, false) => SourceType::ts(),
995 (false, true) => SourceType::jsx(),
996 (false, false) => SourceType::mjs(),
997 }
998}
999
1000fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
1006 let constraint = script.generic_attr.as_deref()?.trim();
1007 if constraint.is_empty() {
1008 return None;
1009 }
1010 Some(format!(
1011 "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
1012 script.body, constraint,
1013 ))
1014}
1015
1016struct TemplateUsageInput<'a> {
1017 kind: SfcKind,
1018 source: &'a str,
1019 template_visible_imports: FxHashSet<String>,
1020 template_visible_bound_targets: FxHashMap<String, String>,
1021 template_visible_iterable_types: &'a FxHashMap<String, String>,
1022 props_return_binding: Option<&'a str>,
1023 credit_load_data: bool,
1024 combined: &'a mut ModuleInfo,
1025}
1026
1027fn apply_template_usage(input: TemplateUsageInput<'_>) {
1028 let TemplateUsageInput {
1029 kind,
1030 source,
1031 template_visible_imports,
1032 template_visible_bound_targets,
1033 template_visible_iterable_types,
1034 props_return_binding,
1035 credit_load_data,
1036 combined,
1037 } = input;
1038 let credited = build_template_credited_set(
1039 template_visible_imports,
1040 props_return_binding,
1041 credit_load_data,
1042 source,
1043 combined,
1044 );
1045 let template_usage = compute_template_usage(
1046 kind,
1047 source,
1048 &credited,
1049 template_visible_bound_targets,
1050 template_visible_iterable_types,
1051 credit_load_data,
1052 );
1053 apply_prop_template_credit(&template_usage, props_return_binding, combined);
1054 merge_template_usage_into_combined(template_usage, combined);
1055}
1056
1057fn build_template_credited_set(
1063 template_visible_imports: FxHashSet<String>,
1064 props_return_binding: Option<&str>,
1065 credit_load_data: bool,
1066 source: &str,
1067 combined: &mut ModuleInfo,
1068) -> FxHashSet<String> {
1069 let mut credited = template_visible_imports;
1070 if credit_load_data {
1075 credited.insert("data".to_string());
1076 if SVELTE_TEMPLATE_DATA_WHOLE_USE_RE.is_match(source) {
1079 combined.has_load_data_whole_use = true;
1080 }
1081 }
1082 if !combined.component_props.is_empty() {
1083 for prop in &combined.component_props {
1084 credited.insert(prop.name.clone());
1087 credited.insert(prop.local.clone());
1088 }
1089 credited.insert("$props".to_string());
1092 if let Some(binding) = props_return_binding {
1093 credited.insert(binding.to_string());
1094 }
1095 }
1096 credited
1097}
1098
1099fn compute_template_usage(
1104 kind: SfcKind,
1105 source: &str,
1106 credited: &FxHashSet<String>,
1107 mut template_visible_bound_targets: FxHashMap<String, String>,
1108 template_visible_iterable_types: &FxHashMap<String, String>,
1109 credit_load_data: bool,
1110) -> crate::template_usage::TemplateUsage {
1111 if credit_load_data {
1112 template_visible_bound_targets.remove("data");
1113 }
1114 collect_template_usage_with_bound_targets(
1115 kind,
1116 source,
1117 credited,
1118 &template_visible_bound_targets,
1119 template_visible_iterable_types,
1120 )
1121}
1122
1123fn apply_prop_template_credit(
1128 template_usage: &crate::template_usage::TemplateUsage,
1129 props_return_binding: Option<&str>,
1130 combined: &mut ModuleInfo,
1131) {
1132 if !combined.component_props.is_empty() {
1133 let member_used: FxHashSet<&str> = template_usage
1134 .member_accesses
1135 .iter()
1136 .filter(|access| {
1137 access.object == "$props"
1138 || props_return_binding.is_some_and(|binding| access.object == binding)
1139 })
1140 .map(|access| access.member.as_str())
1141 .collect();
1142 for prop in &mut combined.component_props {
1143 if template_usage.used_bindings.contains(&prop.name)
1144 || template_usage.used_bindings.contains(&prop.local)
1145 || member_used.contains(prop.name.as_str())
1146 {
1147 prop.used_in_template = true;
1148 }
1149 }
1150 }
1151
1152 if let Some(binding) = props_return_binding
1153 && (template_usage.used_bindings.contains(binding)
1154 || template_usage
1155 .whole_object_uses
1156 .iter()
1157 .any(|used| used == binding))
1158 {
1159 combined.has_props_attrs_fallthrough = true;
1160 }
1161}
1162
1163fn merge_template_usage_into_combined(
1168 template_usage: crate::template_usage::TemplateUsage,
1169 combined: &mut ModuleInfo,
1170) {
1171 combined
1172 .unused_import_bindings
1173 .retain(|binding| !template_usage.used_bindings.contains(binding));
1174 let mut member_accesses = std::mem::take(&mut combined.member_accesses).to_vec();
1175 member_accesses.extend(template_usage.member_accesses);
1176 combined.member_accesses = member_accesses.into();
1177 let mut whole_object_uses = std::mem::take(&mut combined.whole_object_uses).to_vec();
1178 whole_object_uses.extend(template_usage.whole_object_uses);
1179 combined.whole_object_uses = whole_object_uses.into();
1180 combined
1181 .security_sinks
1182 .extend(template_usage.security_sinks);
1183 if !template_usage.unresolved_tag_names.is_empty() {
1184 let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
1185 names.sort_unstable();
1186 combined.auto_import_candidates.extend(names);
1187 combined.auto_import_candidates.dedup();
1188 }
1189}
1190
1191fn apply_template_emit_usage(
1209 source: &str,
1210 emit_return_binding: Option<&str>,
1211 combined: &mut ModuleInfo,
1212) {
1213 let masked = mask_non_markup_regions(source);
1214 let mut used: FxHashSet<String> = FxHashSet::default();
1215 let mut dynamic = false;
1216
1217 for caps in TEMPLATE_EMIT_CALL_RE.captures_iter(&masked) {
1218 let Some(callee) = caps.get(1) else {
1219 continue;
1220 };
1221 let callee = callee.as_str();
1222 let is_emit_call =
1223 callee == "$emit" || emit_return_binding.is_some_and(|binding| callee == binding);
1224 if !is_emit_call {
1225 continue;
1226 }
1227 if let Some(event) = caps.get(2).or_else(|| caps.get(3)) {
1228 used.insert(event.as_str().to_string());
1231 } else if caps.get(4).is_some() {
1232 dynamic = true;
1235 }
1236 }
1237
1238 if dynamic {
1239 combined.has_dynamic_emit = true;
1240 }
1241 if !used.is_empty() {
1242 for emit in &mut combined.component_emits {
1243 if used.contains(&emit.name) {
1244 emit.used = true;
1245 }
1246 }
1247 }
1248}
1249
1250fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
1251 match kind {
1252 SfcKind::Vue => script.is_setup,
1253 SfcKind::Svelte => !script.is_context_module,
1254 }
1255}
1256
1257#[cfg(all(test, not(miri)))]
1258mod tests {
1259 use super::*;
1260 use fallow_types::extract::{
1261 ClassThisMemberAccessFact, ClassThisWholeObjectUseFact, SemanticFactView,
1262 };
1263
1264 #[test]
1265 fn is_sfc_file_vue() {
1266 assert!(is_sfc_file(Path::new("App.vue")));
1267 }
1268
1269 #[test]
1270 fn is_sfc_file_svelte() {
1271 assert!(is_sfc_file(Path::new("Counter.svelte")));
1272 }
1273
1274 #[test]
1275 fn is_sfc_file_rejects_ts() {
1276 assert!(!is_sfc_file(Path::new("utils.ts")));
1277 }
1278
1279 #[test]
1280 fn is_sfc_file_rejects_jsx() {
1281 assert!(!is_sfc_file(Path::new("App.jsx")));
1282 }
1283
1284 #[test]
1285 fn is_sfc_file_rejects_astro() {
1286 assert!(!is_sfc_file(Path::new("Layout.astro")));
1287 }
1288
1289 #[test]
1290 fn single_plain_script() {
1291 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1292 assert_eq!(scripts.len(), 1);
1293 assert_eq!(scripts[0].body, "const x = 1;");
1294 assert!(!scripts[0].is_typescript);
1295 assert!(!scripts[0].is_jsx);
1296 assert!(scripts[0].src.is_none());
1297 }
1298
1299 #[test]
1300 fn single_ts_script() {
1301 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
1302 assert_eq!(scripts.len(), 1);
1303 assert!(scripts[0].is_typescript);
1304 assert!(!scripts[0].is_jsx);
1305 }
1306
1307 #[test]
1308 fn single_tsx_script() {
1309 let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
1310 assert_eq!(scripts.len(), 1);
1311 assert!(scripts[0].is_typescript);
1312 assert!(scripts[0].is_jsx);
1313 }
1314
1315 #[test]
1316 fn single_jsx_script() {
1317 let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
1318 assert_eq!(scripts.len(), 1);
1319 assert!(!scripts[0].is_typescript);
1320 assert!(scripts[0].is_jsx);
1321 }
1322
1323 #[test]
1324 fn two_script_blocks() {
1325 let source = r#"
1326<script lang="ts">
1327export default {};
1328</script>
1329<script setup lang="ts">
1330const count = 0;
1331</script>
1332"#;
1333 let scripts = extract_sfc_scripts(source);
1334 assert_eq!(scripts.len(), 2);
1335 assert!(scripts[0].body.contains("export default"));
1336 assert!(scripts[1].body.contains("count"));
1337 }
1338
1339 #[test]
1340 fn script_setup_extracted() {
1341 let scripts =
1342 extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
1343 assert_eq!(scripts.len(), 1);
1344 assert!(scripts[0].body.contains("import"));
1345 assert!(scripts[0].is_typescript);
1346 }
1347
1348 #[test]
1349 fn script_src_detected() {
1350 let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
1351 assert_eq!(scripts.len(), 1);
1352 assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
1353 }
1354
1355 #[test]
1358 fn svelte4_context_module_is_module_context() {
1359 let scripts =
1360 extract_sfc_scripts(r#"<script context="module">export const x = 1;</script>"#);
1361 assert_eq!(scripts.len(), 1);
1362 assert!(scripts[0].is_context_module);
1363 }
1364
1365 #[test]
1366 fn svelte5_bare_module_attr_is_module_context() {
1367 let scripts = extract_sfc_scripts(r"<script module>export const x = 1;</script>");
1368 assert_eq!(scripts.len(), 1);
1369 assert!(scripts[0].is_context_module);
1370 }
1371
1372 #[test]
1373 fn svelte5_module_with_lang_is_module_context() {
1374 let scripts =
1375 extract_sfc_scripts(r#"<script module lang="ts">export const x = 1;</script>"#);
1376 assert_eq!(scripts.len(), 1);
1377 assert!(scripts[0].is_context_module);
1378 assert!(scripts[0].is_typescript);
1379 }
1380
1381 #[test]
1382 fn plain_script_is_not_module_context() {
1383 let scripts = extract_sfc_scripts(r"<script>const x = 1;</script>");
1384 assert_eq!(scripts.len(), 1);
1385 assert!(!scripts[0].is_context_module);
1386 }
1387
1388 #[test]
1389 fn lang_ts_script_is_not_module_context() {
1390 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x = 1;</script>"#);
1391 assert_eq!(scripts.len(), 1);
1392 assert!(!scripts[0].is_context_module);
1393 }
1394
1395 #[test]
1396 fn data_module_attr_is_not_module_context() {
1397 let scripts =
1399 extract_sfc_scripts(r#"<script data-module="x" lang="ts">const x = 1;</script>"#);
1400 assert_eq!(scripts.len(), 1);
1401 assert!(!scripts[0].is_context_module);
1402 }
1403
1404 #[test]
1405 fn bare_module_script_is_not_template_visible() {
1406 let module_script = SfcScript {
1409 body: String::new(),
1410 is_typescript: false,
1411 is_jsx: false,
1412 byte_offset: 0,
1413 src: None,
1414 src_span: None,
1415 is_setup: false,
1416 is_context_module: true,
1417 generic_attr: None,
1418 };
1419 assert!(!is_template_visible_script(SfcKind::Svelte, &module_script));
1420 let instance_script = SfcScript {
1421 is_context_module: false,
1422 ..module_script
1423 };
1424 assert!(is_template_visible_script(
1425 SfcKind::Svelte,
1426 &instance_script
1427 ));
1428 }
1429
1430 #[test]
1431 fn data_src_not_treated_as_src() {
1432 let scripts =
1433 extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
1434 assert_eq!(scripts.len(), 1);
1435 assert!(scripts[0].src.is_none());
1436 }
1437
1438 #[test]
1439 fn script_inside_html_comment_filtered() {
1440 let source = r#"
1441<!-- <script lang="ts">import { bad } from 'bad';</script> -->
1442<script lang="ts">import { good } from 'good';</script>
1443"#;
1444 let scripts = extract_sfc_scripts(source);
1445 assert_eq!(scripts.len(), 1);
1446 assert!(scripts[0].body.contains("good"));
1447 }
1448
1449 #[test]
1450 fn spanning_comment_filters_script() {
1451 let source = r#"
1452<!-- disabled:
1453<script lang="ts">import { bad } from 'bad';</script>
1454-->
1455<script lang="ts">const ok = true;</script>
1456"#;
1457 let scripts = extract_sfc_scripts(source);
1458 assert_eq!(scripts.len(), 1);
1459 assert!(scripts[0].body.contains("ok"));
1460 }
1461
1462 #[test]
1463 fn string_containing_comment_markers_not_corrupted() {
1464 let source = r#"
1465<script setup lang="ts">
1466const marker = "<!-- not a comment -->";
1467import { ref } from 'vue';
1468</script>
1469"#;
1470 let scripts = extract_sfc_scripts(source);
1471 assert_eq!(scripts.len(), 1);
1472 assert!(scripts[0].body.contains("import"));
1473 }
1474
1475 #[test]
1476 fn generic_attr_with_angle_bracket() {
1477 let source =
1478 r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
1479 let scripts = extract_sfc_scripts(source);
1480 assert_eq!(scripts.len(), 1);
1481 assert_eq!(scripts[0].body, "const x = 1;");
1482 }
1483
1484 #[test]
1485 fn nested_generic_attr() {
1486 let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
1487 let scripts = extract_sfc_scripts(source);
1488 assert_eq!(scripts.len(), 1);
1489 assert_eq!(scripts[0].body, "const x = 1;");
1490 }
1491
1492 #[test]
1493 fn lang_single_quoted() {
1494 let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
1495 assert_eq!(scripts.len(), 1);
1496 assert!(scripts[0].is_typescript);
1497 }
1498
1499 #[test]
1500 fn uppercase_script_tag() {
1501 let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
1502 assert_eq!(scripts.len(), 1);
1503 assert!(scripts[0].is_typescript);
1504 }
1505
1506 #[test]
1507 fn no_script_block() {
1508 let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
1509 assert!(scripts.is_empty());
1510 }
1511
1512 #[test]
1513 fn empty_script_body() {
1514 let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
1515 assert_eq!(scripts.len(), 1);
1516 assert!(scripts[0].body.is_empty());
1517 }
1518
1519 #[test]
1520 fn whitespace_only_script() {
1521 let scripts = extract_sfc_scripts("<script lang=\"ts\">\n \n</script>");
1522 assert_eq!(scripts.len(), 1);
1523 assert!(scripts[0].body.trim().is_empty());
1524 }
1525
1526 #[test]
1527 fn byte_offset_is_set() {
1528 let source = r#"<template><div/></template><script lang="ts">code</script>"#;
1529 let scripts = extract_sfc_scripts(source);
1530 assert_eq!(scripts.len(), 1);
1531 let offset = scripts[0].byte_offset;
1532 assert_eq!(&source[offset..offset + 4], "code");
1533 }
1534
1535 #[test]
1536 fn script_with_extra_attributes() {
1537 let scripts = extract_sfc_scripts(
1538 r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
1539 );
1540 assert_eq!(scripts.len(), 1);
1541 assert!(scripts[0].is_typescript);
1542 assert!(scripts[0].src.is_none());
1543 }
1544
1545 #[test]
1546 fn multiple_script_blocks_exports_combined() {
1547 let source = r#"
1548<script lang="ts">
1549export const version = '1.0';
1550</script>
1551<script setup lang="ts">
1552import { ref } from 'vue';
1553const count = ref(0);
1554</script>
1555"#;
1556 let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
1557 assert!(
1558 info.exports
1559 .iter()
1560 .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
1561 "export from <script> block should be extracted"
1562 );
1563 assert!(
1564 info.imports.iter().any(|i| i.source == "vue"),
1565 "import from <script setup> block should be extracted"
1566 );
1567 }
1568
1569 #[test]
1570 fn class_this_facts_survive_sfc_script_merge() {
1571 let source = r#"
1572<script lang="ts">
1573export class Service {
1574 client!: Client;
1575
1576 run() {
1577 this.client.execute();
1578 Object.keys(this.client);
1579 }
1580}
1581</script>
1582"#;
1583 let info = parse_sfc_to_module(FileId(0), Path::new("Service.vue"), source, 0, false);
1584 let facts = SemanticFactView::new(&info.semantic_facts, &info.member_accesses);
1585
1586 assert_eq!(
1587 facts.class_this_member_accesses(),
1588 vec![ClassThisMemberAccessFact {
1589 class_local_name: "Service".to_string(),
1590 object: "this.client".to_string(),
1591 member: "execute".to_string(),
1592 }]
1593 );
1594 assert_eq!(
1595 facts.class_this_whole_object_uses(),
1596 vec![ClassThisWholeObjectUseFact {
1597 class_local_name: "Service".to_string(),
1598 object: "this.client".to_string(),
1599 }]
1600 );
1601 }
1602
1603 #[test]
1604 fn lang_tsx_detected_as_typescript_jsx() {
1605 let scripts =
1606 extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
1607 assert_eq!(scripts.len(), 1);
1608 assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
1609 assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
1610 }
1611
1612 #[test]
1613 fn multiline_html_comment_filters_all_script_blocks_inside() {
1614 let source = r#"
1615<!--
1616 This whole section is disabled:
1617 <script lang="ts">import { bad1 } from 'bad1';</script>
1618 <script lang="ts">import { bad2 } from 'bad2';</script>
1619-->
1620<script lang="ts">import { good } from 'good';</script>
1621"#;
1622 let scripts = extract_sfc_scripts(source);
1623 assert_eq!(scripts.len(), 1);
1624 assert!(scripts[0].body.contains("good"));
1625 }
1626
1627 #[test]
1628 fn script_src_generates_side_effect_import() {
1629 let info = parse_sfc_to_module(
1630 FileId(0),
1631 Path::new("External.vue"),
1632 r#"<script src="./external-logic.ts" lang="ts"></script>"#,
1633 0,
1634 false,
1635 );
1636 assert!(
1637 info.imports
1638 .iter()
1639 .any(|i| i.source == "./external-logic.ts"
1640 && matches!(i.imported_name, ImportedName::SideEffect)),
1641 "script src should generate a side-effect import"
1642 );
1643 }
1644
1645 #[test]
1646 fn parse_sfc_no_script_returns_empty_module() {
1647 let info = parse_sfc_to_module(
1648 FileId(0),
1649 Path::new("Empty.vue"),
1650 "<template><div>Hello</div></template>",
1651 42,
1652 false,
1653 );
1654 assert!(info.imports.is_empty());
1655 assert!(info.exports.is_empty());
1656 assert_eq!(info.content_hash, 42);
1657 assert_eq!(info.file_id, FileId(0));
1658 }
1659
1660 #[test]
1661 fn parse_sfc_has_line_offsets() {
1662 let info = parse_sfc_to_module(
1663 FileId(0),
1664 Path::new("LineOffsets.vue"),
1665 r#"<script lang="ts">const x = 1;</script>"#,
1666 0,
1667 false,
1668 );
1669 assert!(!info.line_offsets.is_empty());
1670 }
1671
1672 #[test]
1673 fn parse_sfc_has_suppressions() {
1674 let info = parse_sfc_to_module(
1675 FileId(0),
1676 Path::new("Suppressions.vue"),
1677 r#"<script lang="ts">
1678// fallow-ignore-file
1679export const foo = 1;
1680</script>"#,
1681 0,
1682 false,
1683 );
1684 assert!(!info.suppressions.is_empty());
1685 }
1686
1687 #[test]
1688 fn source_type_plain_js_detection() {
1689 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1690 assert_eq!(scripts.len(), 1);
1691 assert!(!scripts[0].is_typescript);
1692 assert!(!scripts[0].is_jsx);
1693 }
1694
1695 #[test]
1696 fn is_sfc_file_rejects_no_extension() {
1697 assert!(!is_sfc_file(Path::new("Makefile")));
1698 }
1699
1700 #[test]
1701 fn is_sfc_file_rejects_mdx() {
1702 assert!(!is_sfc_file(Path::new("post.mdx")));
1703 }
1704
1705 #[test]
1706 fn is_sfc_file_rejects_css() {
1707 assert!(!is_sfc_file(Path::new("styles.css")));
1708 }
1709
1710 #[test]
1711 fn multiple_script_blocks_both_have_offsets() {
1712 let source = r#"<script lang="ts">const a = 1;</script>
1713<script setup lang="ts">const b = 2;</script>"#;
1714 let scripts = extract_sfc_scripts(source);
1715 assert_eq!(scripts.len(), 2);
1716 let offset0 = scripts[0].byte_offset;
1717 let offset1 = scripts[1].byte_offset;
1718 assert_eq!(
1719 &source[offset0..offset0 + "const a = 1;".len()],
1720 "const a = 1;"
1721 );
1722 assert_eq!(
1723 &source[offset1..offset1 + "const b = 2;".len()],
1724 "const b = 2;"
1725 );
1726 }
1727
1728 #[test]
1729 fn script_with_src_and_lang() {
1730 let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
1731 assert_eq!(scripts.len(), 1);
1732 assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
1733 assert!(scripts[0].is_typescript);
1734 assert!(scripts[0].is_jsx);
1735 }
1736
1737 #[test]
1738 fn extract_style_block_lang_scss() {
1739 let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
1740 let styles = extract_sfc_styles(source);
1741 assert_eq!(styles.len(), 1);
1742 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1743 assert!(styles[0].body.contains("@import"));
1744 assert!(styles[0].src.is_none());
1745 }
1746
1747 #[test]
1748 fn extract_style_block_with_src() {
1749 let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
1750 let styles = extract_sfc_styles(source);
1751 assert_eq!(styles.len(), 1);
1752 assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
1753 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1754 }
1755
1756 #[test]
1757 fn extract_style_block_plain_no_lang() {
1758 let source = r"<style>.foo { color: red; }</style>";
1759 let styles = extract_sfc_styles(source);
1760 assert_eq!(styles.len(), 1);
1761 assert!(styles[0].lang.is_none());
1762 }
1763
1764 #[test]
1765 fn extract_multiple_style_blocks() {
1766 let source = r#"<style lang="scss">@import 'a';</style>
1767<style scoped lang="scss">@import 'b';</style>"#;
1768 let styles = extract_sfc_styles(source);
1769 assert_eq!(styles.len(), 2);
1770 }
1771
1772 #[test]
1773 fn style_block_inside_html_comment_filtered() {
1774 let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
1775<style lang="scss">@import 'good';</style>"#;
1776 let styles = extract_sfc_styles(source);
1777 assert_eq!(styles.len(), 1);
1778 assert!(styles[0].body.contains("good"));
1779 }
1780
1781 #[test]
1782 fn parse_sfc_extracts_style_imports_with_from_style_flag() {
1783 let info = parse_sfc_to_module(
1784 FileId(0),
1785 Path::new("Foo.vue"),
1786 r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1787 0,
1788 false,
1789 );
1790 let style_import = info
1791 .imports
1792 .iter()
1793 .find(|i| i.source == "./Foo")
1794 .expect("scss @import 'Foo' should be normalized to ./Foo");
1795 assert!(
1796 style_import.from_style,
1797 "imports from <style> blocks must carry from_style=true so the resolver \
1798 enables SCSS partial fallback for the SFC importer"
1799 );
1800 assert!(matches!(
1801 style_import.imported_name,
1802 ImportedName::SideEffect
1803 ));
1804 }
1805
1806 #[test]
1807 fn parse_sfc_extracts_style_plugin_as_default_import() {
1808 let info = parse_sfc_to_module(
1809 FileId(0),
1810 Path::new("Foo.vue"),
1811 r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1812 0,
1813 false,
1814 );
1815 let plugin_import = info
1816 .imports
1817 .iter()
1818 .find(|i| i.source == "./tailwind-plugin.js")
1819 .expect("style @plugin should create an import");
1820 assert!(plugin_import.from_style);
1821 assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1822 }
1823
1824 #[test]
1825 fn parse_sfc_extracts_style_src_with_from_style_flag() {
1826 let info = parse_sfc_to_module(
1827 FileId(0),
1828 Path::new("Bar.vue"),
1829 r#"<style src="./Bar.scss" lang="scss"></style>"#,
1830 0,
1831 false,
1832 );
1833 let style_src = info
1834 .imports
1835 .iter()
1836 .find(|i| i.source == "./Bar.scss")
1837 .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1838 assert!(style_src.from_style);
1839 }
1840
1841 #[test]
1842 fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1843 let info = parse_sfc_to_module(
1844 FileId(0),
1845 Path::new("Baz.vue"),
1846 r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1847 0,
1848 false,
1849 );
1850 assert!(
1851 info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1852 "src reference should still be seeded for unsupported lang"
1853 );
1854 assert!(
1855 !info.imports.iter().any(|i| i.source.contains("skipped")),
1856 "postcss body should not be scanned for @import directives"
1857 );
1858 }
1859
1860 fn asset_refs(source: &str) -> Vec<String> {
1861 super::collect_template_asset_refs(source)
1862 .into_iter()
1863 .map(|(s, _)| s)
1864 .collect()
1865 }
1866
1867 #[test]
1868 fn captures_static_relative_template_asset_refs() {
1869 assert_eq!(
1870 asset_refs(r#"<template><img src="./logo.png" /></template>"#),
1871 vec!["./logo.png".to_string()]
1872 );
1873 assert_eq!(
1874 asset_refs(r#"<source src="../media/clip.mp4">"#),
1875 vec!["../media/clip.mp4".to_string()]
1876 );
1877 assert_eq!(
1878 asset_refs(r#"<video poster="./thumb.jpg"></video>"#),
1879 vec!["./thumb.jpg".to_string()]
1880 );
1881 }
1882
1883 #[test]
1884 fn skips_dynamic_alias_root_remote_and_query_asset_refs() {
1885 assert!(asset_refs(r#"<img :src="logo" />"#).is_empty());
1887 assert!(asset_refs(r#"<img v-bind:src="logo" />"#).is_empty());
1888 assert!(asset_refs(r#"<img bind:src="logo" />"#).is_empty());
1889 assert!(asset_refs(r"<img src={logo} />").is_empty());
1890 assert!(asset_refs(r#"<img data-src="./x.png" />"#).is_empty());
1891 assert!(asset_refs(r#"<img src="@/assets/x.png" />"#).is_empty());
1893 assert!(asset_refs(r#"<img src="/logo.png" />"#).is_empty());
1894 assert!(asset_refs(r#"<img src="https://cdn/x.png" />"#).is_empty());
1895 assert!(asset_refs(r#"<img src="./x.png?inline" />"#).is_empty());
1897 assert!(asset_refs(r#"<img src="{{ logo }}" />"#).is_empty());
1899 }
1900
1901 #[test]
1902 fn skips_custom_component_src_prop() {
1903 assert!(asset_refs(r#"<MyImage src="./x.png" />"#).is_empty());
1905 assert!(asset_refs(r#"<AppIcon src="../icons/y.svg" />"#).is_empty());
1906 }
1907
1908 #[test]
1909 fn skips_asset_refs_inside_script_style_and_comments() {
1910 assert!(asset_refs(r#"<script>const x = "<img src='./a.png'>"</script>"#).is_empty());
1912 assert!(asset_refs(r#"<style>/* <img src="./b.png"> */ .x{}</style>"#).is_empty());
1913 assert!(asset_refs(r#"<!-- <img src="./c.png" /> -->"#).is_empty());
1914 }
1915
1916 #[test]
1917 fn parse_sfc_emits_template_asset_as_side_effect_import() {
1918 let info = parse_sfc_to_module(
1919 FileId(0),
1920 Path::new("Hero.vue"),
1921 r#"<template><img src="./hero.png" /></template><script>let x=1</script>"#,
1922 0,
1923 false,
1924 );
1925 assert!(
1926 info.imports.iter().any(|i| i.source == "./hero.png"
1927 && matches!(i.imported_name, ImportedName::SideEffect)
1928 && !i.from_style),
1929 "template <img src> should seed a SideEffect import: {:?}",
1930 info.imports
1931 );
1932 }
1933
1934 fn svelte_props(source: &str) -> Vec<crate::ModuleInfo> {
1937 vec![parse_sfc_to_module(
1938 FileId(0),
1939 Path::new("Component.svelte"),
1940 source,
1941 0,
1942 false,
1943 )]
1944 }
1945
1946 fn prop_names(info: &crate::ModuleInfo) -> Vec<String> {
1947 let mut names: Vec<String> = info
1948 .component_props
1949 .iter()
1950 .map(|p| p.name.clone())
1951 .collect();
1952 names.sort();
1953 names
1954 }
1955
1956 #[test]
1957 fn svelte_shorthand_props_harvested() {
1958 let info = &svelte_props(r"<script>let { a, b } = $props();</script>")[0];
1960 assert_eq!(prop_names(info), vec!["a", "b"]);
1961 for prop in &info.component_props {
1962 assert_eq!(prop.local, prop.name);
1963 }
1964 }
1965
1966 #[test]
1967 fn svelte_renamed_prop_tracks_local_and_script_use() {
1968 let info =
1971 &svelte_props(r"<script>let { a: alias } = $props(); console.log(alias);</script>")[0];
1972 assert_eq!(prop_names(info), vec!["a"]);
1973 let prop = &info.component_props[0];
1974 assert_eq!(prop.local, "alias");
1975 assert!(
1976 prop.used_in_script,
1977 "alias is referenced, so a is used in script"
1978 );
1979 }
1980
1981 #[test]
1982 fn svelte_unreferenced_prop_is_unused_in_script() {
1983 let info = &svelte_props(r"<script>let { a } = $props();</script>")[0];
1984 assert_eq!(prop_names(info), vec!["a"]);
1985 assert!(!info.component_props[0].used_in_script);
1986 }
1987
1988 #[test]
1989 fn svelte_default_prop_peeled() {
1990 let info = &svelte_props(r"<script>let { a = 1 } = $props();</script>")[0];
1992 assert_eq!(prop_names(info), vec!["a"]);
1993 }
1994
1995 #[test]
1996 fn svelte_bindable_default_peeled() {
1997 let info = &svelte_props(r"<script>let { a = $bindable() } = $props();</script>")[0];
2000 assert_eq!(prop_names(info), vec!["a"]);
2001 }
2002
2003 #[test]
2004 fn svelte_rest_element_sets_fallthrough_abstain() {
2005 let info = &svelte_props(r"<script>let { a, ...rest } = $props();</script>")[0];
2007 assert!(info.has_props_attrs_fallthrough);
2008 }
2009
2010 #[test]
2011 fn svelte_bare_identifier_binding_sets_unharvestable_abstain() {
2012 let info = &svelte_props(r"<script>let p = $props(); console.log(p.x);</script>")[0];
2014 assert!(info.has_unharvestable_props);
2015 assert!(info.component_props.is_empty());
2016 }
2017
2018 #[test]
2019 fn svelte_nested_destructure_sets_unharvestable_abstain() {
2020 let info = &svelte_props(r"<script>let { a: { x } } = $props();</script>")[0];
2022 assert!(info.has_unharvestable_props);
2023 }
2024
2025 #[test]
2026 fn svelte_prop_used_only_in_markup_credited_as_template_root() {
2027 let info = &svelte_props(r"<script>let { a } = $props();</script><p>{a}</p>")[0];
2030 assert_eq!(prop_names(info), vec!["a"]);
2031 assert!(
2032 info.component_props[0].used_in_template,
2033 "a is used in markup, so used_in_template should be true"
2034 );
2035 }
2036
2037 #[test]
2038 fn svelte_module_script_props_not_harvested() {
2039 let info = &svelte_props(
2041 r"<script module>let { a } = $props();</script><script>let { b } = $props();</script>",
2042 )[0];
2043 assert_eq!(prop_names(info), vec!["b"]);
2045 }
2046
2047 fn dispatched_names(info: &crate::ModuleInfo) -> Vec<String> {
2050 let mut names: Vec<String> = info
2051 .svelte_dispatched_events
2052 .iter()
2053 .map(|e| e.name.clone())
2054 .collect();
2055 names.sort();
2056 names
2057 }
2058
2059 #[test]
2060 fn svelte_dispatch_literal_event_is_harvested() {
2061 let info = &svelte_props(
2062 r"<script>import { createEventDispatcher } from 'svelte';
2063 const dispatch = createEventDispatcher();
2064 function save() { dispatch('save'); }</script>",
2065 )[0];
2066 assert_eq!(dispatched_names(info), vec!["save"]);
2067 assert!(!info.has_dynamic_dispatch);
2068 }
2069
2070 #[test]
2071 fn svelte_dispatch_without_svelte_import_is_ignored() {
2072 let info = &svelte_props(
2075 r"<script>function createEventDispatcher() { return () => {}; }
2076 const dispatch = createEventDispatcher();
2077 dispatch('save');</script>",
2078 )[0];
2079 assert!(info.svelte_dispatched_events.is_empty());
2080 }
2081
2082 #[test]
2083 fn svelte_dynamic_dispatch_sets_abstain() {
2084 let info = &svelte_props(
2085 r"<script>import { createEventDispatcher } from 'svelte';
2086 const dispatch = createEventDispatcher();
2087 function fire(name) { dispatch(name); }</script>",
2088 )[0];
2089 assert!(
2090 info.has_dynamic_dispatch,
2091 "a non-literal dispatch arg must set the abstain flag"
2092 );
2093 }
2094
2095 #[test]
2096 fn svelte_dispatch_whole_value_use_sets_abstain() {
2097 let info = &svelte_props(
2098 r"<script>import { createEventDispatcher } from 'svelte';
2099 const dispatch = createEventDispatcher();
2100 forward(dispatch);</script>",
2101 )[0];
2102 assert!(
2103 info.has_dynamic_dispatch,
2104 "passing the dispatch binding as a whole value must set the abstain flag"
2105 );
2106 }
2107
2108 #[test]
2109 fn svelte_listened_event_on_component_is_harvested() {
2110 let info =
2111 &svelte_props(r"<script>import Child from './Child.svelte';</script><Child on:save />")
2112 [0];
2113 assert!(info.svelte_listened_events.contains(&"save".to_string()));
2114 }
2115}