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
393#[cfg(test)]
395fn parse_sfc_to_module(
396 file_id: FileId,
397 path: &Path,
398 source: &str,
399 content_hash: u64,
400 need_complexity: bool,
401) -> ModuleInfo {
402 parse_sfc_to_module_with_mode(
403 file_id,
404 path,
405 source,
406 content_hash,
407 need_complexity,
408 fallow_types::shared_state::ExtractionMode::Standard,
409 )
410}
411
412pub(crate) fn parse_sfc_to_module_with_mode(
413 file_id: FileId,
414 path: &Path,
415 source: &str,
416 content_hash: u64,
417 need_complexity: bool,
418 mode: fallow_types::shared_state::ExtractionMode,
419) -> ModuleInfo {
420 let scripts = extract_sfc_scripts(source);
421 let styles = extract_sfc_styles(source);
422 let kind = sfc_kind(path);
423 let mut combined = empty_sfc_module(file_id, source, content_hash);
424 let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
425 let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
426 let mut template_visible_iterable_types: FxHashMap<String, String> = FxHashMap::default();
427 let mut props_return_binding: Option<String> = None;
428 let mut emit_return_binding: Option<String> = None;
429 let mut shared_scope_references = SharedScopeReferences::default();
430 let has_setup_script = scripts.iter().any(|script| script.is_setup);
431
432 for script in &scripts {
433 merge_script_into_module(&mut SfcScriptMergeInput {
434 kind,
435 script,
436 has_setup_script,
437 combined: &mut combined,
438 shared_scope_references: &mut shared_scope_references,
439 template_visible_imports: &mut template_visible_imports,
440 template_visible_bound_targets: &mut template_visible_bound_targets,
441 template_visible_iterable_types: &mut template_visible_iterable_types,
442 props_return_binding: &mut props_return_binding,
443 emit_return_binding: &mut emit_return_binding,
444 need_complexity,
445 mode,
446 });
447 }
448 if scripts.len() > 1 {
449 credit_shared_scope_references(&shared_scope_references, &mut combined);
450 }
451
452 for style in &styles {
453 merge_style_into_module(style, &mut combined);
454 }
455
456 if kind == SfcKind::Vue
460 && !combined.component_props.is_empty()
461 && PROPS_ATTRS_SPREAD_RE.is_match(source)
462 {
463 combined.has_props_attrs_fallthrough = true;
464 }
465
466 apply_template_usage(TemplateUsageInput {
467 kind,
468 source,
469 template_visible_imports,
470 template_visible_bound_targets,
471 template_visible_iterable_types: &template_visible_iterable_types,
472 props_return_binding: props_return_binding.as_deref(),
473 credit_load_data: kind == SfcKind::Svelte && is_sveltekit_route_data_component(path),
474 combined: &mut combined,
475 });
476
477 if need_complexity {
478 append_template_complexity(kind, source, &mut combined);
479 }
480
481 if kind == SfcKind::Vue && !combined.component_emits.is_empty() {
485 apply_template_emit_usage(source, emit_return_binding.as_deref(), &mut combined);
486 }
487
488 if kind == SfcKind::Svelte {
492 combined.svelte_listened_events =
493 crate::sfc_template::collect_svelte_listened_events(source);
494 }
495
496 append_template_asset_imports(source, &mut combined);
497 dedup_import_binding_lists(&mut combined);
498 apply_component_contracts(kind, source, &mut combined);
499
500 combined
501}
502
503fn append_template_complexity(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
511 match kind {
512 SfcKind::Vue => {
513 combined.complexity.extend(
514 crate::template_complexity::compute_vue_template_complexity(source),
515 );
516 }
517 SfcKind::Svelte => combined
520 .complexity
521 .extend(crate::template_complexity::compute_svelte_template_complexity(source)),
522 }
523}
524
525fn append_template_asset_imports(source: &str, combined: &mut ModuleInfo) {
529 for (specifier, span) in collect_template_asset_refs(source) {
530 combined.imports.push(ImportInfo {
531 source: specifier,
532 imported_name: ImportedName::SideEffect,
533 local_name: String::new(),
534 is_type_only: false,
535 is_type_only_star: false,
536 from_style: false,
537 span,
538 source_span: span,
539 });
540 }
541}
542
543fn dedup_import_binding_lists(combined: &mut ModuleInfo) {
546 combined.unused_import_bindings.sort_unstable();
547 combined.unused_import_bindings.dedup();
548 combined.type_referenced_import_bindings.sort_unstable();
549 combined.type_referenced_import_bindings.dedup();
550 combined.value_referenced_import_bindings.sort_unstable();
551 combined.value_referenced_import_bindings.dedup();
552 combined.auto_import_candidates.sort_unstable();
553 combined.auto_import_candidates.dedup();
554}
555
556fn sfc_kind(path: &Path) -> SfcKind {
557 if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
558 SfcKind::Vue
559 } else {
560 SfcKind::Svelte
561 }
562}
563
564fn is_sveltekit_route_data_component(path: &Path) -> bool {
575 let Some(stem) = path
576 .file_name()
577 .and_then(|name| name.to_str())
578 .and_then(|name| name.strip_suffix(".svelte"))
579 else {
580 return false;
581 };
582 ["+page", "+layout"].iter().any(|prefix| {
583 stem.strip_prefix(prefix)
584 .is_some_and(|rest| rest.is_empty() || rest.starts_with('@'))
585 })
586}
587
588fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
589 let parsed = crate::suppress_literals::parse_sfc_suppressions(source);
590
591 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
592 file_id,
593 content_hash,
594 source,
595 parsed_suppressions: parsed,
596 imports: Vec::new(),
597 exports: Vec::new(),
598 })
599}
600
601#[path = "sfc_script_merge.rs"]
602mod script_merge;
603use script_merge::{
604 SfcScriptMergeInput, SharedScopeReferences, credit_shared_scope_references,
605 merge_script_into_module,
606};
607
608fn merge_script_binding_usage(
619 input: &mut SfcScriptMergeInput<'_>,
620 allocator: &Allocator,
621 imports: &[ImportInfo],
622 import_equals_bindings: &[String],
623 semantic_usage: crate::parse::SemanticUsage,
624) {
625 let augmented_body = build_generic_attr_probe_source(input.script);
626 let binding_usage = if let Some(augmented) = augmented_body.as_deref() {
627 let augmented_return =
628 Parser::new(allocator, augmented, source_type_for_script(input.script)).parse();
629 let mut probe = compute_import_binding_usage(
630 &augmented_return.program,
631 imports,
632 import_equals_bindings,
633 &FxHashSet::default(),
634 );
635 input
636 .shared_scope_references
637 .record_references(input.kind, &mut probe);
638 probe.import_binding_usage
639 } else {
640 semantic_usage.import_binding_usage
641 };
642 let auto_import_candidates = semantic_usage.auto_import_candidates;
643 crate::parse::append_declaration_merge_facts(
644 &mut input.combined.semantic_facts,
645 semantic_usage.declaration_merges,
646 input.script.byte_offset as u32,
647 );
648 input
649 .combined
650 .unused_import_bindings
651 .extend(binding_usage.unused.iter().cloned());
652 input
653 .combined
654 .type_referenced_import_bindings
655 .extend(binding_usage.type_referenced.iter().cloned());
656 input
657 .combined
658 .value_referenced_import_bindings
659 .extend(binding_usage.value_referenced.iter().cloned());
660 input
661 .combined
662 .auto_import_candidates
663 .extend(auto_import_candidates);
664}
665
666fn harvest_template_visible_bindings(
670 input: &mut SfcScriptMergeInput<'_>,
671 extractor: &ModuleInfoExtractor,
672) {
673 input.template_visible_imports.extend(
674 extractor
675 .imports
676 .iter()
677 .filter(|import| !import.local_name.is_empty())
678 .map(|import| import.local_name.clone()),
679 );
680 input.template_visible_bound_targets.extend(
681 extractor
682 .binding_target_names()
683 .iter()
684 .filter(|(local, _)| !local.starts_with("this."))
685 .filter_map(|(local, target)| {
686 target
687 .class_name()
688 .map(|class_name| (local.clone(), class_name.to_string()))
689 }),
690 );
691 input.template_visible_iterable_types.extend(
695 extractor
696 .array_binding_element_types()
697 .iter()
698 .filter(|(local, _)| !local.starts_with("this."))
699 .map(|(local, element)| (local.clone(), element.clone())),
700 );
701}
702
703fn merge_svelte_props_into(
707 combined: &mut ModuleInfo,
708 program: &oxc_ast::ast::Program<'_>,
709 byte_offset: usize,
710) {
711 let harvest = crate::sfc_props::harvest_svelte_props(program);
712 if harvest.has_unharvestable_props {
713 combined.has_unharvestable_props = true;
714 }
715 if harvest.has_props_attrs_fallthrough {
716 combined.has_props_attrs_fallthrough = true;
717 }
718 for mut prop in harvest.props {
719 prop.span_start += byte_offset as u32;
720 combined.component_props.push(prop);
721 }
722}
723
724fn merge_vue_props_emits_into(
731 input: &mut SfcScriptMergeInput<'_>,
732 program: &oxc_ast::ast::Program<'_>,
733 extractor: &mut ModuleInfoExtractor,
734) {
735 let byte_offset = input.script.byte_offset as u32;
736 if input.script.is_setup {
737 apply_props_harvest(
738 input,
739 crate::sfc_props::harvest_define_props(program),
740 byte_offset,
741 extractor,
742 );
743 apply_emits_harvest(
744 input,
745 crate::sfc_props::harvest_define_emits(program),
746 byte_offset,
747 );
748 } else {
749 apply_props_harvest(
750 input,
751 crate::sfc_props::harvest_options_api_props(program),
752 byte_offset,
753 extractor,
754 );
755 apply_emits_harvest(
756 input,
757 crate::sfc_props::harvest_options_api_emits(program),
758 byte_offset,
759 );
760 }
761}
762
763fn apply_props_harvest(
769 input: &mut SfcScriptMergeInput<'_>,
770 harvest: crate::sfc_props::DefinePropsHarvest,
771 byte_offset: u32,
772 extractor: &mut ModuleInfoExtractor,
773) {
774 if harvest.has_unharvestable_props {
775 input.combined.has_unharvestable_props = true;
776 }
777 if harvest.has_props_attrs_fallthrough {
778 input.combined.has_props_attrs_fallthrough = true;
779 }
780 if harvest.has_define_expose {
781 input.combined.has_define_expose = true;
782 }
783 if harvest.has_define_model {
784 input.combined.has_define_model = true;
785 }
786 if let Some(binding) = harvest.props_return_binding {
787 *input.props_return_binding = Some(binding);
788 }
789 for (field_name, element_type) in harvest.props_array_element_types {
797 extractor
798 .array_binding_element_types_mut()
799 .insert(format!("props.{field_name}"), element_type);
800 }
801 for mut prop in harvest.props {
802 prop.span_start += byte_offset;
803 input.combined.component_props.push(prop);
804 }
805}
806
807fn apply_emits_harvest(
813 input: &mut SfcScriptMergeInput<'_>,
814 harvest: crate::sfc_props::DefineEmitsHarvest,
815 byte_offset: u32,
816) {
817 if harvest.has_unharvestable_emits {
818 input.combined.has_unharvestable_emits = true;
819 }
820 if harvest.has_dynamic_emit {
821 input.combined.has_dynamic_emit = true;
822 }
823 if harvest.has_emit_whole_object_use {
824 input.combined.has_emit_whole_object_use = true;
825 }
826 if let Some(binding) = harvest.emit_binding {
827 *input.emit_return_binding = Some(binding);
828 }
829 for mut emit in harvest.emits {
830 emit.span_start += byte_offset;
831 input.combined.component_emits.push(emit);
832 }
833}
834
835pub(crate) fn translate_script_complexity(
839 script: &SfcScript,
840 program: &oxc_ast::ast::Program<'_>,
841 sfc_line_offsets: &[u32],
842) -> Vec<FunctionComplexity> {
843 let script_line_offsets = compute_line_offsets(&script.body);
844 let mut complexity =
845 crate::complexity::compute_complexity(program, &script.body, &script_line_offsets);
846 let (body_start_line, body_start_col) = byte_offset_to_line_col(
847 sfc_line_offsets,
848 u32::try_from(script.byte_offset).unwrap_or(u32::MAX),
849 );
850
851 for function in &mut complexity {
852 function.line = body_start_line + function.line.saturating_sub(1);
853 if function.line == body_start_line {
854 function.col += body_start_col;
855 }
856 }
857
858 complexity
859}
860
861fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
862 let span = source_span.unwrap_or_default();
863 module.imports.push(ImportInfo {
864 source: normalize_asset_url(source),
865 imported_name: ImportedName::SideEffect,
866 local_name: String::new(),
867 is_type_only: false,
868 is_type_only_star: false,
869 from_style: false,
870 span,
871 source_span: span,
872 });
873}
874
875fn style_lang_is_scss(lang: Option<&str>) -> bool {
881 matches!(lang, Some("scss" | "sass"))
882}
883
884fn style_lang_is_css_like(lang: Option<&str>) -> bool {
885 lang.is_none() || matches!(lang, Some("css"))
886}
887
888fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
889 if let Some(src) = &style.src {
890 let span = style.src_span.unwrap_or_default();
891 combined.imports.push(ImportInfo {
892 source: normalize_asset_url(src),
893 imported_name: ImportedName::SideEffect,
894 local_name: String::new(),
895 is_type_only: false,
896 is_type_only_star: false,
897 from_style: true,
898 span,
899 source_span: span,
900 });
901 }
902
903 let lang = style.lang.as_deref();
904 let is_scss = style_lang_is_scss(lang);
905 if !is_scss && !style_lang_is_css_like(lang) {
906 return;
907 }
908
909 let masked = crate::css_url::mask_style_block(&style.body, is_scss, combined);
910 for source in crate::css::import_sources_from_masked(&masked, is_scss) {
911 let source_span = Span::new(
912 style.byte_offset as u32 + source.span.start,
913 style.byte_offset as u32 + source.span.end,
914 );
915 combined.imports.push(ImportInfo {
916 source: source.normalized,
917 imported_name: if source.is_plugin {
918 ImportedName::Default
919 } else {
920 ImportedName::SideEffect
921 },
922 local_name: String::new(),
923 is_type_only: false,
924 is_type_only_star: false,
925 from_style: true,
926 span: source_span,
927 source_span,
928 });
929 }
930}
931
932pub(crate) fn source_type_for_script(script: &SfcScript) -> SourceType {
933 source_type_for(script.is_typescript, script.is_jsx)
934}
935
936fn source_type_for(is_typescript: bool, is_jsx: bool) -> SourceType {
937 match (is_typescript, is_jsx) {
938 (true, true) => SourceType::tsx(),
939 (true, false) => SourceType::ts(),
940 (false, true) => SourceType::jsx(),
941 (false, false) => SourceType::mjs(),
942 }
943}
944
945#[must_use]
955pub fn sfc_merged_script_source(source: &str) -> Option<(String, SourceType)> {
956 let scripts: Vec<SfcScript> = extract_sfc_scripts(source)
957 .into_iter()
958 .filter(|script| script.src.is_none())
959 .collect();
960 if scripts.is_empty() {
961 return None;
962 }
963 let is_typescript = scripts.iter().any(|script| script.is_typescript);
964 let is_jsx = scripts.iter().any(|script| script.is_jsx);
965 let mut merged = String::new();
966 for script in &scripts {
967 let body = build_generic_attr_probe_source(script);
968 merged.push_str(body.as_deref().unwrap_or(&script.body));
969 merged.push_str("\n;\n");
970 }
971 Some((merged, source_type_for(is_typescript, is_jsx)))
972}
973
974fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
980 let constraint = script.generic_attr.as_deref()?.trim();
981 if constraint.is_empty() {
982 return None;
983 }
984 Some(format!(
985 "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
986 script.body, constraint,
987 ))
988}
989
990struct TemplateUsageInput<'a> {
991 kind: SfcKind,
992 source: &'a str,
993 template_visible_imports: FxHashSet<String>,
994 template_visible_bound_targets: FxHashMap<String, String>,
995 template_visible_iterable_types: &'a FxHashMap<String, String>,
996 props_return_binding: Option<&'a str>,
997 credit_load_data: bool,
998 combined: &'a mut ModuleInfo,
999}
1000
1001fn apply_template_usage(input: TemplateUsageInput<'_>) {
1002 let TemplateUsageInput {
1003 kind,
1004 source,
1005 template_visible_imports,
1006 template_visible_bound_targets,
1007 template_visible_iterable_types,
1008 props_return_binding,
1009 credit_load_data,
1010 combined,
1011 } = input;
1012 let credited = build_template_credited_set(
1013 template_visible_imports,
1014 props_return_binding,
1015 credit_load_data,
1016 source,
1017 combined,
1018 );
1019 let template_usage = compute_template_usage(
1020 kind,
1021 source,
1022 &credited,
1023 template_visible_bound_targets,
1024 template_visible_iterable_types,
1025 credit_load_data,
1026 );
1027 apply_prop_template_credit(&template_usage, props_return_binding, combined);
1028 merge_template_usage_into_combined(template_usage, combined);
1029}
1030
1031fn build_template_credited_set(
1037 template_visible_imports: FxHashSet<String>,
1038 props_return_binding: Option<&str>,
1039 credit_load_data: bool,
1040 source: &str,
1041 combined: &mut ModuleInfo,
1042) -> FxHashSet<String> {
1043 let mut credited = template_visible_imports;
1044 if credit_load_data {
1049 credited.insert("data".to_string());
1050 if SVELTE_TEMPLATE_DATA_WHOLE_USE_RE.is_match(source) {
1053 combined.has_load_data_whole_use = true;
1054 }
1055 }
1056 if !combined.component_props.is_empty() {
1057 for prop in &combined.component_props {
1058 credited.insert(prop.name.clone());
1061 credited.insert(prop.local.clone());
1062 }
1063 credited.insert("$props".to_string());
1066 if let Some(binding) = props_return_binding {
1067 credited.insert(binding.to_string());
1068 }
1069 }
1070 credited
1071}
1072
1073fn compute_template_usage(
1078 kind: SfcKind,
1079 source: &str,
1080 credited: &FxHashSet<String>,
1081 mut template_visible_bound_targets: FxHashMap<String, String>,
1082 template_visible_iterable_types: &FxHashMap<String, String>,
1083 credit_load_data: bool,
1084) -> crate::template_usage::TemplateUsage {
1085 if credit_load_data {
1086 template_visible_bound_targets.remove("data");
1087 }
1088 collect_template_usage_with_bound_targets(
1089 kind,
1090 source,
1091 credited,
1092 &template_visible_bound_targets,
1093 template_visible_iterable_types,
1094 )
1095}
1096
1097fn apply_prop_template_credit(
1102 template_usage: &crate::template_usage::TemplateUsage,
1103 props_return_binding: Option<&str>,
1104 combined: &mut ModuleInfo,
1105) {
1106 if !combined.component_props.is_empty() {
1107 let member_used: FxHashSet<&str> = template_usage
1108 .member_accesses
1109 .iter()
1110 .filter(|access| {
1111 access.object == "$props"
1112 || props_return_binding.is_some_and(|binding| access.object == binding)
1113 })
1114 .map(|access| access.member.as_str())
1115 .collect();
1116 for prop in &mut combined.component_props {
1117 if template_usage.used_bindings.contains(&prop.name)
1118 || template_usage.used_bindings.contains(&prop.local)
1119 || member_used.contains(prop.name.as_str())
1120 {
1121 prop.used_in_template = true;
1122 }
1123 }
1124 }
1125
1126 if let Some(binding) = props_return_binding
1127 && (template_usage.used_bindings.contains(binding)
1128 || template_usage
1129 .whole_object_uses
1130 .iter()
1131 .any(|used| used == binding))
1132 {
1133 combined.has_props_attrs_fallthrough = true;
1134 }
1135}
1136
1137fn merge_template_usage_into_combined(
1142 template_usage: crate::template_usage::TemplateUsage,
1143 combined: &mut ModuleInfo,
1144) {
1145 combined
1146 .unused_import_bindings
1147 .retain(|binding| !template_usage.used_bindings.contains(binding));
1148 let mut member_accesses = std::mem::take(&mut combined.member_accesses).to_vec();
1149 member_accesses.extend(template_usage.member_accesses);
1150 combined.member_accesses = member_accesses.into();
1151 let mut whole_object_uses = std::mem::take(&mut combined.whole_object_uses).to_vec();
1152 whole_object_uses.extend(template_usage.whole_object_uses);
1153 combined.whole_object_uses = whole_object_uses.into();
1154 combined
1155 .security_sinks
1156 .extend(template_usage.security_sinks);
1157 if !template_usage.unresolved_tag_names.is_empty() {
1158 let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
1159 names.sort_unstable();
1160 combined.auto_import_candidates.extend(names);
1161 combined.auto_import_candidates.dedup();
1162 }
1163}
1164
1165fn apply_template_emit_usage(
1183 source: &str,
1184 emit_return_binding: Option<&str>,
1185 combined: &mut ModuleInfo,
1186) {
1187 let masked = mask_non_markup_regions(source);
1188 let mut used: FxHashSet<String> = FxHashSet::default();
1189 let mut dynamic = false;
1190
1191 for caps in TEMPLATE_EMIT_CALL_RE.captures_iter(&masked) {
1192 let Some(callee) = caps.get(1) else {
1193 continue;
1194 };
1195 let callee = callee.as_str();
1196 let is_emit_call =
1197 callee == "$emit" || emit_return_binding.is_some_and(|binding| callee == binding);
1198 if !is_emit_call {
1199 continue;
1200 }
1201 if let Some(event) = caps.get(2).or_else(|| caps.get(3)) {
1202 used.insert(event.as_str().to_string());
1205 } else if caps.get(4).is_some() {
1206 dynamic = true;
1209 }
1210 }
1211
1212 if dynamic {
1213 combined.has_dynamic_emit = true;
1214 }
1215 if !used.is_empty() {
1216 for emit in &mut combined.component_emits {
1217 if used.contains(&emit.name) {
1218 emit.used = true;
1219 }
1220 }
1221 }
1222}
1223
1224fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
1225 match kind {
1226 SfcKind::Vue => script.is_setup,
1227 SfcKind::Svelte => !script.is_context_module,
1228 }
1229}
1230
1231#[cfg(all(test, not(miri)))]
1232mod tests {
1233 use super::*;
1234 use fallow_types::extract::{
1235 ClassThisMemberAccessFact, ClassThisWholeObjectUseFact, SemanticFactView,
1236 };
1237
1238 #[test]
1239 fn merged_script_source_joins_inline_blocks_as_typescript() {
1240 let source = r#"<script>export const a = 1;</script>
1241<script setup lang="ts" generic="T extends Item">defineProps<{ a: T }>();</script>
1242<script src="./external.ts"></script>"#;
1243 let (merged, source_type) =
1244 sfc_merged_script_source(source).expect("inline scripts give a source");
1245 assert!(source_type.is_typescript());
1246 assert!(merged.contains("export const a = 1;"));
1247 assert!(merged.contains("defineProps<{ a: T }>();"));
1248 assert!(merged.contains("<T extends Item>"));
1249 assert!(!merged.contains("external"));
1250 }
1251
1252 #[test]
1253 fn merged_script_source_is_none_without_inline_script() {
1254 assert!(sfc_merged_script_source("<template><div /></template>").is_none());
1255 assert!(sfc_merged_script_source(r#"<script src="./a.ts"></script>"#).is_none());
1256 }
1257
1258 #[test]
1259 fn is_sfc_file_vue() {
1260 assert!(is_sfc_file(Path::new("App.vue")));
1261 }
1262
1263 #[test]
1264 fn is_sfc_file_svelte() {
1265 assert!(is_sfc_file(Path::new("Counter.svelte")));
1266 }
1267
1268 #[test]
1269 fn is_sfc_file_rejects_ts() {
1270 assert!(!is_sfc_file(Path::new("utils.ts")));
1271 }
1272
1273 #[test]
1274 fn is_sfc_file_rejects_jsx() {
1275 assert!(!is_sfc_file(Path::new("App.jsx")));
1276 }
1277
1278 #[test]
1279 fn is_sfc_file_rejects_astro() {
1280 assert!(!is_sfc_file(Path::new("Layout.astro")));
1281 }
1282
1283 #[test]
1284 fn single_plain_script() {
1285 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1286 assert_eq!(scripts.len(), 1);
1287 assert_eq!(scripts[0].body, "const x = 1;");
1288 assert!(!scripts[0].is_typescript);
1289 assert!(!scripts[0].is_jsx);
1290 assert!(scripts[0].src.is_none());
1291 }
1292
1293 #[test]
1294 fn single_ts_script() {
1295 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
1296 assert_eq!(scripts.len(), 1);
1297 assert!(scripts[0].is_typescript);
1298 assert!(!scripts[0].is_jsx);
1299 }
1300
1301 #[test]
1302 fn single_tsx_script() {
1303 let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
1304 assert_eq!(scripts.len(), 1);
1305 assert!(scripts[0].is_typescript);
1306 assert!(scripts[0].is_jsx);
1307 }
1308
1309 #[test]
1310 fn single_jsx_script() {
1311 let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
1312 assert_eq!(scripts.len(), 1);
1313 assert!(!scripts[0].is_typescript);
1314 assert!(scripts[0].is_jsx);
1315 }
1316
1317 #[test]
1318 fn two_script_blocks() {
1319 let source = r#"
1320<script lang="ts">
1321export default {};
1322</script>
1323<script setup lang="ts">
1324const count = 0;
1325</script>
1326"#;
1327 let scripts = extract_sfc_scripts(source);
1328 assert_eq!(scripts.len(), 2);
1329 assert!(scripts[0].body.contains("export default"));
1330 assert!(scripts[1].body.contains("count"));
1331 }
1332
1333 #[test]
1334 fn script_setup_extracted() {
1335 let scripts =
1336 extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
1337 assert_eq!(scripts.len(), 1);
1338 assert!(scripts[0].body.contains("import"));
1339 assert!(scripts[0].is_typescript);
1340 }
1341
1342 #[test]
1343 fn script_src_detected() {
1344 let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
1345 assert_eq!(scripts.len(), 1);
1346 assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
1347 }
1348
1349 #[test]
1352 fn svelte4_context_module_is_module_context() {
1353 let scripts =
1354 extract_sfc_scripts(r#"<script context="module">export const x = 1;</script>"#);
1355 assert_eq!(scripts.len(), 1);
1356 assert!(scripts[0].is_context_module);
1357 }
1358
1359 #[test]
1360 fn svelte5_bare_module_attr_is_module_context() {
1361 let scripts = extract_sfc_scripts(r"<script module>export const x = 1;</script>");
1362 assert_eq!(scripts.len(), 1);
1363 assert!(scripts[0].is_context_module);
1364 }
1365
1366 #[test]
1367 fn svelte5_module_with_lang_is_module_context() {
1368 let scripts =
1369 extract_sfc_scripts(r#"<script module lang="ts">export const x = 1;</script>"#);
1370 assert_eq!(scripts.len(), 1);
1371 assert!(scripts[0].is_context_module);
1372 assert!(scripts[0].is_typescript);
1373 }
1374
1375 #[test]
1376 fn plain_script_is_not_module_context() {
1377 let scripts = extract_sfc_scripts(r"<script>const x = 1;</script>");
1378 assert_eq!(scripts.len(), 1);
1379 assert!(!scripts[0].is_context_module);
1380 }
1381
1382 #[test]
1383 fn lang_ts_script_is_not_module_context() {
1384 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x = 1;</script>"#);
1385 assert_eq!(scripts.len(), 1);
1386 assert!(!scripts[0].is_context_module);
1387 }
1388
1389 #[test]
1390 fn data_module_attr_is_not_module_context() {
1391 let scripts =
1393 extract_sfc_scripts(r#"<script data-module="x" lang="ts">const x = 1;</script>"#);
1394 assert_eq!(scripts.len(), 1);
1395 assert!(!scripts[0].is_context_module);
1396 }
1397
1398 #[test]
1399 fn bare_module_script_is_not_template_visible() {
1400 let module_script = SfcScript {
1403 body: String::new(),
1404 is_typescript: false,
1405 is_jsx: false,
1406 byte_offset: 0,
1407 src: None,
1408 src_span: None,
1409 is_setup: false,
1410 is_context_module: true,
1411 generic_attr: None,
1412 };
1413 assert!(!is_template_visible_script(SfcKind::Svelte, &module_script));
1414 let instance_script = SfcScript {
1415 is_context_module: false,
1416 ..module_script
1417 };
1418 assert!(is_template_visible_script(
1419 SfcKind::Svelte,
1420 &instance_script
1421 ));
1422 }
1423
1424 #[test]
1425 fn data_src_not_treated_as_src() {
1426 let scripts =
1427 extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
1428 assert_eq!(scripts.len(), 1);
1429 assert!(scripts[0].src.is_none());
1430 }
1431
1432 #[test]
1433 fn script_inside_html_comment_filtered() {
1434 let source = r#"
1435<!-- <script lang="ts">import { bad } from 'bad';</script> -->
1436<script lang="ts">import { good } from 'good';</script>
1437"#;
1438 let scripts = extract_sfc_scripts(source);
1439 assert_eq!(scripts.len(), 1);
1440 assert!(scripts[0].body.contains("good"));
1441 }
1442
1443 #[test]
1444 fn spanning_comment_filters_script() {
1445 let source = r#"
1446<!-- disabled:
1447<script lang="ts">import { bad } from 'bad';</script>
1448-->
1449<script lang="ts">const ok = true;</script>
1450"#;
1451 let scripts = extract_sfc_scripts(source);
1452 assert_eq!(scripts.len(), 1);
1453 assert!(scripts[0].body.contains("ok"));
1454 }
1455
1456 #[test]
1457 fn string_containing_comment_markers_not_corrupted() {
1458 let source = r#"
1459<script setup lang="ts">
1460const marker = "<!-- not a comment -->";
1461import { ref } from 'vue';
1462</script>
1463"#;
1464 let scripts = extract_sfc_scripts(source);
1465 assert_eq!(scripts.len(), 1);
1466 assert!(scripts[0].body.contains("import"));
1467 }
1468
1469 #[test]
1470 fn generic_attr_with_angle_bracket() {
1471 let source =
1472 r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
1473 let scripts = extract_sfc_scripts(source);
1474 assert_eq!(scripts.len(), 1);
1475 assert_eq!(scripts[0].body, "const x = 1;");
1476 }
1477
1478 #[test]
1479 fn nested_generic_attr() {
1480 let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
1481 let scripts = extract_sfc_scripts(source);
1482 assert_eq!(scripts.len(), 1);
1483 assert_eq!(scripts[0].body, "const x = 1;");
1484 }
1485
1486 #[test]
1487 fn lang_single_quoted() {
1488 let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
1489 assert_eq!(scripts.len(), 1);
1490 assert!(scripts[0].is_typescript);
1491 }
1492
1493 #[test]
1494 fn uppercase_script_tag() {
1495 let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
1496 assert_eq!(scripts.len(), 1);
1497 assert!(scripts[0].is_typescript);
1498 }
1499
1500 #[test]
1501 fn no_script_block() {
1502 let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
1503 assert!(scripts.is_empty());
1504 }
1505
1506 #[test]
1507 fn empty_script_body() {
1508 let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
1509 assert_eq!(scripts.len(), 1);
1510 assert!(scripts[0].body.is_empty());
1511 }
1512
1513 #[test]
1514 fn whitespace_only_script() {
1515 let scripts = extract_sfc_scripts("<script lang=\"ts\">\n \n</script>");
1516 assert_eq!(scripts.len(), 1);
1517 assert!(scripts[0].body.trim().is_empty());
1518 }
1519
1520 #[test]
1521 fn byte_offset_is_set() {
1522 let source = r#"<template><div/></template><script lang="ts">code</script>"#;
1523 let scripts = extract_sfc_scripts(source);
1524 assert_eq!(scripts.len(), 1);
1525 let offset = scripts[0].byte_offset;
1526 assert_eq!(&source[offset..offset + 4], "code");
1527 }
1528
1529 #[test]
1530 fn script_with_extra_attributes() {
1531 let scripts = extract_sfc_scripts(
1532 r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
1533 );
1534 assert_eq!(scripts.len(), 1);
1535 assert!(scripts[0].is_typescript);
1536 assert!(scripts[0].src.is_none());
1537 }
1538
1539 #[test]
1540 fn multiple_script_blocks_exports_combined() {
1541 let source = r#"
1542<script lang="ts">
1543export const version = '1.0';
1544</script>
1545<script setup lang="ts">
1546import { ref } from 'vue';
1547const count = ref(0);
1548</script>
1549"#;
1550 let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
1551 assert!(
1552 info.exports
1553 .iter()
1554 .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
1555 "export from <script> block should be extracted"
1556 );
1557 assert!(
1558 info.imports.iter().any(|i| i.source == "vue"),
1559 "import from <script setup> block should be extracted"
1560 );
1561 }
1562
1563 #[test]
1564 fn class_this_facts_survive_sfc_script_merge() {
1565 let source = r#"
1566<script lang="ts">
1567export class Service {
1568 client!: Client;
1569
1570 run() {
1571 this.client.execute();
1572 Object.keys(this.client);
1573 }
1574}
1575</script>
1576"#;
1577 let info = parse_sfc_to_module(FileId(0), Path::new("Service.vue"), source, 0, false);
1578 let facts = SemanticFactView::new(&info.semantic_facts, &info.member_accesses);
1579
1580 assert_eq!(
1581 facts.class_this_member_accesses(),
1582 vec![ClassThisMemberAccessFact {
1583 class_local_name: "Service".to_string(),
1584 object: "this.client".to_string(),
1585 member: "execute".to_string(),
1586 }]
1587 );
1588 assert_eq!(
1589 facts.class_this_whole_object_uses(),
1590 vec![ClassThisWholeObjectUseFact {
1591 class_local_name: "Service".to_string(),
1592 object: "this.client".to_string(),
1593 }]
1594 );
1595 }
1596
1597 #[test]
1598 fn lang_tsx_detected_as_typescript_jsx() {
1599 let scripts =
1600 extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
1601 assert_eq!(scripts.len(), 1);
1602 assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
1603 assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
1604 }
1605
1606 #[test]
1607 fn multiline_html_comment_filters_all_script_blocks_inside() {
1608 let source = r#"
1609<!--
1610 This whole section is disabled:
1611 <script lang="ts">import { bad1 } from 'bad1';</script>
1612 <script lang="ts">import { bad2 } from 'bad2';</script>
1613-->
1614<script lang="ts">import { good } from 'good';</script>
1615"#;
1616 let scripts = extract_sfc_scripts(source);
1617 assert_eq!(scripts.len(), 1);
1618 assert!(scripts[0].body.contains("good"));
1619 }
1620
1621 #[test]
1622 fn script_src_generates_side_effect_import() {
1623 let info = parse_sfc_to_module(
1624 FileId(0),
1625 Path::new("External.vue"),
1626 r#"<script src="./external-logic.ts" lang="ts"></script>"#,
1627 0,
1628 false,
1629 );
1630 assert!(
1631 info.imports
1632 .iter()
1633 .any(|i| i.source == "./external-logic.ts"
1634 && matches!(i.imported_name, ImportedName::SideEffect)),
1635 "script src should generate a side-effect import"
1636 );
1637 }
1638
1639 #[test]
1640 fn parse_sfc_no_script_returns_empty_module() {
1641 let info = parse_sfc_to_module(
1642 FileId(0),
1643 Path::new("Empty.vue"),
1644 "<template><div>Hello</div></template>",
1645 42,
1646 false,
1647 );
1648 assert!(info.imports.is_empty());
1649 assert!(info.exports.is_empty());
1650 assert_eq!(info.content_hash, 42);
1651 assert_eq!(info.file_id, FileId(0));
1652 }
1653
1654 #[test]
1655 fn parse_sfc_has_line_offsets() {
1656 let info = parse_sfc_to_module(
1657 FileId(0),
1658 Path::new("LineOffsets.vue"),
1659 r#"<script lang="ts">const x = 1;</script>"#,
1660 0,
1661 false,
1662 );
1663 assert!(!info.line_offsets.is_empty());
1664 }
1665
1666 #[test]
1667 fn parse_sfc_has_suppressions() {
1668 let info = parse_sfc_to_module(
1669 FileId(0),
1670 Path::new("Suppressions.vue"),
1671 r#"<script lang="ts">
1672// fallow-ignore-file
1673export const foo = 1;
1674</script>"#,
1675 0,
1676 false,
1677 );
1678 assert!(!info.suppressions.is_empty());
1679 }
1680
1681 #[test]
1682 fn source_type_plain_js_detection() {
1683 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1684 assert_eq!(scripts.len(), 1);
1685 assert!(!scripts[0].is_typescript);
1686 assert!(!scripts[0].is_jsx);
1687 }
1688
1689 #[test]
1690 fn is_sfc_file_rejects_no_extension() {
1691 assert!(!is_sfc_file(Path::new("Makefile")));
1692 }
1693
1694 #[test]
1695 fn is_sfc_file_rejects_mdx() {
1696 assert!(!is_sfc_file(Path::new("post.mdx")));
1697 }
1698
1699 #[test]
1700 fn is_sfc_file_rejects_css() {
1701 assert!(!is_sfc_file(Path::new("styles.css")));
1702 }
1703
1704 #[test]
1705 fn multiple_script_blocks_both_have_offsets() {
1706 let source = r#"<script lang="ts">const a = 1;</script>
1707<script setup lang="ts">const b = 2;</script>"#;
1708 let scripts = extract_sfc_scripts(source);
1709 assert_eq!(scripts.len(), 2);
1710 let offset0 = scripts[0].byte_offset;
1711 let offset1 = scripts[1].byte_offset;
1712 assert_eq!(
1713 &source[offset0..offset0 + "const a = 1;".len()],
1714 "const a = 1;"
1715 );
1716 assert_eq!(
1717 &source[offset1..offset1 + "const b = 2;".len()],
1718 "const b = 2;"
1719 );
1720 }
1721
1722 #[test]
1723 fn script_with_src_and_lang() {
1724 let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
1725 assert_eq!(scripts.len(), 1);
1726 assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
1727 assert!(scripts[0].is_typescript);
1728 assert!(scripts[0].is_jsx);
1729 }
1730
1731 #[test]
1732 fn extract_style_block_lang_scss() {
1733 let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
1734 let styles = extract_sfc_styles(source);
1735 assert_eq!(styles.len(), 1);
1736 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1737 assert!(styles[0].body.contains("@import"));
1738 assert!(styles[0].src.is_none());
1739 }
1740
1741 #[test]
1742 fn extract_style_block_with_src() {
1743 let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
1744 let styles = extract_sfc_styles(source);
1745 assert_eq!(styles.len(), 1);
1746 assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
1747 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1748 }
1749
1750 #[test]
1751 fn extract_style_block_plain_no_lang() {
1752 let source = r"<style>.foo { color: red; }</style>";
1753 let styles = extract_sfc_styles(source);
1754 assert_eq!(styles.len(), 1);
1755 assert!(styles[0].lang.is_none());
1756 }
1757
1758 #[test]
1759 fn extract_multiple_style_blocks() {
1760 let source = r#"<style lang="scss">@import 'a';</style>
1761<style scoped lang="scss">@import 'b';</style>"#;
1762 let styles = extract_sfc_styles(source);
1763 assert_eq!(styles.len(), 2);
1764 }
1765
1766 #[test]
1767 fn style_block_inside_html_comment_filtered() {
1768 let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
1769<style lang="scss">@import 'good';</style>"#;
1770 let styles = extract_sfc_styles(source);
1771 assert_eq!(styles.len(), 1);
1772 assert!(styles[0].body.contains("good"));
1773 }
1774
1775 #[test]
1776 fn parse_sfc_extracts_style_imports_with_from_style_flag() {
1777 let info = parse_sfc_to_module(
1778 FileId(0),
1779 Path::new("Foo.vue"),
1780 r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1781 0,
1782 false,
1783 );
1784 let style_import = info
1785 .imports
1786 .iter()
1787 .find(|i| i.source == "./Foo")
1788 .expect("scss @import 'Foo' should be normalized to ./Foo");
1789 assert!(
1790 style_import.from_style,
1791 "imports from <style> blocks must carry from_style=true so the resolver \
1792 enables SCSS partial fallback for the SFC importer"
1793 );
1794 assert!(matches!(
1795 style_import.imported_name,
1796 ImportedName::SideEffect
1797 ));
1798 }
1799
1800 #[test]
1801 fn parse_sfc_extracts_style_plugin_as_default_import() {
1802 let info = parse_sfc_to_module(
1803 FileId(0),
1804 Path::new("Foo.vue"),
1805 r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1806 0,
1807 false,
1808 );
1809 let plugin_import = info
1810 .imports
1811 .iter()
1812 .find(|i| i.source == "./tailwind-plugin.js")
1813 .expect("style @plugin should create an import");
1814 assert!(plugin_import.from_style);
1815 assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1816 }
1817
1818 #[test]
1819 fn parse_sfc_extracts_style_src_with_from_style_flag() {
1820 let info = parse_sfc_to_module(
1821 FileId(0),
1822 Path::new("Bar.vue"),
1823 r#"<style src="./Bar.scss" lang="scss"></style>"#,
1824 0,
1825 false,
1826 );
1827 let style_src = info
1828 .imports
1829 .iter()
1830 .find(|i| i.source == "./Bar.scss")
1831 .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1832 assert!(style_src.from_style);
1833 }
1834
1835 #[test]
1836 fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1837 let info = parse_sfc_to_module(
1838 FileId(0),
1839 Path::new("Baz.vue"),
1840 r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1841 0,
1842 false,
1843 );
1844 assert!(
1845 info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1846 "src reference should still be seeded for unsupported lang"
1847 );
1848 assert!(
1849 !info.imports.iter().any(|i| i.source.contains("skipped")),
1850 "postcss body should not be scanned for @import directives"
1851 );
1852 }
1853
1854 fn asset_refs(source: &str) -> Vec<String> {
1855 super::collect_template_asset_refs(source)
1856 .into_iter()
1857 .map(|(s, _)| s)
1858 .collect()
1859 }
1860
1861 #[test]
1862 fn captures_static_relative_template_asset_refs() {
1863 assert_eq!(
1864 asset_refs(r#"<template><img src="./logo.png" /></template>"#),
1865 vec!["./logo.png".to_string()]
1866 );
1867 assert_eq!(
1868 asset_refs(r#"<source src="../media/clip.mp4">"#),
1869 vec!["../media/clip.mp4".to_string()]
1870 );
1871 assert_eq!(
1872 asset_refs(r#"<video poster="./thumb.jpg"></video>"#),
1873 vec!["./thumb.jpg".to_string()]
1874 );
1875 }
1876
1877 #[test]
1878 fn skips_dynamic_alias_root_remote_and_query_asset_refs() {
1879 assert!(asset_refs(r#"<img :src="logo" />"#).is_empty());
1881 assert!(asset_refs(r#"<img v-bind:src="logo" />"#).is_empty());
1882 assert!(asset_refs(r#"<img bind:src="logo" />"#).is_empty());
1883 assert!(asset_refs(r"<img src={logo} />").is_empty());
1884 assert!(asset_refs(r#"<img data-src="./x.png" />"#).is_empty());
1885 assert!(asset_refs(r#"<img src="@/assets/x.png" />"#).is_empty());
1887 assert!(asset_refs(r#"<img src="/logo.png" />"#).is_empty());
1888 assert!(asset_refs(r#"<img src="https://cdn/x.png" />"#).is_empty());
1889 assert!(asset_refs(r#"<img src="./x.png?inline" />"#).is_empty());
1891 assert!(asset_refs(r#"<img src="{{ logo }}" />"#).is_empty());
1893 }
1894
1895 #[test]
1896 fn skips_custom_component_src_prop() {
1897 assert!(asset_refs(r#"<MyImage src="./x.png" />"#).is_empty());
1899 assert!(asset_refs(r#"<AppIcon src="../icons/y.svg" />"#).is_empty());
1900 }
1901
1902 #[test]
1903 fn skips_asset_refs_inside_script_style_and_comments() {
1904 assert!(asset_refs(r#"<script>const x = "<img src='./a.png'>"</script>"#).is_empty());
1906 assert!(asset_refs(r#"<style>/* <img src="./b.png"> */ .x{}</style>"#).is_empty());
1907 assert!(asset_refs(r#"<!-- <img src="./c.png" /> -->"#).is_empty());
1908 }
1909
1910 #[test]
1911 fn parse_sfc_emits_template_asset_as_side_effect_import() {
1912 let info = parse_sfc_to_module(
1913 FileId(0),
1914 Path::new("Hero.vue"),
1915 r#"<template><img src="./hero.png" /></template><script>let x=1</script>"#,
1916 0,
1917 false,
1918 );
1919 assert!(
1920 info.imports.iter().any(|i| i.source == "./hero.png"
1921 && matches!(i.imported_name, ImportedName::SideEffect)
1922 && !i.from_style),
1923 "template <img src> should seed a SideEffect import: {:?}",
1924 info.imports
1925 );
1926 }
1927
1928 fn svelte_props(source: &str) -> Vec<crate::ModuleInfo> {
1931 vec![parse_sfc_to_module(
1932 FileId(0),
1933 Path::new("Component.svelte"),
1934 source,
1935 0,
1936 false,
1937 )]
1938 }
1939
1940 fn prop_names(info: &crate::ModuleInfo) -> Vec<String> {
1941 let mut names: Vec<String> = info
1942 .component_props
1943 .iter()
1944 .map(|p| p.name.clone())
1945 .collect();
1946 names.sort();
1947 names
1948 }
1949
1950 #[test]
1951 fn svelte_shorthand_props_harvested() {
1952 let info = &svelte_props(r"<script>let { a, b } = $props();</script>")[0];
1954 assert_eq!(prop_names(info), vec!["a", "b"]);
1955 for prop in &info.component_props {
1956 assert_eq!(prop.local, prop.name);
1957 }
1958 }
1959
1960 #[test]
1961 fn svelte_renamed_prop_tracks_local_and_script_use() {
1962 let info =
1965 &svelte_props(r"<script>let { a: alias } = $props(); console.log(alias);</script>")[0];
1966 assert_eq!(prop_names(info), vec!["a"]);
1967 let prop = &info.component_props[0];
1968 assert_eq!(prop.local, "alias");
1969 assert!(
1970 prop.used_in_script,
1971 "alias is referenced, so a is used in script"
1972 );
1973 }
1974
1975 #[test]
1976 fn svelte_unreferenced_prop_is_unused_in_script() {
1977 let info = &svelte_props(r"<script>let { a } = $props();</script>")[0];
1978 assert_eq!(prop_names(info), vec!["a"]);
1979 assert!(!info.component_props[0].used_in_script);
1980 }
1981
1982 #[test]
1983 fn svelte_default_prop_peeled() {
1984 let info = &svelte_props(r"<script>let { a = 1 } = $props();</script>")[0];
1986 assert_eq!(prop_names(info), vec!["a"]);
1987 }
1988
1989 #[test]
1990 fn svelte_bindable_default_peeled() {
1991 let info = &svelte_props(r"<script>let { a = $bindable() } = $props();</script>")[0];
1994 assert_eq!(prop_names(info), vec!["a"]);
1995 }
1996
1997 #[test]
1998 fn svelte_rest_element_sets_fallthrough_abstain() {
1999 let info = &svelte_props(r"<script>let { a, ...rest } = $props();</script>")[0];
2001 assert!(info.has_props_attrs_fallthrough);
2002 }
2003
2004 #[test]
2005 fn svelte_bare_identifier_binding_sets_unharvestable_abstain() {
2006 let info = &svelte_props(r"<script>let p = $props(); console.log(p.x);</script>")[0];
2008 assert!(info.has_unharvestable_props);
2009 assert!(info.component_props.is_empty());
2010 }
2011
2012 #[test]
2013 fn svelte_nested_destructure_sets_unharvestable_abstain() {
2014 let info = &svelte_props(r"<script>let { a: { x } } = $props();</script>")[0];
2016 assert!(info.has_unharvestable_props);
2017 }
2018
2019 #[test]
2020 fn svelte_prop_used_only_in_markup_credited_as_template_root() {
2021 let info = &svelte_props(r"<script>let { a } = $props();</script><p>{a}</p>")[0];
2024 assert_eq!(prop_names(info), vec!["a"]);
2025 assert!(
2026 info.component_props[0].used_in_template,
2027 "a is used in markup, so used_in_template should be true"
2028 );
2029 }
2030
2031 #[test]
2032 fn svelte_module_script_props_not_harvested() {
2033 let info = &svelte_props(
2035 r"<script module>let { a } = $props();</script><script>let { b } = $props();</script>",
2036 )[0];
2037 assert_eq!(prop_names(info), vec!["b"]);
2039 }
2040
2041 fn dispatched_names(info: &crate::ModuleInfo) -> Vec<String> {
2044 let mut names: Vec<String> = info
2045 .svelte_dispatched_events
2046 .iter()
2047 .map(|e| e.name.clone())
2048 .collect();
2049 names.sort();
2050 names
2051 }
2052
2053 #[test]
2054 fn svelte_dispatch_literal_event_is_harvested() {
2055 let info = &svelte_props(
2056 r"<script>import { createEventDispatcher } from 'svelte';
2057 const dispatch = createEventDispatcher();
2058 function save() { dispatch('save'); }</script>",
2059 )[0];
2060 assert_eq!(dispatched_names(info), vec!["save"]);
2061 assert!(!info.has_dynamic_dispatch);
2062 }
2063
2064 #[test]
2065 fn svelte_dispatch_without_svelte_import_is_ignored() {
2066 let info = &svelte_props(
2069 r"<script>function createEventDispatcher() { return () => {}; }
2070 const dispatch = createEventDispatcher();
2071 dispatch('save');</script>",
2072 )[0];
2073 assert!(info.svelte_dispatched_events.is_empty());
2074 }
2075
2076 #[test]
2077 fn svelte_dynamic_dispatch_sets_abstain() {
2078 let info = &svelte_props(
2079 r"<script>import { createEventDispatcher } from 'svelte';
2080 const dispatch = createEventDispatcher();
2081 function fire(name) { dispatch(name); }</script>",
2082 )[0];
2083 assert!(
2084 info.has_dynamic_dispatch,
2085 "a non-literal dispatch arg must set the abstain flag"
2086 );
2087 }
2088
2089 #[test]
2090 fn svelte_dispatch_whole_value_use_sets_abstain() {
2091 let info = &svelte_props(
2092 r"<script>import { createEventDispatcher } from 'svelte';
2093 const dispatch = createEventDispatcher();
2094 forward(dispatch);</script>",
2095 )[0];
2096 assert!(
2097 info.has_dynamic_dispatch,
2098 "passing the dispatch binding as a whole value must set the abstain flag"
2099 );
2100 }
2101
2102 #[test]
2103 fn svelte_listened_event_on_component_is_harvested() {
2104 let info =
2105 &svelte_props(r"<script>import Child from './Child.svelte';</script><Child on:save />")
2106 [0];
2107 assert!(info.svelte_listened_events.contains(&"save".to_string()));
2108 }
2109}
2110
2111fn apply_component_contracts(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
2112 let framework = match kind {
2113 SfcKind::Vue => fallow_types::extract::ComponentFramework::Vue,
2114 SfcKind::Svelte => fallow_types::extract::ComponentFramework::Svelte,
2115 };
2116 let callers = crate::sfc_template::component_contracts::collect(
2117 &mask_non_markup_regions(source),
2118 &combined.imports,
2119 framework,
2120 0,
2121 combined
2122 .component_contracts
2123 .as_deref()
2124 .map_or(&[], |facts| facts.spread_bindings.as_slice()),
2125 combined
2126 .component_contracts
2127 .as_deref()
2128 .map_or(&[], |facts| facts.aliases.as_slice()),
2129 );
2130 crate::component_contracts::merge(&mut combined.component_contracts, callers, 0, None);
2131 if let Some(facts) = &mut combined.component_contracts {
2132 let credited: FxHashSet<String> = facts
2133 .declarations
2134 .iter()
2135 .flat_map(|prop| [prop.local.clone(), prop.name.clone()])
2136 .collect();
2137 let usage = collect_template_usage_with_bound_targets(
2138 kind,
2139 source,
2140 &credited,
2141 &FxHashMap::default(),
2142 &FxHashMap::default(),
2143 );
2144 for declaration in &mut facts.declarations {
2145 declaration.is_used |= usage.used_bindings.contains(&declaration.local)
2146 || usage.member_accesses.iter().any(|access| {
2147 access.object == declaration.local && access.member == declaration.name
2148 });
2149 }
2150 }
2151 if let Some(facts) = &mut combined.component_contracts {
2152 for declaration in &mut facts.declarations {
2153 if let Some(prop) = combined
2154 .component_props
2155 .iter()
2156 .find(|prop| prop.name == declaration.name)
2157 {
2158 declaration.is_used |= prop.used_in_template;
2159 }
2160 declaration.incomplete |= combined.has_props_attrs_fallthrough
2161 || combined.has_define_expose
2162 || combined.has_define_model;
2163 }
2164 }
2165
2166 crate::component_contracts::attach_sfc_default_export(combined);
2167}