Skip to main content

fallow_extract/
sfc.rs

1//! Vue/Svelte Single File Component (SFC) script and style extraction.
2//!
3//! Extracts `<script>` block content from `.vue` and `.svelte` files using regex,
4//! handling `lang`, `src` metadata, and `generic` attributes, and filtering
5//! HTML comments. Vue external script references are emitted as graph edges;
6//! Svelte markup-level script `src` references are treated as runtime HTML.
7//! Also extracts `<style>` block sources (`@import` / `@use` / `@forward` /
8//! `@plugin` and `<style src="...">`) so referenced CSS / SCSS files become
9//! reachable from the component, preventing false `unused-files` reports on
10//! co-located styles.
11
12use 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::{
23    compute_auto_import_candidates, compute_import_binding_usage, compute_semantic_usage,
24};
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
33/// Regex to extract `<script>` block content from Vue/Svelte SFCs.
34/// The attrs pattern handles `>` inside quoted attribute values (e.g., `generic="T extends Foo<Bar>"`).
35static SCRIPT_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
36    crate::static_regex(
37        r#"(?is)<script\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</script>"#,
38    )
39});
40
41/// Regex to extract the `lang` attribute value from a script tag.
42static LANG_ATTR_RE: LazyLock<regex::Regex> =
43    LazyLock::new(|| crate::static_regex(r#"lang\s*=\s*["'](\w+)["']"#));
44
45/// Regex to extract the `src` attribute value from a script tag.
46/// Requires whitespace (or start of string) before `src` to avoid matching `data-src` etc.
47static SRC_ATTR_RE: LazyLock<regex::Regex> =
48    LazyLock::new(|| crate::static_regex(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#));
49
50/// Regex to detect Vue's bare `setup` attribute.
51static SETUP_ATTR_RE: LazyLock<regex::Regex> =
52    LazyLock::new(|| crate::static_regex(r"(?:^|\s)setup(?:\s|$)"));
53
54/// Regex to detect Svelte's `context="module"` attribute.
55static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
56    LazyLock::new(|| crate::static_regex(r#"context\s*=\s*["']module["']"#));
57
58/// Regex to extract Vue's `generic="..."` attribute value (script-setup
59/// generics). Matches the contents between the quotes and stops at the
60/// closing quote, mirroring `LANG_ATTR_RE`.
61static VUE_GENERIC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
62    crate::static_regex(r#"(?:^|\s)generic\s*=\s*"([^"]*)"|(?:^|\s)generic\s*=\s*'([^']*)'"#)
63});
64
65/// Regex to extract Svelte's `generics="..."` attribute value (Svelte 4
66/// generic script attribute, repurposed by some Svelte 5 code).
67static SVELTE_GENERICS_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
68    crate::static_regex(r#"(?:^|\s)generics\s*=\s*"([^"]*)"|(?:^|\s)generics\s*=\s*'([^']*)'"#)
69});
70
71/// Regex to match HTML comments for filtering script blocks inside comments.
72static HTML_COMMENT_RE: LazyLock<regex::Regex> =
73    LazyLock::new(|| crate::static_regex(r"(?s)<!--.*?-->"));
74
75/// Regex to extract `<style>` block content from Vue/Svelte SFCs.
76/// Mirrors `SCRIPT_BLOCK_RE`: handles `>` inside quoted attribute values and
77/// captures the body so `@import` / `@use` / `@forward` directives can be parsed.
78static STYLE_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
79    crate::static_regex(
80        r#"(?is)<style\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</style>"#,
81    )
82});
83
84/// An extracted `<script>` block from a Vue or Svelte SFC.
85pub struct SfcScript {
86    /// The script body text.
87    pub body: String,
88    /// Whether the script uses TypeScript (`lang="ts"` or `lang="tsx"`).
89    pub is_typescript: bool,
90    /// Whether the script uses JSX syntax (`lang="tsx"` or `lang="jsx"`).
91    pub is_jsx: bool,
92    /// Byte offset of the script body within the full SFC source.
93    pub byte_offset: usize,
94    /// External script source path from `src` attribute.
95    pub src: Option<String>,
96    /// Span of the `src` attribute value in the full SFC source.
97    pub src_span: Option<Span>,
98    /// Whether this script is a Vue `<script setup>` block.
99    pub is_setup: bool,
100    /// Whether this script is a Svelte module-context block.
101    pub is_context_module: bool,
102    /// Type-parameter list from a `generic="..."` (Vue) or `generics="..."`
103    /// (Svelte) attribute on the script tag. Holds the bare constraint, no
104    /// surrounding angle brackets, e.g. `T extends Test<boolean>`.
105    pub generic_attr: Option<String>,
106}
107
108/// Extract all `<script>` blocks from a Vue/Svelte SFC source string.
109pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
110    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
111        .find_iter(source)
112        .map(|m| (m.start(), m.end()))
113        .collect();
114
115    SCRIPT_BLOCK_RE
116        .captures_iter(source)
117        .filter(|cap| {
118            let start = cap.get(0).map_or(0, |m| m.start());
119            !comment_ranges
120                .iter()
121                .any(|&(cs, ce)| start >= cs && start < ce)
122        })
123        .map(|cap| {
124            let attrs = cap.name("attrs").map_or("", |m| m.as_str());
125            let body_match = cap.name("body");
126            let byte_offset = body_match.map_or(0, |m| m.start());
127            let body = body_match.map_or("", |m| m.as_str()).to_string();
128            let lang = LANG_ATTR_RE
129                .captures(attrs)
130                .and_then(|c| c.get(1))
131                .map(|m| m.as_str());
132            let is_typescript = matches!(lang, Some("ts" | "tsx"));
133            let is_jsx = matches!(lang, Some("tsx" | "jsx"));
134            let src = SRC_ATTR_RE
135                .captures(attrs)
136                .and_then(|c| c.get(1))
137                .map(|m| m.as_str().to_string());
138            let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
139            let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
140                Span::new(
141                    (attrs_start + m.start()) as u32,
142                    (attrs_start + m.end()) as u32,
143                )
144            });
145            let is_setup = SETUP_ATTR_RE.is_match(attrs);
146            let is_context_module = CONTEXT_MODULE_ATTR_RE.is_match(attrs);
147            let generic_attr = VUE_GENERIC_ATTR_RE
148                .captures(attrs)
149                .or_else(|| SVELTE_GENERICS_ATTR_RE.captures(attrs))
150                .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
151                .map(|m| m.as_str().to_string())
152                .filter(|value| !value.trim().is_empty());
153            SfcScript {
154                body,
155                is_typescript,
156                is_jsx,
157                byte_offset,
158                src,
159                src_span,
160                is_setup,
161                is_context_module,
162                generic_attr,
163            }
164        })
165        .collect()
166}
167
168/// An extracted `<style>` block from a Vue or Svelte SFC.
169pub struct SfcStyle {
170    /// The style body text (CSS / SCSS / Sass / Less / Stylus / PostCSS source).
171    pub body: String,
172    /// The `lang` attribute value (`scss`, `sass`, `less`, `stylus`, `postcss`, ...).
173    /// `None` for plain `<style>` (CSS).
174    pub lang: Option<String>,
175    /// External style source path from the `src` attribute (`<style src="./theme.scss">`).
176    pub src: Option<String>,
177    /// Span of the `src` attribute value in the full SFC source.
178    pub src_span: Option<Span>,
179    /// Byte offset of the style body within the full SFC source.
180    pub byte_offset: usize,
181}
182
183/// Extract all `<style>` blocks from a Vue/Svelte SFC source string.
184///
185/// Mirrors [`extract_sfc_scripts`]: filters blocks inside HTML comments and
186/// captures the `lang` and `src` attributes so the caller can route the body to
187/// the right preprocessor's import scanner (currently only CSS / SCSS / Sass) or
188/// seed the `src` reference as a side-effect import.
189pub fn extract_sfc_styles(source: &str) -> Vec<SfcStyle> {
190    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
191        .find_iter(source)
192        .map(|m| (m.start(), m.end()))
193        .collect();
194
195    STYLE_BLOCK_RE
196        .captures_iter(source)
197        .filter(|cap| {
198            let start = cap.get(0).map_or(0, |m| m.start());
199            !comment_ranges
200                .iter()
201                .any(|&(cs, ce)| start >= cs && start < ce)
202        })
203        .map(|cap| {
204            let attrs = cap.name("attrs").map_or("", |m| m.as_str());
205            let body = cap.name("body").map_or("", |m| m.as_str()).to_string();
206            let byte_offset = cap.name("body").map_or(0, |m| m.start());
207            let lang = LANG_ATTR_RE
208                .captures(attrs)
209                .and_then(|c| c.get(1))
210                .map(|m| m.as_str().to_string());
211            let src = SRC_ATTR_RE
212                .captures(attrs)
213                .and_then(|c| c.get(1))
214                .map(|m| m.as_str().to_string());
215            let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
216            let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
217                Span::new(
218                    (attrs_start + m.start()) as u32,
219                    (attrs_start + m.end()) as u32,
220                )
221            });
222            SfcStyle {
223                body,
224                lang,
225                src,
226                src_span,
227                byte_offset,
228            }
229        })
230        .collect()
231}
232
233/// Check if a file path is a Vue or Svelte SFC (`.vue` or `.svelte`).
234#[must_use]
235pub fn is_sfc_file(path: &Path) -> bool {
236    path.extension()
237        .and_then(|e| e.to_str())
238        .is_some_and(|ext| ext == "vue" || ext == "svelte")
239}
240
241/// Parse an SFC file by extracting and combining all `<script>` and `<style>` blocks.
242pub(crate) fn parse_sfc_to_module(
243    file_id: FileId,
244    path: &Path,
245    source: &str,
246    content_hash: u64,
247    need_complexity: bool,
248) -> ModuleInfo {
249    let scripts = extract_sfc_scripts(source);
250    let styles = extract_sfc_styles(source);
251    let kind = sfc_kind(path);
252    let mut combined = empty_sfc_module(file_id, source, content_hash);
253    let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
254    let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
255
256    for script in &scripts {
257        merge_script_into_module(
258            kind,
259            script,
260            &mut combined,
261            &mut template_visible_imports,
262            &mut template_visible_bound_targets,
263            need_complexity,
264        );
265    }
266
267    for style in &styles {
268        merge_style_into_module(style, &mut combined);
269    }
270
271    apply_template_usage(
272        kind,
273        source,
274        &template_visible_imports,
275        &template_visible_bound_targets,
276        &mut combined,
277    );
278    combined.unused_import_bindings.sort_unstable();
279    combined.unused_import_bindings.dedup();
280    combined.type_referenced_import_bindings.sort_unstable();
281    combined.type_referenced_import_bindings.dedup();
282    combined.value_referenced_import_bindings.sort_unstable();
283    combined.value_referenced_import_bindings.dedup();
284    combined.auto_import_candidates.sort_unstable();
285    combined.auto_import_candidates.dedup();
286
287    combined
288}
289
290fn sfc_kind(path: &Path) -> SfcKind {
291    if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
292        SfcKind::Vue
293    } else {
294        SfcKind::Svelte
295    }
296}
297
298fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
299    let parsed = crate::suppress::parse_suppressions_from_source(source);
300
301    ModuleInfo {
302        file_id,
303        exports: Vec::new(),
304        imports: Vec::new(),
305        re_exports: Vec::new(),
306        dynamic_imports: Vec::new(),
307        dynamic_import_patterns: Vec::new(),
308        require_calls: Vec::new(),
309        member_accesses: Vec::new(),
310        whole_object_uses: Vec::new(),
311        has_cjs_exports: false,
312        has_angular_component_template_url: false,
313        content_hash,
314        suppressions: parsed.suppressions,
315        unknown_suppression_kinds: parsed.unknown_kinds,
316        unused_import_bindings: Vec::new(),
317        type_referenced_import_bindings: Vec::new(),
318        value_referenced_import_bindings: Vec::new(),
319        line_offsets: compute_line_offsets(source),
320        complexity: Vec::new(),
321        flag_uses: Vec::new(),
322        class_heritage: vec![],
323        injection_tokens: vec![],
324        local_type_declarations: Vec::new(),
325        public_signature_type_references: Vec::new(),
326        namespace_object_aliases: Vec::new(),
327        iconify_prefixes: Vec::new(),
328        auto_import_candidates: Vec::new(),
329        directives: Vec::new(),
330        security_sinks: Vec::new(),
331        security_sinks_skipped: 0,
332        tainted_bindings: Vec::new(),
333        sanitized_sink_args: Vec::new(),
334    }
335}
336
337fn merge_script_into_module(
338    kind: SfcKind,
339    script: &SfcScript,
340    combined: &mut ModuleInfo,
341    template_visible_imports: &mut FxHashSet<String>,
342    template_visible_bound_targets: &mut FxHashMap<String, String>,
343    need_complexity: bool,
344) {
345    if kind == SfcKind::Vue
346        && let Some(src) = &script.src
347    {
348        add_script_src_import(combined, src, script.src_span);
349    }
350
351    let allocator = Allocator::default();
352    let parser_return =
353        Parser::new(&allocator, &script.body, source_type_for_script(script)).parse();
354    let mut extractor = ModuleInfoExtractor::new();
355    extractor.visit_program(&parser_return.program);
356    let extraction = ExtractionResult::contiguous(&script.body, script.byte_offset);
357    extractor.remap_spans_with(|span| extraction.remap_span(span));
358    extractor.resolve_typed_destructure_bindings();
359
360    let augmented_body = build_generic_attr_probe_source(script);
361    let empty_template_used = rustc_hash::FxHashSet::default();
362    let (binding_usage, auto_import_candidates) = if let Some(augmented) = augmented_body.as_deref()
363    {
364        let augmented_return =
365            Parser::new(&allocator, augmented, source_type_for_script(script)).parse();
366        (
367            compute_import_binding_usage(
368                &augmented_return.program,
369                &extractor.imports,
370                &empty_template_used,
371            ),
372            compute_auto_import_candidates(&parser_return.program),
373        )
374    } else {
375        let semantic_usage = compute_semantic_usage(
376            &parser_return.program,
377            &extractor.imports,
378            &empty_template_used,
379        );
380        (
381            semantic_usage.import_binding_usage,
382            semantic_usage.auto_import_candidates,
383        )
384    };
385    combined
386        .unused_import_bindings
387        .extend(binding_usage.unused.iter().cloned());
388    combined
389        .type_referenced_import_bindings
390        .extend(binding_usage.type_referenced.iter().cloned());
391    combined
392        .value_referenced_import_bindings
393        .extend(binding_usage.value_referenced.iter().cloned());
394    combined
395        .auto_import_candidates
396        .extend(auto_import_candidates);
397    if need_complexity {
398        combined.complexity.extend(translate_script_complexity(
399            script,
400            &parser_return.program,
401            &combined.line_offsets,
402        ));
403    }
404
405    if is_template_visible_script(kind, script) {
406        template_visible_imports.extend(
407            extractor
408                .imports
409                .iter()
410                .filter(|import| !import.local_name.is_empty())
411                .map(|import| import.local_name.clone()),
412        );
413        template_visible_bound_targets.extend(
414            extractor
415                .binding_target_names()
416                .iter()
417                .filter(|(local, _)| !local.starts_with("this."))
418                .map(|(local, target)| (local.clone(), target.clone())),
419        );
420    }
421
422    extractor.merge_into(combined);
423}
424
425fn translate_script_complexity(
426    script: &SfcScript,
427    program: &oxc_ast::ast::Program<'_>,
428    sfc_line_offsets: &[u32],
429) -> Vec<FunctionComplexity> {
430    let script_line_offsets = compute_line_offsets(&script.body);
431    let mut complexity =
432        crate::complexity::compute_complexity(program, &script.body, &script_line_offsets);
433    let (body_start_line, body_start_col) =
434        byte_offset_to_line_col(sfc_line_offsets, script.byte_offset as u32);
435
436    for function in &mut complexity {
437        function.line = body_start_line + function.line.saturating_sub(1);
438        if function.line == body_start_line {
439            function.col += body_start_col;
440        }
441    }
442
443    complexity
444}
445
446fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
447    let span = source_span.unwrap_or_default();
448    module.imports.push(ImportInfo {
449        source: normalize_asset_url(source),
450        imported_name: ImportedName::SideEffect,
451        local_name: String::new(),
452        is_type_only: false,
453        from_style: false,
454        span,
455        source_span: span,
456    });
457}
458
459/// `lang` attribute values whose body we know how to scan for `@import` /
460/// `@use` / `@forward` / `@plugin` directives. Plain `<style>` (no `lang`) is treated as
461/// CSS. `less`, `stylus`, and `postcss` bodies are NOT scanned because their
462/// import syntax differs (`@import (reference)` modifiers, etc.); their
463/// `<style src="...">` references are still seeded.
464fn style_lang_is_scss(lang: Option<&str>) -> bool {
465    matches!(lang, Some("scss" | "sass"))
466}
467
468fn style_lang_is_css_like(lang: Option<&str>) -> bool {
469    lang.is_none() || matches!(lang, Some("css"))
470}
471
472fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
473    if let Some(src) = &style.src {
474        let span = style.src_span.unwrap_or_default();
475        combined.imports.push(ImportInfo {
476            source: normalize_asset_url(src),
477            imported_name: ImportedName::SideEffect,
478            local_name: String::new(),
479            is_type_only: false,
480            from_style: true,
481            span,
482            source_span: span,
483        });
484    }
485
486    let lang = style.lang.as_deref();
487    let is_scss = style_lang_is_scss(lang);
488    let is_css_like = style_lang_is_css_like(lang);
489    if !is_scss && !is_css_like {
490        return;
491    }
492
493    for source in crate::css::extract_css_import_sources(&style.body, is_scss) {
494        let source_span = Span::new(
495            style.byte_offset as u32 + source.span.start,
496            style.byte_offset as u32 + source.span.end,
497        );
498        combined.imports.push(ImportInfo {
499            source: source.normalized,
500            imported_name: if source.is_plugin {
501                ImportedName::Default
502            } else {
503                ImportedName::SideEffect
504            },
505            local_name: String::new(),
506            is_type_only: false,
507            from_style: true,
508            span: source_span,
509            source_span,
510        });
511    }
512}
513
514fn source_type_for_script(script: &SfcScript) -> SourceType {
515    match (script.is_typescript, script.is_jsx) {
516        (true, true) => SourceType::tsx(),
517        (true, false) => SourceType::ts(),
518        (false, true) => SourceType::jsx(),
519        (false, false) => SourceType::mjs(),
520    }
521}
522
523/// Build an augmented script body that pins the `generic="..."` constraint as
524/// a synthetic local type alias. The alias is unexported and uses a sentinel
525/// name so it can't collide with user code. Returns `None` when there is no
526/// generic attribute to pin (the common case), so callers fall back to the
527/// raw body without paying for a second parse.
528fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
529    let constraint = script.generic_attr.as_deref()?.trim();
530    if constraint.is_empty() {
531        return None;
532    }
533    Some(format!(
534        "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
535        script.body, constraint,
536    ))
537}
538
539fn apply_template_usage(
540    kind: SfcKind,
541    source: &str,
542    template_visible_imports: &FxHashSet<String>,
543    template_visible_bound_targets: &FxHashMap<String, String>,
544    combined: &mut ModuleInfo,
545) {
546    let template_usage = collect_template_usage_with_bound_targets(
547        kind,
548        source,
549        template_visible_imports,
550        template_visible_bound_targets,
551    );
552    combined
553        .unused_import_bindings
554        .retain(|binding| !template_usage.used_bindings.contains(binding));
555    combined
556        .member_accesses
557        .extend(template_usage.member_accesses);
558    combined
559        .whole_object_uses
560        .extend(template_usage.whole_object_uses);
561    if !template_usage.unresolved_tag_names.is_empty() {
562        let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
563        names.sort_unstable();
564        combined.auto_import_candidates.extend(names);
565        combined.auto_import_candidates.dedup();
566    }
567}
568
569fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
570    match kind {
571        SfcKind::Vue => script.is_setup,
572        SfcKind::Svelte => !script.is_context_module,
573    }
574}
575
576#[cfg(all(test, not(miri)))]
577mod tests {
578    use super::*;
579
580    #[test]
581    fn is_sfc_file_vue() {
582        assert!(is_sfc_file(Path::new("App.vue")));
583    }
584
585    #[test]
586    fn is_sfc_file_svelte() {
587        assert!(is_sfc_file(Path::new("Counter.svelte")));
588    }
589
590    #[test]
591    fn is_sfc_file_rejects_ts() {
592        assert!(!is_sfc_file(Path::new("utils.ts")));
593    }
594
595    #[test]
596    fn is_sfc_file_rejects_jsx() {
597        assert!(!is_sfc_file(Path::new("App.jsx")));
598    }
599
600    #[test]
601    fn is_sfc_file_rejects_astro() {
602        assert!(!is_sfc_file(Path::new("Layout.astro")));
603    }
604
605    #[test]
606    fn single_plain_script() {
607        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
608        assert_eq!(scripts.len(), 1);
609        assert_eq!(scripts[0].body, "const x = 1;");
610        assert!(!scripts[0].is_typescript);
611        assert!(!scripts[0].is_jsx);
612        assert!(scripts[0].src.is_none());
613    }
614
615    #[test]
616    fn single_ts_script() {
617        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
618        assert_eq!(scripts.len(), 1);
619        assert!(scripts[0].is_typescript);
620        assert!(!scripts[0].is_jsx);
621    }
622
623    #[test]
624    fn single_tsx_script() {
625        let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
626        assert_eq!(scripts.len(), 1);
627        assert!(scripts[0].is_typescript);
628        assert!(scripts[0].is_jsx);
629    }
630
631    #[test]
632    fn single_jsx_script() {
633        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
634        assert_eq!(scripts.len(), 1);
635        assert!(!scripts[0].is_typescript);
636        assert!(scripts[0].is_jsx);
637    }
638
639    #[test]
640    fn two_script_blocks() {
641        let source = r#"
642<script lang="ts">
643export default {};
644</script>
645<script setup lang="ts">
646const count = 0;
647</script>
648"#;
649        let scripts = extract_sfc_scripts(source);
650        assert_eq!(scripts.len(), 2);
651        assert!(scripts[0].body.contains("export default"));
652        assert!(scripts[1].body.contains("count"));
653    }
654
655    #[test]
656    fn script_setup_extracted() {
657        let scripts =
658            extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
659        assert_eq!(scripts.len(), 1);
660        assert!(scripts[0].body.contains("import"));
661        assert!(scripts[0].is_typescript);
662    }
663
664    #[test]
665    fn script_src_detected() {
666        let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
667        assert_eq!(scripts.len(), 1);
668        assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
669    }
670
671    #[test]
672    fn data_src_not_treated_as_src() {
673        let scripts =
674            extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
675        assert_eq!(scripts.len(), 1);
676        assert!(scripts[0].src.is_none());
677    }
678
679    #[test]
680    fn script_inside_html_comment_filtered() {
681        let source = r#"
682<!-- <script lang="ts">import { bad } from 'bad';</script> -->
683<script lang="ts">import { good } from 'good';</script>
684"#;
685        let scripts = extract_sfc_scripts(source);
686        assert_eq!(scripts.len(), 1);
687        assert!(scripts[0].body.contains("good"));
688    }
689
690    #[test]
691    fn spanning_comment_filters_script() {
692        let source = r#"
693<!-- disabled:
694<script lang="ts">import { bad } from 'bad';</script>
695-->
696<script lang="ts">const ok = true;</script>
697"#;
698        let scripts = extract_sfc_scripts(source);
699        assert_eq!(scripts.len(), 1);
700        assert!(scripts[0].body.contains("ok"));
701    }
702
703    #[test]
704    fn string_containing_comment_markers_not_corrupted() {
705        let source = r#"
706<script setup lang="ts">
707const marker = "<!-- not a comment -->";
708import { ref } from 'vue';
709</script>
710"#;
711        let scripts = extract_sfc_scripts(source);
712        assert_eq!(scripts.len(), 1);
713        assert!(scripts[0].body.contains("import"));
714    }
715
716    #[test]
717    fn generic_attr_with_angle_bracket() {
718        let source =
719            r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
720        let scripts = extract_sfc_scripts(source);
721        assert_eq!(scripts.len(), 1);
722        assert_eq!(scripts[0].body, "const x = 1;");
723    }
724
725    #[test]
726    fn nested_generic_attr() {
727        let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
728        let scripts = extract_sfc_scripts(source);
729        assert_eq!(scripts.len(), 1);
730        assert_eq!(scripts[0].body, "const x = 1;");
731    }
732
733    #[test]
734    fn lang_single_quoted() {
735        let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
736        assert_eq!(scripts.len(), 1);
737        assert!(scripts[0].is_typescript);
738    }
739
740    #[test]
741    fn uppercase_script_tag() {
742        let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
743        assert_eq!(scripts.len(), 1);
744        assert!(scripts[0].is_typescript);
745    }
746
747    #[test]
748    fn no_script_block() {
749        let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
750        assert!(scripts.is_empty());
751    }
752
753    #[test]
754    fn empty_script_body() {
755        let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
756        assert_eq!(scripts.len(), 1);
757        assert!(scripts[0].body.is_empty());
758    }
759
760    #[test]
761    fn whitespace_only_script() {
762        let scripts = extract_sfc_scripts("<script lang=\"ts\">\n  \n</script>");
763        assert_eq!(scripts.len(), 1);
764        assert!(scripts[0].body.trim().is_empty());
765    }
766
767    #[test]
768    fn byte_offset_is_set() {
769        let source = r#"<template><div/></template><script lang="ts">code</script>"#;
770        let scripts = extract_sfc_scripts(source);
771        assert_eq!(scripts.len(), 1);
772        let offset = scripts[0].byte_offset;
773        assert_eq!(&source[offset..offset + 4], "code");
774    }
775
776    #[test]
777    fn script_with_extra_attributes() {
778        let scripts = extract_sfc_scripts(
779            r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
780        );
781        assert_eq!(scripts.len(), 1);
782        assert!(scripts[0].is_typescript);
783        assert!(scripts[0].src.is_none());
784    }
785
786    #[test]
787    fn multiple_script_blocks_exports_combined() {
788        let source = r#"
789<script lang="ts">
790export const version = '1.0';
791</script>
792<script setup lang="ts">
793import { ref } from 'vue';
794const count = ref(0);
795</script>
796"#;
797        let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
798        assert!(
799            info.exports
800                .iter()
801                .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
802            "export from <script> block should be extracted"
803        );
804        assert!(
805            info.imports.iter().any(|i| i.source == "vue"),
806            "import from <script setup> block should be extracted"
807        );
808    }
809
810    #[test]
811    fn lang_tsx_detected_as_typescript_jsx() {
812        let scripts =
813            extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
814        assert_eq!(scripts.len(), 1);
815        assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
816        assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
817    }
818
819    #[test]
820    fn multiline_html_comment_filters_all_script_blocks_inside() {
821        let source = r#"
822<!--
823  This whole section is disabled:
824  <script lang="ts">import { bad1 } from 'bad1';</script>
825  <script lang="ts">import { bad2 } from 'bad2';</script>
826-->
827<script lang="ts">import { good } from 'good';</script>
828"#;
829        let scripts = extract_sfc_scripts(source);
830        assert_eq!(scripts.len(), 1);
831        assert!(scripts[0].body.contains("good"));
832    }
833
834    #[test]
835    fn script_src_generates_side_effect_import() {
836        let info = parse_sfc_to_module(
837            FileId(0),
838            Path::new("External.vue"),
839            r#"<script src="./external-logic.ts" lang="ts"></script>"#,
840            0,
841            false,
842        );
843        assert!(
844            info.imports
845                .iter()
846                .any(|i| i.source == "./external-logic.ts"
847                    && matches!(i.imported_name, ImportedName::SideEffect)),
848            "script src should generate a side-effect import"
849        );
850    }
851
852    #[test]
853    fn parse_sfc_no_script_returns_empty_module() {
854        let info = parse_sfc_to_module(
855            FileId(0),
856            Path::new("Empty.vue"),
857            "<template><div>Hello</div></template>",
858            42,
859            false,
860        );
861        assert!(info.imports.is_empty());
862        assert!(info.exports.is_empty());
863        assert_eq!(info.content_hash, 42);
864        assert_eq!(info.file_id, FileId(0));
865    }
866
867    #[test]
868    fn parse_sfc_has_line_offsets() {
869        let info = parse_sfc_to_module(
870            FileId(0),
871            Path::new("LineOffsets.vue"),
872            r#"<script lang="ts">const x = 1;</script>"#,
873            0,
874            false,
875        );
876        assert!(!info.line_offsets.is_empty());
877    }
878
879    #[test]
880    fn parse_sfc_has_suppressions() {
881        let info = parse_sfc_to_module(
882            FileId(0),
883            Path::new("Suppressions.vue"),
884            r#"<script lang="ts">
885// fallow-ignore-file
886export const foo = 1;
887</script>"#,
888            0,
889            false,
890        );
891        assert!(!info.suppressions.is_empty());
892    }
893
894    #[test]
895    fn source_type_jsx_detection() {
896        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
897        assert_eq!(scripts.len(), 1);
898        assert!(!scripts[0].is_typescript);
899        assert!(scripts[0].is_jsx);
900    }
901
902    #[test]
903    fn source_type_plain_js_detection() {
904        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
905        assert_eq!(scripts.len(), 1);
906        assert!(!scripts[0].is_typescript);
907        assert!(!scripts[0].is_jsx);
908    }
909
910    #[test]
911    fn is_sfc_file_rejects_no_extension() {
912        assert!(!is_sfc_file(Path::new("Makefile")));
913    }
914
915    #[test]
916    fn is_sfc_file_rejects_mdx() {
917        assert!(!is_sfc_file(Path::new("post.mdx")));
918    }
919
920    #[test]
921    fn is_sfc_file_rejects_css() {
922        assert!(!is_sfc_file(Path::new("styles.css")));
923    }
924
925    #[test]
926    fn multiple_script_blocks_both_have_offsets() {
927        let source = r#"<script lang="ts">const a = 1;</script>
928<script setup lang="ts">const b = 2;</script>"#;
929        let scripts = extract_sfc_scripts(source);
930        assert_eq!(scripts.len(), 2);
931        let offset0 = scripts[0].byte_offset;
932        let offset1 = scripts[1].byte_offset;
933        assert_eq!(
934            &source[offset0..offset0 + "const a = 1;".len()],
935            "const a = 1;"
936        );
937        assert_eq!(
938            &source[offset1..offset1 + "const b = 2;".len()],
939            "const b = 2;"
940        );
941    }
942
943    #[test]
944    fn script_with_src_and_lang() {
945        let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
946        assert_eq!(scripts.len(), 1);
947        assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
948        assert!(scripts[0].is_typescript);
949        assert!(scripts[0].is_jsx);
950    }
951
952    #[test]
953    fn extract_style_block_lang_scss() {
954        let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
955        let styles = extract_sfc_styles(source);
956        assert_eq!(styles.len(), 1);
957        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
958        assert!(styles[0].body.contains("@import"));
959        assert!(styles[0].src.is_none());
960    }
961
962    #[test]
963    fn extract_style_block_with_src() {
964        let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
965        let styles = extract_sfc_styles(source);
966        assert_eq!(styles.len(), 1);
967        assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
968        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
969    }
970
971    #[test]
972    fn extract_style_block_plain_no_lang() {
973        let source = r"<style>.foo { color: red; }</style>";
974        let styles = extract_sfc_styles(source);
975        assert_eq!(styles.len(), 1);
976        assert!(styles[0].lang.is_none());
977    }
978
979    #[test]
980    fn extract_multiple_style_blocks() {
981        let source = r#"<style lang="scss">@import 'a';</style>
982<style scoped lang="scss">@import 'b';</style>"#;
983        let styles = extract_sfc_styles(source);
984        assert_eq!(styles.len(), 2);
985    }
986
987    #[test]
988    fn style_block_inside_html_comment_filtered() {
989        let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
990<style lang="scss">@import 'good';</style>"#;
991        let styles = extract_sfc_styles(source);
992        assert_eq!(styles.len(), 1);
993        assert!(styles[0].body.contains("good"));
994    }
995
996    #[test]
997    fn parse_sfc_extracts_style_imports_with_from_style_flag() {
998        let info = parse_sfc_to_module(
999            FileId(0),
1000            Path::new("Foo.vue"),
1001            r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1002            0,
1003            false,
1004        );
1005        let style_import = info
1006            .imports
1007            .iter()
1008            .find(|i| i.source == "./Foo")
1009            .expect("scss @import 'Foo' should be normalized to ./Foo");
1010        assert!(
1011            style_import.from_style,
1012            "imports from <style> blocks must carry from_style=true so the resolver \
1013             enables SCSS partial fallback for the SFC importer"
1014        );
1015        assert!(matches!(
1016            style_import.imported_name,
1017            ImportedName::SideEffect
1018        ));
1019    }
1020
1021    #[test]
1022    fn parse_sfc_extracts_style_plugin_as_default_import() {
1023        let info = parse_sfc_to_module(
1024            FileId(0),
1025            Path::new("Foo.vue"),
1026            r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1027            0,
1028            false,
1029        );
1030        let plugin_import = info
1031            .imports
1032            .iter()
1033            .find(|i| i.source == "./tailwind-plugin.js")
1034            .expect("style @plugin should create an import");
1035        assert!(plugin_import.from_style);
1036        assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1037    }
1038
1039    #[test]
1040    fn parse_sfc_extracts_style_src_with_from_style_flag() {
1041        let info = parse_sfc_to_module(
1042            FileId(0),
1043            Path::new("Bar.vue"),
1044            r#"<style src="./Bar.scss" lang="scss"></style>"#,
1045            0,
1046            false,
1047        );
1048        let style_src = info
1049            .imports
1050            .iter()
1051            .find(|i| i.source == "./Bar.scss")
1052            .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1053        assert!(style_src.from_style);
1054    }
1055
1056    #[test]
1057    fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1058        let info = parse_sfc_to_module(
1059            FileId(0),
1060            Path::new("Baz.vue"),
1061            r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1062            0,
1063            false,
1064        );
1065        assert!(
1066            info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1067            "src reference should still be seeded for unsupported lang"
1068        );
1069        assert!(
1070            !info.imports.iter().any(|i| i.source.contains("skipped")),
1071            "postcss body should not be scanned for @import directives"
1072        );
1073    }
1074}