1use std::path::Path;
14use std::sync::LazyLock;
15
16use oxc_allocator::Allocator;
17use oxc_ast_visit::Visit;
18use oxc_parser::Parser;
19use oxc_span::SourceType;
20use rustc_hash::{FxHashMap, FxHashSet};
21
22use crate::asset_url::normalize_asset_url;
23use crate::parse::compute_import_binding_usage;
24use crate::sfc_blocks::{script_blocks, style_blocks};
25use crate::sfc_template::{SfcKind, collect_template_usage_with_bound_targets};
26use crate::source_map::ExtractionResult;
27use crate::visitor::ModuleInfoExtractor;
28use crate::{ImportInfo, ImportedName, ModuleInfo};
29use fallow_types::discover::FileId;
30use fallow_types::extract::{FunctionComplexity, byte_offset_to_line_col, compute_line_offsets};
31use oxc_span::Span;
32
33static LANG_ATTR_RE: LazyLock<regex::Regex> =
35 LazyLock::new(|| crate::static_regex(r#"lang\s*=\s*["'](\w+)["']"#));
36
37static SRC_ATTR_RE: LazyLock<regex::Regex> =
40 LazyLock::new(|| crate::static_regex(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#));
41
42static SETUP_ATTR_RE: LazyLock<regex::Regex> =
44 LazyLock::new(|| crate::static_regex(r"(?:^|\s)setup(?:\s|$)"));
45
46static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
48 LazyLock::new(|| crate::static_regex(r#"context\s*=\s*["']module["']"#));
49
50static SVELTE_MODULE_ATTR_RE: LazyLock<regex::Regex> =
55 LazyLock::new(|| crate::static_regex(r"(?:^|\s)module(?:\s|$|=)"));
56
57static VUE_GENERIC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
61 crate::static_regex(r#"(?:^|\s)generic\s*=\s*"([^"]*)"|(?:^|\s)generic\s*=\s*'([^']*)'"#)
62});
63
64static SVELTE_GENERICS_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
67 crate::static_regex(r#"(?:^|\s)generics\s*=\s*"([^"]*)"|(?:^|\s)generics\s*=\s*'([^']*)'"#)
68});
69
70static HTML_COMMENT_RE: LazyLock<regex::Regex> =
72 LazyLock::new(|| crate::static_regex(r"(?s)<!--.*?-->"));
73
74static PROPS_ATTRS_SPREAD_RE: LazyLock<regex::Regex> =
79 LazyLock::new(|| crate::static_regex(r#"v-bind\s*=\s*["'](?:\$attrs|\$props|props)["']"#));
80
81static TEMPLATE_ASSET_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
96 crate::static_regex(
97 r#"(?si)<(?:img|source|video|audio|track|embed)\b(?:[^>"']|"[^"]*"|'[^']*')*?\s(?:src|poster)\s*=\s*(?:"((?:\./|\.\./)[^"<>{}?#\s]*)"|'((?:\./|\.\./)[^'<>{}?#\s]*)')"#,
98 )
99});
100
101fn mask_non_markup_regions(source: &str) -> String {
105 let mut masked = source.to_string();
106 let spans: Vec<_> = script_blocks(&masked).into_iter().map(|b| b.span).collect();
107 mask_spans(&mut masked, spans);
108 let spans: Vec<_> = style_blocks(&masked).into_iter().map(|b| b.span).collect();
109 mask_spans(&mut masked, spans);
110 let spans: Vec<_> = HTML_COMMENT_RE
111 .find_iter(&masked)
112 .map(|m| m.range())
113 .collect();
114 mask_spans(&mut masked, spans);
115 masked
116}
117
118fn mask_spans(text: &mut String, spans: Vec<std::ops::Range<usize>>) {
120 for span in spans {
121 let len = span.len();
122 text.replace_range(span, &" ".repeat(len));
123 }
124}
125
126fn in_ranges(ranges: &[(usize, usize)], pos: usize) -> bool {
128 let index = ranges.partition_point(|&(_, end)| end <= pos);
129 ranges.get(index).is_some_and(|&(start, _)| start <= pos)
130}
131
132fn collect_template_asset_refs(source: &str) -> Vec<(String, Span)> {
135 let masked = mask_non_markup_regions(source);
136 let mut refs = Vec::new();
137 for caps in TEMPLATE_ASSET_RE.captures_iter(&masked) {
138 let Some(value) = caps.get(1).or_else(|| caps.get(2)) else {
139 continue;
140 };
141 let raw = value.as_str();
142 if raw.is_empty() {
143 continue;
144 }
145 refs.push((
146 normalize_asset_url(raw),
147 Span::new(value.start() as u32, value.end() as u32),
148 ));
149 }
150 refs
151}
152
153pub struct SfcScript {
155 pub body: String,
157 pub is_typescript: bool,
159 pub is_jsx: bool,
161 pub byte_offset: usize,
163 pub src: Option<String>,
165 pub src_span: Option<Span>,
167 pub is_setup: bool,
169 pub is_context_module: bool,
171 pub generic_attr: Option<String>,
175}
176
177pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
179 let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
180 .find_iter(source)
181 .map(|m| (m.start(), m.end()))
182 .collect();
183
184 script_blocks(source)
185 .into_iter()
186 .filter(|block| !in_ranges(&comment_ranges, block.span.start))
187 .map(|block| {
188 let attrs = &source[block.attrs.clone()];
189 let byte_offset = block.body.start;
190 let body = source[block.body].to_string();
191 let lang = LANG_ATTR_RE
192 .captures(attrs)
193 .and_then(|c| c.get(1))
194 .map(|m| m.as_str());
195 let is_typescript = matches!(lang, Some("ts" | "tsx"));
196 let is_jsx = matches!(lang, Some("tsx" | "jsx"));
197 let src = SRC_ATTR_RE
198 .captures(attrs)
199 .and_then(|c| c.get(1))
200 .map(|m| m.as_str().to_string());
201 let attrs_start = block.attrs.start;
202 let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
203 Span::new(
204 (attrs_start + m.start()) as u32,
205 (attrs_start + m.end()) as u32,
206 )
207 });
208 let is_setup = SETUP_ATTR_RE.is_match(attrs);
209 let is_context_module =
214 CONTEXT_MODULE_ATTR_RE.is_match(attrs) || SVELTE_MODULE_ATTR_RE.is_match(attrs);
215 let generic_attr = VUE_GENERIC_ATTR_RE
216 .captures(attrs)
217 .or_else(|| SVELTE_GENERICS_ATTR_RE.captures(attrs))
218 .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
219 .map(|m| m.as_str().to_string())
220 .filter(|value| !value.trim().is_empty());
221 SfcScript {
222 body,
223 is_typescript,
224 is_jsx,
225 byte_offset,
226 src,
227 src_span,
228 is_setup,
229 is_context_module,
230 generic_attr,
231 }
232 })
233 .collect()
234}
235
236pub struct SfcStyle {
238 pub body: String,
240 pub lang: Option<String>,
243 pub src: Option<String>,
245 pub src_span: Option<Span>,
247 pub byte_offset: usize,
249}
250
251pub struct SourceRegion {
254 pub body: String,
256 pub byte_offset: usize,
258}
259
260#[must_use]
266pub fn extract_sfc_template_regions(source: &str) -> Vec<SourceRegion> {
267 let mut ranges: Vec<(usize, usize)> = script_blocks(source)
268 .into_iter()
269 .chain(style_blocks(source))
270 .map(|block| block.span)
271 .chain(HTML_COMMENT_RE.find_iter(source).map(|m| m.range()))
272 .map(|span| (span.start, span.end))
273 .collect();
274 ranges.sort_unstable_by_key(|(start, _)| *start);
275 ranges_to_gaps(source, &ranges)
276}
277
278pub fn extract_sfc_styles(source: &str) -> Vec<SfcStyle> {
285 let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
286 .find_iter(source)
287 .map(|m| (m.start(), m.end()))
288 .collect();
289
290 style_blocks(source)
291 .into_iter()
292 .filter(|block| !in_ranges(&comment_ranges, block.span.start))
293 .map(|block| {
294 let attrs = &source[block.attrs.clone()];
295 let byte_offset = block.body.start;
296 let body = source[block.body].to_string();
297 let lang = LANG_ATTR_RE
298 .captures(attrs)
299 .and_then(|c| c.get(1))
300 .map(|m| m.as_str().to_string());
301 let src = SRC_ATTR_RE
302 .captures(attrs)
303 .and_then(|c| c.get(1))
304 .map(|m| m.as_str().to_string());
305 let attrs_start = block.attrs.start;
306 let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
307 Span::new(
308 (attrs_start + m.start()) as u32,
309 (attrs_start + m.end()) as u32,
310 )
311 });
312 SfcStyle {
313 body,
314 lang,
315 src,
316 src_span,
317 byte_offset,
318 }
319 })
320 .collect()
321}
322
323pub(crate) fn ranges_to_gaps(source: &str, ranges: &[(usize, usize)]) -> Vec<SourceRegion> {
327 let mut regions = Vec::new();
328 let mut cursor = 0;
329 for &(start, end) in ranges {
330 if start > cursor {
331 push_region(source, cursor, start, &mut regions);
332 }
333 cursor = cursor.max(end);
334 }
335 if cursor < source.len() {
336 push_region(source, cursor, source.len(), &mut regions);
337 }
338 regions
339}
340
341fn push_region(source: &str, start: usize, end: usize, regions: &mut Vec<SourceRegion>) {
342 let Some(body) = source.get(start..end) else {
343 return;
344 };
345 if body.trim().is_empty() {
346 return;
347 }
348 regions.push(SourceRegion {
349 body: body.to_string(),
350 byte_offset: start,
351 });
352}
353
354#[must_use]
356pub fn is_sfc_file(path: &Path) -> bool {
357 path.extension()
358 .and_then(|e| e.to_str())
359 .is_some_and(|ext| ext == "vue" || ext == "svelte")
360}
361
362#[cfg(test)]
364fn parse_sfc_to_module(
365 file_id: FileId,
366 path: &Path,
367 source: &str,
368 content_hash: u64,
369 need_complexity: bool,
370) -> ModuleInfo {
371 parse_sfc_to_module_with_mode(
372 file_id,
373 path,
374 source,
375 content_hash,
376 need_complexity,
377 crate::module_parse::ExtractionGates::STANDARD,
378 )
379}
380
381pub(crate) fn parse_sfc_to_module_with_mode(
382 file_id: FileId,
383 path: &Path,
384 source: &str,
385 content_hash: u64,
386 need_complexity: bool,
387 gates: crate::module_parse::ExtractionGates,
388) -> ModuleInfo {
389 let scripts = extract_sfc_scripts(source);
390 let styles = extract_sfc_styles(source);
391 let kind = sfc_kind(path);
392 let mut combined = empty_sfc_module(file_id, source, content_hash);
393 let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
394 let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
395 let mut template_visible_iterable_types: FxHashMap<String, String> = FxHashMap::default();
396 let mut props_return_binding: Option<String> = None;
397 let mut emit_return_binding: Option<String> = None;
398 let mut shared_scope_references = SharedScopeReferences::default();
399 let mut script_binding_context = crate::template_usage::ScriptBindingContext::default();
400 let has_setup_script = scripts.iter().any(|script| script.is_setup);
401
402 for script in &scripts {
403 merge_script_into_module(&mut SfcScriptMergeInput {
404 kind,
405 script,
406 has_setup_script,
407 combined: &mut combined,
408 shared_scope_references: &mut shared_scope_references,
409 template_visible_imports: &mut template_visible_imports,
410 template_visible_bound_targets: &mut template_visible_bound_targets,
411 template_visible_iterable_types: &mut template_visible_iterable_types,
412 props_return_binding: &mut props_return_binding,
413 emit_return_binding: &mut emit_return_binding,
414 script_binding_context: &mut script_binding_context,
415 need_complexity,
416 gates,
417 });
418 }
419 if scripts.len() > 1 {
420 credit_shared_scope_references(&shared_scope_references, &mut combined);
421 }
422
423 for style in &styles {
424 merge_style_into_module(style, &mut combined);
425 }
426
427 if kind == SfcKind::Vue
431 && !combined.component_props.is_empty()
432 && PROPS_ATTRS_SPREAD_RE.is_match(source)
433 {
434 combined.has_props_attrs_fallthrough = true;
435 }
436
437 if kind == SfcKind::Vue && !combined.component_emits.is_empty() {
440 combined.has_dynamic_emit |= crate::sfc_template::vue_template_is_not_html(source);
441 script_binding_context
442 .emit_bindings
443 .insert("$emit".to_string());
444 script_binding_context
445 .emit_bindings
446 .extend(emit_return_binding.iter().cloned());
447 }
448
449 apply_template_usage(TemplateUsageInput {
450 kind,
451 source,
452 script_binding_context,
453 template_visible_imports,
454 template_visible_bound_targets,
455 template_visible_iterable_types: &template_visible_iterable_types,
456 props_return_binding: props_return_binding.as_deref(),
457 credit_load_data: kind == SfcKind::Svelte && is_sveltekit_route_data_component(path),
458 combined: &mut combined,
459 });
460
461 if need_complexity {
462 append_template_complexity(kind, source, &mut combined);
463 }
464
465 if kind == SfcKind::Svelte {
470 combined.svelte_listened_events =
471 crate::sfc_template::collect_svelte_listened_events(source);
472 }
473
474 append_template_asset_imports(source, &mut combined);
475 dedup_import_binding_lists(&mut combined);
476 if gates.component_contracts {
477 apply_component_contracts(kind, source, &mut combined);
478 }
479
480 combined
481}
482
483fn append_template_complexity(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
491 match kind {
492 SfcKind::Vue => {
493 combined.complexity.extend(
494 crate::template_complexity::compute_vue_template_complexity(source),
495 );
496 }
497 SfcKind::Svelte => combined
500 .complexity
501 .extend(crate::template_complexity::compute_svelte_template_complexity(source)),
502 }
503}
504
505fn append_template_asset_imports(source: &str, combined: &mut ModuleInfo) {
509 for (specifier, span) in collect_template_asset_refs(source) {
510 combined.imports.push(ImportInfo {
511 source: specifier,
512 imported_name: ImportedName::SideEffect,
513 local_name: String::new(),
514 is_type_only: false,
515 is_type_only_star: false,
516 from_style: false,
517 span,
518 source_span: span,
519 });
520 }
521}
522
523fn dedup_import_binding_lists(combined: &mut ModuleInfo) {
526 combined.unused_import_bindings.sort_unstable();
527 combined.unused_import_bindings.dedup();
528 combined.type_referenced_import_bindings.sort_unstable();
529 combined.type_referenced_import_bindings.dedup();
530 combined.value_referenced_import_bindings.sort_unstable();
531 combined.value_referenced_import_bindings.dedup();
532 combined.auto_import_candidates.sort_unstable();
533 combined.auto_import_candidates.dedup();
534}
535
536fn sfc_kind(path: &Path) -> SfcKind {
537 if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
538 SfcKind::Vue
539 } else {
540 SfcKind::Svelte
541 }
542}
543
544fn is_sveltekit_route_data_component(path: &Path) -> bool {
555 let Some(stem) = path
556 .file_name()
557 .and_then(|name| name.to_str())
558 .and_then(|name| name.strip_suffix(".svelte"))
559 else {
560 return false;
561 };
562 ["+page", "+layout"].iter().any(|prefix| {
563 stem.strip_prefix(prefix)
564 .is_some_and(|rest| rest.is_empty() || rest.starts_with('@'))
565 })
566}
567
568fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
569 let parsed = crate::suppress_literals::parse_sfc_suppressions(source);
570
571 crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
572 file_id,
573 content_hash,
574 source,
575 parsed_suppressions: parsed,
576 imports: Vec::new(),
577 exports: Vec::new(),
578 })
579}
580
581#[path = "sfc_component_contracts.rs"]
582mod component_contracts_apply;
583#[path = "sfc_script_merge.rs"]
584mod script_merge;
585use component_contracts_apply::apply_component_contracts;
586pub(crate) use script_merge::translate_script_complexity;
587use script_merge::{
588 SfcScriptMergeInput, SharedScopeReferences, credit_shared_scope_references,
589 merge_script_into_module,
590};
591
592fn merge_script_binding_usage(
603 input: &mut SfcScriptMergeInput<'_>,
604 allocator: &Allocator,
605 imports: &[ImportInfo],
606 import_equals_bindings: &[String],
607 semantic_usage: crate::parse::SemanticUsage,
608) {
609 let augmented_body = build_generic_attr_probe_source(input.script);
610 let binding_usage = if let Some(augmented) = augmented_body.as_deref() {
611 let augmented_return =
612 Parser::new(allocator, augmented, source_type_for_script(input.script)).parse();
613 let mut probe = compute_import_binding_usage(
614 &augmented_return.program,
615 imports,
616 import_equals_bindings,
617 &FxHashSet::default(),
618 );
619 input
620 .shared_scope_references
621 .record_references(input.kind, &mut probe);
622 probe.import_binding_usage
623 } else {
624 semantic_usage.import_binding_usage
625 };
626 let auto_import_candidates = semantic_usage.auto_import_candidates;
627 crate::parse::append_declaration_merge_facts(
628 &mut input.combined.semantic_facts,
629 semantic_usage.declaration_merges,
630 input.script.byte_offset as u32,
631 );
632 input
633 .combined
634 .unused_import_bindings
635 .extend(binding_usage.unused.iter().cloned());
636 input
637 .combined
638 .type_referenced_import_bindings
639 .extend(binding_usage.type_referenced.iter().cloned());
640 input
641 .combined
642 .value_referenced_import_bindings
643 .extend(binding_usage.value_referenced.iter().cloned());
644 input
645 .combined
646 .auto_import_candidates
647 .extend(auto_import_candidates);
648}
649
650fn harvest_template_visible_bindings(
654 input: &mut SfcScriptMergeInput<'_>,
655 extractor: &ModuleInfoExtractor,
656) {
657 input.template_visible_imports.extend(
658 extractor
659 .imports
660 .iter()
661 .filter(|import| !import.local_name.is_empty())
662 .map(|import| import.local_name.clone()),
663 );
664 input.template_visible_bound_targets.extend(
665 extractor
666 .binding_target_names()
667 .iter()
668 .filter(|(local, _)| !local.starts_with("this."))
669 .filter_map(|(local, target)| {
670 target
671 .class_name()
672 .map(|class_name| (local.clone(), class_name.to_string()))
673 }),
674 );
675 input.template_visible_iterable_types.extend(
679 extractor
680 .array_binding_element_types()
681 .iter()
682 .filter(|(local, _)| !local.starts_with("this."))
683 .map(|(local, element)| (local.clone(), element.clone())),
684 );
685}
686
687fn merge_svelte_props_into(
691 combined: &mut ModuleInfo,
692 program: &oxc_ast::ast::Program<'_>,
693 byte_offset: usize,
694) {
695 let harvest = crate::sfc_props::harvest_svelte_props(program);
696 if harvest.has_unharvestable_props {
697 combined.has_unharvestable_props = true;
698 }
699 if harvest.has_props_attrs_fallthrough {
700 combined.has_props_attrs_fallthrough = true;
701 }
702 for mut prop in harvest.props {
703 prop.span_start += byte_offset as u32;
704 combined.component_props.push(prop);
705 }
706}
707
708fn merge_vue_props_emits_into(
715 input: &mut SfcScriptMergeInput<'_>,
716 program: &oxc_ast::ast::Program<'_>,
717 extractor: &mut ModuleInfoExtractor,
718) {
719 let byte_offset = input.script.byte_offset as u32;
720 if input.script.is_setup {
721 apply_props_harvest(
722 input,
723 crate::sfc_props::harvest_define_props(program),
724 byte_offset,
725 extractor,
726 );
727 apply_emits_harvest(
728 input,
729 crate::sfc_props::harvest_define_emits(program),
730 byte_offset,
731 );
732 } else {
733 apply_props_harvest(
734 input,
735 crate::sfc_props::harvest_options_api_props(program),
736 byte_offset,
737 extractor,
738 );
739 apply_emits_harvest(
740 input,
741 crate::sfc_props::harvest_options_api_emits(program),
742 byte_offset,
743 );
744 }
745}
746
747fn apply_props_harvest(
753 input: &mut SfcScriptMergeInput<'_>,
754 harvest: crate::sfc_props::DefinePropsHarvest,
755 byte_offset: u32,
756 extractor: &mut ModuleInfoExtractor,
757) {
758 if harvest.has_unharvestable_props {
759 input.combined.has_unharvestable_props = true;
760 }
761 if harvest.has_props_attrs_fallthrough {
762 input.combined.has_props_attrs_fallthrough = true;
763 }
764 if harvest.has_define_expose {
765 input.combined.has_define_expose = true;
766 }
767 if harvest.has_define_model {
768 input.combined.has_define_model = true;
769 }
770 if let Some(binding) = harvest.props_return_binding {
771 *input.props_return_binding = Some(binding);
772 }
773 for (field_name, element_type) in harvest.props_array_element_types {
781 extractor
782 .array_binding_element_types_mut()
783 .insert(format!("props.{field_name}"), element_type);
784 }
785 for mut prop in harvest.props {
786 prop.span_start += byte_offset;
787 input.combined.component_props.push(prop);
788 }
789}
790
791fn apply_emits_harvest(
797 input: &mut SfcScriptMergeInput<'_>,
798 harvest: crate::sfc_props::DefineEmitsHarvest,
799 byte_offset: u32,
800) {
801 if harvest.has_unharvestable_emits {
802 input.combined.has_unharvestable_emits = true;
803 }
804 if harvest.has_dynamic_emit {
805 input.combined.has_dynamic_emit = true;
806 }
807 if harvest.has_emit_whole_object_use {
808 input.combined.has_emit_whole_object_use = true;
809 }
810 if let Some(binding) = harvest.emit_binding {
811 *input.emit_return_binding = Some(binding);
812 }
813 for mut emit in harvest.emits {
814 emit.span_start += byte_offset;
815 input.combined.component_emits.push(emit);
816 }
817}
818
819fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
820 let span = source_span.unwrap_or_default();
821 module.imports.push(ImportInfo {
822 source: normalize_asset_url(source),
823 imported_name: ImportedName::SideEffect,
824 local_name: String::new(),
825 is_type_only: false,
826 is_type_only_star: false,
827 from_style: false,
828 span,
829 source_span: span,
830 });
831}
832
833fn style_lang_is_scss(lang: Option<&str>) -> bool {
839 matches!(lang, Some("scss" | "sass"))
840}
841
842fn style_lang_is_css_like(lang: Option<&str>) -> bool {
843 lang.is_none() || matches!(lang, Some("css"))
844}
845
846fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
847 if let Some(src) = &style.src {
848 let span = style.src_span.unwrap_or_default();
849 combined.imports.push(ImportInfo {
850 source: normalize_asset_url(src),
851 imported_name: ImportedName::SideEffect,
852 local_name: String::new(),
853 is_type_only: false,
854 is_type_only_star: false,
855 from_style: true,
856 span,
857 source_span: span,
858 });
859 }
860
861 let lang = style.lang.as_deref();
862 let is_scss = style_lang_is_scss(lang);
863 if !is_scss && !style_lang_is_css_like(lang) {
864 return;
865 }
866
867 let masked = crate::css_url::mask_style_block(&style.body, is_scss, combined);
868 for source in crate::css::import_sources_from_masked(&masked, is_scss) {
869 let source_span = Span::new(
870 style.byte_offset as u32 + source.span.start,
871 style.byte_offset as u32 + source.span.end,
872 );
873 combined.imports.push(ImportInfo {
874 source: source.normalized,
875 imported_name: if source.is_plugin {
876 ImportedName::Default
877 } else {
878 ImportedName::SideEffect
879 },
880 local_name: String::new(),
881 is_type_only: false,
882 is_type_only_star: false,
883 from_style: true,
884 span: source_span,
885 source_span,
886 });
887 }
888}
889
890pub(crate) fn source_type_for_script(script: &SfcScript) -> SourceType {
891 source_type_for(script.is_typescript, script.is_jsx)
892}
893
894fn source_type_for(is_typescript: bool, is_jsx: bool) -> SourceType {
895 match (is_typescript, is_jsx) {
896 (true, true) => SourceType::tsx(),
897 (true, false) => SourceType::ts(),
898 (false, true) => SourceType::jsx(),
899 (false, false) => SourceType::mjs(),
900 }
901}
902
903#[must_use]
913pub fn sfc_merged_script_source(source: &str) -> Option<(String, SourceType)> {
914 let scripts: Vec<SfcScript> = extract_sfc_scripts(source)
915 .into_iter()
916 .filter(|script| script.src.is_none())
917 .collect();
918 if scripts.is_empty() {
919 return None;
920 }
921 let is_typescript = scripts.iter().any(|script| script.is_typescript);
922 let is_jsx = scripts.iter().any(|script| script.is_jsx);
923 let mut merged = String::new();
924 for script in &scripts {
925 let body = build_generic_attr_probe_source(script);
926 merged.push_str(body.as_deref().unwrap_or(&script.body));
927 merged.push_str("\n;\n");
928 }
929 Some((merged, source_type_for(is_typescript, is_jsx)))
930}
931
932fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
938 let constraint = script.generic_attr.as_deref()?.trim();
939 if constraint.is_empty() {
940 return None;
941 }
942 Some(format!(
943 "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
944 script.body, constraint,
945 ))
946}
947
948struct TemplateUsageInput<'a> {
949 kind: SfcKind,
950 source: &'a str,
951 script_binding_context: crate::template_usage::ScriptBindingContext,
952 template_visible_imports: FxHashSet<String>,
953 template_visible_bound_targets: FxHashMap<String, String>,
954 template_visible_iterable_types: &'a FxHashMap<String, String>,
955 props_return_binding: Option<&'a str>,
956 credit_load_data: bool,
957 combined: &'a mut ModuleInfo,
958}
959
960fn apply_template_usage(input: TemplateUsageInput<'_>) {
961 let TemplateUsageInput {
962 kind,
963 source,
964 script_binding_context,
965 template_visible_imports,
966 template_visible_bound_targets,
967 template_visible_iterable_types,
968 props_return_binding,
969 credit_load_data,
970 combined,
971 } = input;
972 let credited = build_template_credited_set(
973 template_visible_imports,
974 props_return_binding,
975 credit_load_data,
976 combined,
977 );
978 let file_id = combined.file_id;
979 let seed = crate::template_usage::TemplateUsage::with_markup_sink(
980 script_binding_context,
981 std::mem::replace(combined, ModuleInfo::empty(file_id)),
982 );
983 let mut template_visible_bound_targets = template_visible_bound_targets;
984 if credit_load_data {
985 template_visible_bound_targets.remove("data");
986 }
987 let mut template_usage = compute_template_usage(
988 kind,
989 source,
990 &credited,
991 &template_visible_bound_targets,
992 template_visible_iterable_types,
993 seed,
994 );
995 let module = template_usage.take_markup_module();
996 debug_assert!(
997 module.is_some(),
998 "the template scan gives back the component module of its markup sink"
999 );
1000 if let Some(module) = module {
1001 *combined = module;
1002 }
1003 combined.has_load_data_whole_use |= credit_load_data && template_usage.uses_whole("data");
1007 apply_prop_template_credit(&template_usage, props_return_binding, combined);
1008 merge_template_usage_into_combined(template_usage, combined);
1009}
1010
1011fn build_template_credited_set(
1016 template_visible_imports: FxHashSet<String>,
1017 props_return_binding: Option<&str>,
1018 credit_load_data: bool,
1019 combined: &ModuleInfo,
1020) -> FxHashSet<String> {
1021 let mut credited = template_visible_imports;
1022 if credit_load_data {
1027 credited.insert("data".to_string());
1028 }
1029 if !combined.component_props.is_empty() {
1030 for prop in &combined.component_props {
1031 credited.insert(prop.name.clone());
1034 credited.insert(prop.local.clone());
1035 }
1036 credited.insert("$props".to_string());
1039 if let Some(binding) = props_return_binding {
1040 credited.insert(binding.to_string());
1041 }
1042 }
1043 credited
1044}
1045
1046fn compute_template_usage(
1052 kind: SfcKind,
1053 source: &str,
1054 credited: &FxHashSet<String>,
1055 template_visible_bound_targets: &FxHashMap<String, String>,
1056 template_visible_iterable_types: &FxHashMap<String, String>,
1057 seed: crate::template_usage::TemplateUsage,
1058) -> crate::template_usage::TemplateUsage {
1059 crate::sfc_template::collect_template_usage_seeded(
1060 kind,
1061 source,
1062 credited,
1063 template_visible_bound_targets,
1064 template_visible_iterable_types,
1065 seed,
1066 )
1067}
1068
1069fn apply_prop_template_credit(
1074 template_usage: &crate::template_usage::TemplateUsage,
1075 props_return_binding: Option<&str>,
1076 combined: &mut ModuleInfo,
1077) {
1078 if !combined.component_props.is_empty() {
1079 let member_used: FxHashSet<&str> = template_usage
1080 .member_accesses
1081 .iter()
1082 .filter(|access| {
1083 access.object == "$props"
1084 || props_return_binding.is_some_and(|binding| access.object == binding)
1085 })
1086 .map(|access| access.member.as_str())
1087 .collect();
1088 for prop in &mut combined.component_props {
1089 if template_usage.used_bindings.contains(&prop.name)
1090 || template_usage.used_bindings.contains(&prop.local)
1091 || member_used.contains(prop.name.as_str())
1092 {
1093 prop.used_in_template = true;
1094 }
1095 }
1096 }
1097
1098 if let Some(binding) = props_return_binding
1099 && (template_usage.used_bindings.contains(binding)
1100 || template_usage
1101 .whole_object_uses
1102 .iter()
1103 .any(|used| used == binding))
1104 {
1105 combined.has_props_attrs_fallthrough = true;
1106 }
1107}
1108
1109fn merge_template_usage_into_combined(
1114 template_usage: crate::template_usage::TemplateUsage,
1115 combined: &mut ModuleInfo,
1116) {
1117 combined
1118 .unused_import_bindings
1119 .retain(|binding| !template_usage.used_bindings.contains(binding));
1120 let mut member_accesses = std::mem::take(&mut combined.member_accesses).to_vec();
1121 member_accesses.extend(template_usage.member_accesses);
1122 combined.member_accesses = member_accesses.into();
1123 let mut whole_object_uses = std::mem::take(&mut combined.whole_object_uses).to_vec();
1124 whole_object_uses.extend(template_usage.whole_object_uses);
1125 combined.whole_object_uses = whole_object_uses.into();
1126 combined
1127 .security_sinks
1128 .extend(template_usage.security_sinks);
1129 if !template_usage.unresolved_tag_names.is_empty() {
1130 let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
1131 names.sort_unstable();
1132 combined.auto_import_candidates.extend(names);
1133 combined.auto_import_candidates.dedup();
1134 }
1135}
1136
1137fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
1138 match kind {
1139 SfcKind::Vue => script.is_setup,
1140 SfcKind::Svelte => !script.is_context_module,
1141 }
1142}
1143
1144#[cfg(all(test, not(miri)))]
1145mod tests {
1146 use super::*;
1147 use fallow_types::extract::{
1148 ClassThisMemberAccessFact, ClassThisWholeObjectUseFact, SemanticFactView,
1149 };
1150
1151 #[test]
1152 fn merged_script_source_joins_inline_blocks_as_typescript() {
1153 let source = r#"<script>export const a = 1;</script>
1154<script setup lang="ts" generic="T extends Item">defineProps<{ a: T }>();</script>
1155<script src="./external.ts"></script>"#;
1156 let (merged, source_type) =
1157 sfc_merged_script_source(source).expect("inline scripts give a source");
1158 assert!(source_type.is_typescript());
1159 assert!(merged.contains("export const a = 1;"));
1160 assert!(merged.contains("defineProps<{ a: T }>();"));
1161 assert!(merged.contains("<T extends Item>"));
1162 assert!(!merged.contains("external"));
1163 }
1164
1165 #[test]
1166 fn merged_script_source_is_none_without_inline_script() {
1167 assert!(sfc_merged_script_source("<template><div /></template>").is_none());
1168 assert!(sfc_merged_script_source(r#"<script src="./a.ts"></script>"#).is_none());
1169 }
1170
1171 #[test]
1172 fn is_sfc_file_vue() {
1173 assert!(is_sfc_file(Path::new("App.vue")));
1174 }
1175
1176 #[test]
1177 fn is_sfc_file_svelte() {
1178 assert!(is_sfc_file(Path::new("Counter.svelte")));
1179 }
1180
1181 #[test]
1182 fn is_sfc_file_rejects_ts() {
1183 assert!(!is_sfc_file(Path::new("utils.ts")));
1184 }
1185
1186 #[test]
1187 fn is_sfc_file_rejects_jsx() {
1188 assert!(!is_sfc_file(Path::new("App.jsx")));
1189 }
1190
1191 #[test]
1192 fn is_sfc_file_rejects_astro() {
1193 assert!(!is_sfc_file(Path::new("Layout.astro")));
1194 }
1195
1196 #[test]
1197 fn single_plain_script() {
1198 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1199 assert_eq!(scripts.len(), 1);
1200 assert_eq!(scripts[0].body, "const x = 1;");
1201 assert!(!scripts[0].is_typescript);
1202 assert!(!scripts[0].is_jsx);
1203 assert!(scripts[0].src.is_none());
1204 }
1205
1206 #[test]
1207 fn single_ts_script() {
1208 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
1209 assert_eq!(scripts.len(), 1);
1210 assert!(scripts[0].is_typescript);
1211 assert!(!scripts[0].is_jsx);
1212 }
1213
1214 #[test]
1215 fn single_tsx_script() {
1216 let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
1217 assert_eq!(scripts.len(), 1);
1218 assert!(scripts[0].is_typescript);
1219 assert!(scripts[0].is_jsx);
1220 }
1221
1222 #[test]
1223 fn single_jsx_script() {
1224 let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
1225 assert_eq!(scripts.len(), 1);
1226 assert!(!scripts[0].is_typescript);
1227 assert!(scripts[0].is_jsx);
1228 }
1229
1230 #[test]
1231 fn two_script_blocks() {
1232 let source = r#"
1233<script lang="ts">
1234export default {};
1235</script>
1236<script setup lang="ts">
1237const count = 0;
1238</script>
1239"#;
1240 let scripts = extract_sfc_scripts(source);
1241 assert_eq!(scripts.len(), 2);
1242 assert!(scripts[0].body.contains("export default"));
1243 assert!(scripts[1].body.contains("count"));
1244 }
1245
1246 #[test]
1247 fn script_setup_extracted() {
1248 let scripts =
1249 extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
1250 assert_eq!(scripts.len(), 1);
1251 assert!(scripts[0].body.contains("import"));
1252 assert!(scripts[0].is_typescript);
1253 }
1254
1255 #[test]
1256 fn script_src_detected() {
1257 let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
1258 assert_eq!(scripts.len(), 1);
1259 assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
1260 }
1261
1262 #[test]
1265 fn svelte4_context_module_is_module_context() {
1266 let scripts =
1267 extract_sfc_scripts(r#"<script context="module">export const x = 1;</script>"#);
1268 assert_eq!(scripts.len(), 1);
1269 assert!(scripts[0].is_context_module);
1270 }
1271
1272 #[test]
1273 fn svelte5_bare_module_attr_is_module_context() {
1274 let scripts = extract_sfc_scripts(r"<script module>export const x = 1;</script>");
1275 assert_eq!(scripts.len(), 1);
1276 assert!(scripts[0].is_context_module);
1277 }
1278
1279 #[test]
1280 fn svelte5_module_with_lang_is_module_context() {
1281 let scripts =
1282 extract_sfc_scripts(r#"<script module lang="ts">export const x = 1;</script>"#);
1283 assert_eq!(scripts.len(), 1);
1284 assert!(scripts[0].is_context_module);
1285 assert!(scripts[0].is_typescript);
1286 }
1287
1288 #[test]
1289 fn plain_script_is_not_module_context() {
1290 let scripts = extract_sfc_scripts(r"<script>const x = 1;</script>");
1291 assert_eq!(scripts.len(), 1);
1292 assert!(!scripts[0].is_context_module);
1293 }
1294
1295 #[test]
1296 fn lang_ts_script_is_not_module_context() {
1297 let scripts = extract_sfc_scripts(r#"<script lang="ts">const x = 1;</script>"#);
1298 assert_eq!(scripts.len(), 1);
1299 assert!(!scripts[0].is_context_module);
1300 }
1301
1302 #[test]
1303 fn data_module_attr_is_not_module_context() {
1304 let scripts =
1306 extract_sfc_scripts(r#"<script data-module="x" lang="ts">const x = 1;</script>"#);
1307 assert_eq!(scripts.len(), 1);
1308 assert!(!scripts[0].is_context_module);
1309 }
1310
1311 #[test]
1312 fn bare_module_script_is_not_template_visible() {
1313 let module_script = SfcScript {
1316 body: String::new(),
1317 is_typescript: false,
1318 is_jsx: false,
1319 byte_offset: 0,
1320 src: None,
1321 src_span: None,
1322 is_setup: false,
1323 is_context_module: true,
1324 generic_attr: None,
1325 };
1326 assert!(!is_template_visible_script(SfcKind::Svelte, &module_script));
1327 let instance_script = SfcScript {
1328 is_context_module: false,
1329 ..module_script
1330 };
1331 assert!(is_template_visible_script(
1332 SfcKind::Svelte,
1333 &instance_script
1334 ));
1335 }
1336
1337 #[test]
1338 fn data_src_not_treated_as_src() {
1339 let scripts =
1340 extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
1341 assert_eq!(scripts.len(), 1);
1342 assert!(scripts[0].src.is_none());
1343 }
1344
1345 #[test]
1346 fn script_inside_html_comment_filtered() {
1347 let source = r#"
1348<!-- <script lang="ts">import { bad } from 'bad';</script> -->
1349<script lang="ts">import { good } from 'good';</script>
1350"#;
1351 let scripts = extract_sfc_scripts(source);
1352 assert_eq!(scripts.len(), 1);
1353 assert!(scripts[0].body.contains("good"));
1354 }
1355
1356 #[test]
1357 fn spanning_comment_filters_script() {
1358 let source = r#"
1359<!-- disabled:
1360<script lang="ts">import { bad } from 'bad';</script>
1361-->
1362<script lang="ts">const ok = true;</script>
1363"#;
1364 let scripts = extract_sfc_scripts(source);
1365 assert_eq!(scripts.len(), 1);
1366 assert!(scripts[0].body.contains("ok"));
1367 }
1368
1369 #[test]
1370 fn string_containing_comment_markers_not_corrupted() {
1371 let source = r#"
1372<script setup lang="ts">
1373const marker = "<!-- not a comment -->";
1374import { ref } from 'vue';
1375</script>
1376"#;
1377 let scripts = extract_sfc_scripts(source);
1378 assert_eq!(scripts.len(), 1);
1379 assert!(scripts[0].body.contains("import"));
1380 }
1381
1382 #[test]
1383 fn generic_attr_with_angle_bracket() {
1384 let source =
1385 r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
1386 let scripts = extract_sfc_scripts(source);
1387 assert_eq!(scripts.len(), 1);
1388 assert_eq!(scripts[0].body, "const x = 1;");
1389 }
1390
1391 #[test]
1392 fn nested_generic_attr() {
1393 let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
1394 let scripts = extract_sfc_scripts(source);
1395 assert_eq!(scripts.len(), 1);
1396 assert_eq!(scripts[0].body, "const x = 1;");
1397 }
1398
1399 #[test]
1400 fn lang_single_quoted() {
1401 let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
1402 assert_eq!(scripts.len(), 1);
1403 assert!(scripts[0].is_typescript);
1404 }
1405
1406 #[test]
1407 fn uppercase_script_tag() {
1408 let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
1409 assert_eq!(scripts.len(), 1);
1410 assert!(scripts[0].is_typescript);
1411 }
1412
1413 #[test]
1414 fn no_script_block() {
1415 let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
1416 assert!(scripts.is_empty());
1417 }
1418
1419 #[test]
1420 fn empty_script_body() {
1421 let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
1422 assert_eq!(scripts.len(), 1);
1423 assert!(scripts[0].body.is_empty());
1424 }
1425
1426 #[test]
1427 fn whitespace_only_script() {
1428 let scripts = extract_sfc_scripts("<script lang=\"ts\">\n \n</script>");
1429 assert_eq!(scripts.len(), 1);
1430 assert!(scripts[0].body.trim().is_empty());
1431 }
1432
1433 #[test]
1434 fn byte_offset_is_set() {
1435 let source = r#"<template><div/></template><script lang="ts">code</script>"#;
1436 let scripts = extract_sfc_scripts(source);
1437 assert_eq!(scripts.len(), 1);
1438 let offset = scripts[0].byte_offset;
1439 assert_eq!(&source[offset..offset + 4], "code");
1440 }
1441
1442 #[test]
1443 fn script_with_extra_attributes() {
1444 let scripts = extract_sfc_scripts(
1445 r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
1446 );
1447 assert_eq!(scripts.len(), 1);
1448 assert!(scripts[0].is_typescript);
1449 assert!(scripts[0].src.is_none());
1450 }
1451
1452 #[test]
1453 fn multiple_script_blocks_exports_combined() {
1454 let source = r#"
1455<script lang="ts">
1456export const version = '1.0';
1457</script>
1458<script setup lang="ts">
1459import { ref } from 'vue';
1460const count = ref(0);
1461</script>
1462"#;
1463 let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
1464 assert!(
1465 info.exports
1466 .iter()
1467 .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
1468 "export from <script> block should be extracted"
1469 );
1470 assert!(
1471 info.imports.iter().any(|i| i.source == "vue"),
1472 "import from <script setup> block should be extracted"
1473 );
1474 }
1475
1476 #[test]
1477 fn class_this_facts_survive_sfc_script_merge() {
1478 let source = r#"
1479<script lang="ts">
1480export class Service {
1481 client!: Client;
1482
1483 run() {
1484 this.client.execute();
1485 Object.keys(this.client);
1486 }
1487}
1488</script>
1489"#;
1490 let info = parse_sfc_to_module(FileId(0), Path::new("Service.vue"), source, 0, false);
1491 let facts = SemanticFactView::new(&info.semantic_facts, &info.member_accesses);
1492
1493 assert_eq!(
1494 facts.class_this_member_accesses(),
1495 vec![ClassThisMemberAccessFact {
1496 class_local_name: "Service".to_string(),
1497 object: "this.client".to_string(),
1498 member: "execute".to_string(),
1499 }]
1500 );
1501 assert_eq!(
1502 facts.class_this_whole_object_uses(),
1503 vec![ClassThisWholeObjectUseFact {
1504 class_local_name: "Service".to_string(),
1505 object: "this.client".to_string(),
1506 }]
1507 );
1508 }
1509
1510 #[test]
1511 fn lang_tsx_detected_as_typescript_jsx() {
1512 let scripts =
1513 extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
1514 assert_eq!(scripts.len(), 1);
1515 assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
1516 assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
1517 }
1518
1519 #[test]
1520 fn multiline_html_comment_filters_all_script_blocks_inside() {
1521 let source = r#"
1522<!--
1523 This whole section is disabled:
1524 <script lang="ts">import { bad1 } from 'bad1';</script>
1525 <script lang="ts">import { bad2 } from 'bad2';</script>
1526-->
1527<script lang="ts">import { good } from 'good';</script>
1528"#;
1529 let scripts = extract_sfc_scripts(source);
1530 assert_eq!(scripts.len(), 1);
1531 assert!(scripts[0].body.contains("good"));
1532 }
1533
1534 #[test]
1535 fn script_src_generates_side_effect_import() {
1536 let info = parse_sfc_to_module(
1537 FileId(0),
1538 Path::new("External.vue"),
1539 r#"<script src="./external-logic.ts" lang="ts"></script>"#,
1540 0,
1541 false,
1542 );
1543 assert!(
1544 info.imports
1545 .iter()
1546 .any(|i| i.source == "./external-logic.ts"
1547 && matches!(i.imported_name, ImportedName::SideEffect)),
1548 "script src should generate a side-effect import"
1549 );
1550 }
1551
1552 #[test]
1553 fn parse_sfc_no_script_returns_empty_module() {
1554 let info = parse_sfc_to_module(
1555 FileId(0),
1556 Path::new("Empty.vue"),
1557 "<template><div>Hello</div></template>",
1558 42,
1559 false,
1560 );
1561 assert!(info.imports.is_empty());
1562 assert!(info.exports.is_empty());
1563 assert_eq!(info.content_hash, 42);
1564 assert_eq!(info.file_id, FileId(0));
1565 }
1566
1567 #[test]
1568 fn parse_sfc_has_line_offsets() {
1569 let info = parse_sfc_to_module(
1570 FileId(0),
1571 Path::new("LineOffsets.vue"),
1572 r#"<script lang="ts">const x = 1;</script>"#,
1573 0,
1574 false,
1575 );
1576 assert!(!info.line_offsets.is_empty());
1577 }
1578
1579 #[test]
1580 fn parse_sfc_has_suppressions() {
1581 let info = parse_sfc_to_module(
1582 FileId(0),
1583 Path::new("Suppressions.vue"),
1584 r#"<script lang="ts">
1585// fallow-ignore-file
1586export const foo = 1;
1587</script>"#,
1588 0,
1589 false,
1590 );
1591 assert!(!info.suppressions.is_empty());
1592 }
1593
1594 #[test]
1595 fn source_type_plain_js_detection() {
1596 let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1597 assert_eq!(scripts.len(), 1);
1598 assert!(!scripts[0].is_typescript);
1599 assert!(!scripts[0].is_jsx);
1600 }
1601
1602 #[test]
1603 fn is_sfc_file_rejects_no_extension() {
1604 assert!(!is_sfc_file(Path::new("Makefile")));
1605 }
1606
1607 #[test]
1608 fn is_sfc_file_rejects_mdx() {
1609 assert!(!is_sfc_file(Path::new("post.mdx")));
1610 }
1611
1612 #[test]
1613 fn is_sfc_file_rejects_css() {
1614 assert!(!is_sfc_file(Path::new("styles.css")));
1615 }
1616
1617 #[test]
1618 fn multiple_script_blocks_both_have_offsets() {
1619 let source = r#"<script lang="ts">const a = 1;</script>
1620<script setup lang="ts">const b = 2;</script>"#;
1621 let scripts = extract_sfc_scripts(source);
1622 assert_eq!(scripts.len(), 2);
1623 let offset0 = scripts[0].byte_offset;
1624 let offset1 = scripts[1].byte_offset;
1625 assert_eq!(
1626 &source[offset0..offset0 + "const a = 1;".len()],
1627 "const a = 1;"
1628 );
1629 assert_eq!(
1630 &source[offset1..offset1 + "const b = 2;".len()],
1631 "const b = 2;"
1632 );
1633 }
1634
1635 #[test]
1636 fn script_with_src_and_lang() {
1637 let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
1638 assert_eq!(scripts.len(), 1);
1639 assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
1640 assert!(scripts[0].is_typescript);
1641 assert!(scripts[0].is_jsx);
1642 }
1643
1644 #[test]
1645 fn extract_style_block_lang_scss() {
1646 let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
1647 let styles = extract_sfc_styles(source);
1648 assert_eq!(styles.len(), 1);
1649 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1650 assert!(styles[0].body.contains("@import"));
1651 assert!(styles[0].src.is_none());
1652 }
1653
1654 #[test]
1655 fn extract_style_block_with_src() {
1656 let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
1657 let styles = extract_sfc_styles(source);
1658 assert_eq!(styles.len(), 1);
1659 assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
1660 assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1661 }
1662
1663 #[test]
1664 fn extract_style_block_plain_no_lang() {
1665 let source = r"<style>.foo { color: red; }</style>";
1666 let styles = extract_sfc_styles(source);
1667 assert_eq!(styles.len(), 1);
1668 assert!(styles[0].lang.is_none());
1669 }
1670
1671 #[test]
1672 fn extract_multiple_style_blocks() {
1673 let source = r#"<style lang="scss">@import 'a';</style>
1674<style scoped lang="scss">@import 'b';</style>"#;
1675 let styles = extract_sfc_styles(source);
1676 assert_eq!(styles.len(), 2);
1677 }
1678
1679 #[test]
1680 fn style_block_inside_html_comment_filtered() {
1681 let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
1682<style lang="scss">@import 'good';</style>"#;
1683 let styles = extract_sfc_styles(source);
1684 assert_eq!(styles.len(), 1);
1685 assert!(styles[0].body.contains("good"));
1686 }
1687
1688 #[test]
1689 fn parse_sfc_extracts_style_imports_with_from_style_flag() {
1690 let info = parse_sfc_to_module(
1691 FileId(0),
1692 Path::new("Foo.vue"),
1693 r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1694 0,
1695 false,
1696 );
1697 let style_import = info
1698 .imports
1699 .iter()
1700 .find(|i| i.source == "./Foo")
1701 .expect("scss @import 'Foo' should be normalized to ./Foo");
1702 assert!(
1703 style_import.from_style,
1704 "imports from <style> blocks must carry from_style=true so the resolver \
1705 enables SCSS partial fallback for the SFC importer"
1706 );
1707 assert!(matches!(
1708 style_import.imported_name,
1709 ImportedName::SideEffect
1710 ));
1711 }
1712
1713 #[test]
1714 fn parse_sfc_extracts_style_plugin_as_default_import() {
1715 let info = parse_sfc_to_module(
1716 FileId(0),
1717 Path::new("Foo.vue"),
1718 r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1719 0,
1720 false,
1721 );
1722 let plugin_import = info
1723 .imports
1724 .iter()
1725 .find(|i| i.source == "./tailwind-plugin.js")
1726 .expect("style @plugin should create an import");
1727 assert!(plugin_import.from_style);
1728 assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1729 }
1730
1731 #[test]
1732 fn parse_sfc_extracts_style_src_with_from_style_flag() {
1733 let info = parse_sfc_to_module(
1734 FileId(0),
1735 Path::new("Bar.vue"),
1736 r#"<style src="./Bar.scss" lang="scss"></style>"#,
1737 0,
1738 false,
1739 );
1740 let style_src = info
1741 .imports
1742 .iter()
1743 .find(|i| i.source == "./Bar.scss")
1744 .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1745 assert!(style_src.from_style);
1746 }
1747
1748 #[test]
1749 fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1750 let info = parse_sfc_to_module(
1751 FileId(0),
1752 Path::new("Baz.vue"),
1753 r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1754 0,
1755 false,
1756 );
1757 assert!(
1758 info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1759 "src reference should still be seeded for unsupported lang"
1760 );
1761 assert!(
1762 !info.imports.iter().any(|i| i.source.contains("skipped")),
1763 "postcss body should not be scanned for @import directives"
1764 );
1765 }
1766
1767 fn asset_refs(source: &str) -> Vec<String> {
1768 super::collect_template_asset_refs(source)
1769 .into_iter()
1770 .map(|(s, _)| s)
1771 .collect()
1772 }
1773
1774 #[test]
1775 fn captures_static_relative_template_asset_refs() {
1776 assert_eq!(
1777 asset_refs(r#"<template><img src="./logo.png" /></template>"#),
1778 vec!["./logo.png".to_string()]
1779 );
1780 assert_eq!(
1781 asset_refs(r#"<source src="../media/clip.mp4">"#),
1782 vec!["../media/clip.mp4".to_string()]
1783 );
1784 assert_eq!(
1785 asset_refs(r#"<video poster="./thumb.jpg"></video>"#),
1786 vec!["./thumb.jpg".to_string()]
1787 );
1788 }
1789
1790 #[test]
1791 fn skips_dynamic_alias_root_remote_and_query_asset_refs() {
1792 assert!(asset_refs(r#"<img :src="logo" />"#).is_empty());
1794 assert!(asset_refs(r#"<img v-bind:src="logo" />"#).is_empty());
1795 assert!(asset_refs(r#"<img bind:src="logo" />"#).is_empty());
1796 assert!(asset_refs(r"<img src={logo} />").is_empty());
1797 assert!(asset_refs(r#"<img data-src="./x.png" />"#).is_empty());
1798 assert!(asset_refs(r#"<img src="@/assets/x.png" />"#).is_empty());
1800 assert!(asset_refs(r#"<img src="/logo.png" />"#).is_empty());
1801 assert!(asset_refs(r#"<img src="https://cdn/x.png" />"#).is_empty());
1802 assert!(asset_refs(r#"<img src="./x.png?inline" />"#).is_empty());
1804 assert!(asset_refs(r#"<img src="{{ logo }}" />"#).is_empty());
1806 }
1807
1808 #[test]
1809 fn skips_custom_component_src_prop() {
1810 assert!(asset_refs(r#"<MyImage src="./x.png" />"#).is_empty());
1812 assert!(asset_refs(r#"<AppIcon src="../icons/y.svg" />"#).is_empty());
1813 }
1814
1815 #[test]
1816 fn skips_asset_refs_inside_script_style_and_comments() {
1817 assert!(asset_refs(r#"<script>const x = "<img src='./a.png'>"</script>"#).is_empty());
1819 assert!(asset_refs(r#"<style>/* <img src="./b.png"> */ .x{}</style>"#).is_empty());
1820 assert!(asset_refs(r#"<!-- <img src="./c.png" /> -->"#).is_empty());
1821 }
1822
1823 #[test]
1824 fn parse_sfc_emits_template_asset_as_side_effect_import() {
1825 let info = parse_sfc_to_module(
1826 FileId(0),
1827 Path::new("Hero.vue"),
1828 r#"<template><img src="./hero.png" /></template><script>let x=1</script>"#,
1829 0,
1830 false,
1831 );
1832 assert!(
1833 info.imports.iter().any(|i| i.source == "./hero.png"
1834 && matches!(i.imported_name, ImportedName::SideEffect)
1835 && !i.from_style),
1836 "template <img src> should seed a SideEffect import: {:?}",
1837 info.imports
1838 );
1839 }
1840
1841 fn svelte_props(source: &str) -> Vec<crate::ModuleInfo> {
1844 vec![parse_sfc_to_module(
1845 FileId(0),
1846 Path::new("Component.svelte"),
1847 source,
1848 0,
1849 false,
1850 )]
1851 }
1852
1853 fn prop_names(info: &crate::ModuleInfo) -> Vec<String> {
1854 let mut names: Vec<String> = info
1855 .component_props
1856 .iter()
1857 .map(|p| p.name.clone())
1858 .collect();
1859 names.sort();
1860 names
1861 }
1862
1863 #[test]
1864 fn svelte_shorthand_props_harvested() {
1865 let info = &svelte_props(r"<script>let { a, b } = $props();</script>")[0];
1867 assert_eq!(prop_names(info), vec!["a", "b"]);
1868 for prop in &info.component_props {
1869 assert_eq!(prop.local, prop.name);
1870 }
1871 }
1872
1873 #[test]
1874 fn svelte_renamed_prop_tracks_local_and_script_use() {
1875 let info =
1878 &svelte_props(r"<script>let { a: alias } = $props(); console.log(alias);</script>")[0];
1879 assert_eq!(prop_names(info), vec!["a"]);
1880 let prop = &info.component_props[0];
1881 assert_eq!(prop.local, "alias");
1882 assert!(
1883 prop.used_in_script,
1884 "alias is referenced, so a is used in script"
1885 );
1886 }
1887
1888 #[test]
1889 fn svelte_unreferenced_prop_is_unused_in_script() {
1890 let info = &svelte_props(r"<script>let { a } = $props();</script>")[0];
1891 assert_eq!(prop_names(info), vec!["a"]);
1892 assert!(!info.component_props[0].used_in_script);
1893 }
1894
1895 #[test]
1896 fn svelte_default_prop_peeled() {
1897 let info = &svelte_props(r"<script>let { a = 1 } = $props();</script>")[0];
1899 assert_eq!(prop_names(info), vec!["a"]);
1900 }
1901
1902 #[test]
1903 fn svelte_bindable_default_peeled() {
1904 let info = &svelte_props(r"<script>let { a = $bindable() } = $props();</script>")[0];
1907 assert_eq!(prop_names(info), vec!["a"]);
1908 }
1909
1910 #[test]
1911 fn svelte_rest_element_sets_fallthrough_abstain() {
1912 let info = &svelte_props(r"<script>let { a, ...rest } = $props();</script>")[0];
1914 assert!(info.has_props_attrs_fallthrough);
1915 }
1916
1917 #[test]
1918 fn svelte_bare_identifier_binding_sets_unharvestable_abstain() {
1919 let info = &svelte_props(r"<script>let p = $props(); console.log(p.x);</script>")[0];
1921 assert!(info.has_unharvestable_props);
1922 assert!(info.component_props.is_empty());
1923 }
1924
1925 #[test]
1926 fn svelte_nested_destructure_sets_unharvestable_abstain() {
1927 let info = &svelte_props(r"<script>let { a: { x } } = $props();</script>")[0];
1929 assert!(info.has_unharvestable_props);
1930 }
1931
1932 #[test]
1933 fn svelte_prop_used_only_in_markup_credited_as_template_root() {
1934 let info = &svelte_props(r"<script>let { a } = $props();</script><p>{a}</p>")[0];
1937 assert_eq!(prop_names(info), vec!["a"]);
1938 assert!(
1939 info.component_props[0].used_in_template,
1940 "a is used in markup, so used_in_template should be true"
1941 );
1942 }
1943
1944 #[test]
1945 fn svelte_module_script_props_not_harvested() {
1946 let info = &svelte_props(
1948 r"<script module>let { a } = $props();</script><script>let { b } = $props();</script>",
1949 )[0];
1950 assert_eq!(prop_names(info), vec!["b"]);
1952 }
1953
1954 fn dispatched_names(info: &crate::ModuleInfo) -> Vec<String> {
1957 let mut names: Vec<String> = info
1958 .svelte_dispatched_events
1959 .iter()
1960 .map(|e| e.name.clone())
1961 .collect();
1962 names.sort();
1963 names
1964 }
1965
1966 #[test]
1967 fn svelte_dispatch_literal_event_is_harvested() {
1968 let info = &svelte_props(
1969 r"<script>import { createEventDispatcher } from 'svelte';
1970 const dispatch = createEventDispatcher();
1971 function save() { dispatch('save'); }</script>",
1972 )[0];
1973 assert_eq!(dispatched_names(info), vec!["save"]);
1974 assert!(!info.has_dynamic_dispatch);
1975 }
1976
1977 #[test]
1978 fn svelte_dispatch_without_svelte_import_is_ignored() {
1979 let info = &svelte_props(
1982 r"<script>function createEventDispatcher() { return () => {}; }
1983 const dispatch = createEventDispatcher();
1984 dispatch('save');</script>",
1985 )[0];
1986 assert!(info.svelte_dispatched_events.is_empty());
1987 }
1988
1989 #[test]
1990 fn svelte_dynamic_dispatch_sets_abstain() {
1991 let info = &svelte_props(
1992 r"<script>import { createEventDispatcher } from 'svelte';
1993 const dispatch = createEventDispatcher();
1994 function fire(name) { dispatch(name); }</script>",
1995 )[0];
1996 assert!(
1997 info.has_dynamic_dispatch,
1998 "a non-literal dispatch arg must set the abstain flag"
1999 );
2000 }
2001
2002 #[test]
2003 fn svelte_dispatch_whole_value_use_sets_abstain() {
2004 let info = &svelte_props(
2005 r"<script>import { createEventDispatcher } from 'svelte';
2006 const dispatch = createEventDispatcher();
2007 forward(dispatch);</script>",
2008 )[0];
2009 assert!(
2010 info.has_dynamic_dispatch,
2011 "passing the dispatch binding as a whole value must set the abstain flag"
2012 );
2013 }
2014
2015 #[test]
2016 fn svelte_listened_event_on_component_is_harvested() {
2017 let info =
2018 &svelte_props(r"<script>import Child from './Child.svelte';</script><Child on:save />")
2019 [0];
2020 assert!(info.svelte_listened_events.contains(&"save".to_string()));
2021 }
2022}