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        local_type_declarations: Vec::new(),
324        public_signature_type_references: Vec::new(),
325        namespace_object_aliases: Vec::new(),
326        iconify_prefixes: Vec::new(),
327        auto_import_candidates: Vec::new(),
328        directives: Vec::new(),
329        security_sinks: Vec::new(),
330        security_sinks_skipped: 0,
331    }
332}
333
334fn merge_script_into_module(
335    kind: SfcKind,
336    script: &SfcScript,
337    combined: &mut ModuleInfo,
338    template_visible_imports: &mut FxHashSet<String>,
339    template_visible_bound_targets: &mut FxHashMap<String, String>,
340    need_complexity: bool,
341) {
342    if kind == SfcKind::Vue
343        && let Some(src) = &script.src
344    {
345        add_script_src_import(combined, src, script.src_span);
346    }
347
348    let allocator = Allocator::default();
349    let parser_return =
350        Parser::new(&allocator, &script.body, source_type_for_script(script)).parse();
351    let mut extractor = ModuleInfoExtractor::new();
352    extractor.visit_program(&parser_return.program);
353    let extraction = ExtractionResult::contiguous(&script.body, script.byte_offset);
354    extractor.remap_spans_with(|span| extraction.remap_span(span));
355    extractor.resolve_typed_destructure_bindings();
356
357    let augmented_body = build_generic_attr_probe_source(script);
358    let empty_template_used = rustc_hash::FxHashSet::default();
359    let (binding_usage, auto_import_candidates) = if let Some(augmented) = augmented_body.as_deref()
360    {
361        let augmented_return =
362            Parser::new(&allocator, augmented, source_type_for_script(script)).parse();
363        (
364            compute_import_binding_usage(
365                &augmented_return.program,
366                &extractor.imports,
367                &empty_template_used,
368            ),
369            compute_auto_import_candidates(&parser_return.program),
370        )
371    } else {
372        let semantic_usage = compute_semantic_usage(
373            &parser_return.program,
374            &extractor.imports,
375            &empty_template_used,
376        );
377        (
378            semantic_usage.import_binding_usage,
379            semantic_usage.auto_import_candidates,
380        )
381    };
382    combined
383        .unused_import_bindings
384        .extend(binding_usage.unused.iter().cloned());
385    combined
386        .type_referenced_import_bindings
387        .extend(binding_usage.type_referenced.iter().cloned());
388    combined
389        .value_referenced_import_bindings
390        .extend(binding_usage.value_referenced.iter().cloned());
391    combined
392        .auto_import_candidates
393        .extend(auto_import_candidates);
394    if need_complexity {
395        combined.complexity.extend(translate_script_complexity(
396            script,
397            &parser_return.program,
398            &combined.line_offsets,
399        ));
400    }
401
402    if is_template_visible_script(kind, script) {
403        template_visible_imports.extend(
404            extractor
405                .imports
406                .iter()
407                .filter(|import| !import.local_name.is_empty())
408                .map(|import| import.local_name.clone()),
409        );
410        template_visible_bound_targets.extend(
411            extractor
412                .binding_target_names()
413                .iter()
414                .filter(|(local, _)| !local.starts_with("this."))
415                .map(|(local, target)| (local.clone(), target.clone())),
416        );
417    }
418
419    extractor.merge_into(combined);
420}
421
422fn translate_script_complexity(
423    script: &SfcScript,
424    program: &oxc_ast::ast::Program<'_>,
425    sfc_line_offsets: &[u32],
426) -> Vec<FunctionComplexity> {
427    let script_line_offsets = compute_line_offsets(&script.body);
428    let mut complexity =
429        crate::complexity::compute_complexity(program, &script.body, &script_line_offsets);
430    let (body_start_line, body_start_col) =
431        byte_offset_to_line_col(sfc_line_offsets, script.byte_offset as u32);
432
433    for function in &mut complexity {
434        function.line = body_start_line + function.line.saturating_sub(1);
435        if function.line == body_start_line {
436            function.col += body_start_col;
437        }
438    }
439
440    complexity
441}
442
443fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
444    let span = source_span.unwrap_or_default();
445    module.imports.push(ImportInfo {
446        source: normalize_asset_url(source),
447        imported_name: ImportedName::SideEffect,
448        local_name: String::new(),
449        is_type_only: false,
450        from_style: false,
451        span,
452        source_span: span,
453    });
454}
455
456/// `lang` attribute values whose body we know how to scan for `@import` /
457/// `@use` / `@forward` / `@plugin` directives. Plain `<style>` (no `lang`) is treated as
458/// CSS. `less`, `stylus`, and `postcss` bodies are NOT scanned because their
459/// import syntax differs (`@import (reference)` modifiers, etc.); their
460/// `<style src="...">` references are still seeded.
461fn style_lang_is_scss(lang: Option<&str>) -> bool {
462    matches!(lang, Some("scss" | "sass"))
463}
464
465fn style_lang_is_css_like(lang: Option<&str>) -> bool {
466    lang.is_none() || matches!(lang, Some("css"))
467}
468
469fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
470    if let Some(src) = &style.src {
471        let span = style.src_span.unwrap_or_default();
472        combined.imports.push(ImportInfo {
473            source: normalize_asset_url(src),
474            imported_name: ImportedName::SideEffect,
475            local_name: String::new(),
476            is_type_only: false,
477            from_style: true,
478            span,
479            source_span: span,
480        });
481    }
482
483    let lang = style.lang.as_deref();
484    let is_scss = style_lang_is_scss(lang);
485    let is_css_like = style_lang_is_css_like(lang);
486    if !is_scss && !is_css_like {
487        return;
488    }
489
490    for source in crate::css::extract_css_import_sources(&style.body, is_scss) {
491        let source_span = Span::new(
492            style.byte_offset as u32 + source.span.start,
493            style.byte_offset as u32 + source.span.end,
494        );
495        combined.imports.push(ImportInfo {
496            source: source.normalized,
497            imported_name: if source.is_plugin {
498                ImportedName::Default
499            } else {
500                ImportedName::SideEffect
501            },
502            local_name: String::new(),
503            is_type_only: false,
504            from_style: true,
505            span: source_span,
506            source_span,
507        });
508    }
509}
510
511fn source_type_for_script(script: &SfcScript) -> SourceType {
512    match (script.is_typescript, script.is_jsx) {
513        (true, true) => SourceType::tsx(),
514        (true, false) => SourceType::ts(),
515        (false, true) => SourceType::jsx(),
516        (false, false) => SourceType::mjs(),
517    }
518}
519
520/// Build an augmented script body that pins the `generic="..."` constraint as
521/// a synthetic local type alias. The alias is unexported and uses a sentinel
522/// name so it can't collide with user code. Returns `None` when there is no
523/// generic attribute to pin (the common case), so callers fall back to the
524/// raw body without paying for a second parse.
525fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
526    let constraint = script.generic_attr.as_deref()?.trim();
527    if constraint.is_empty() {
528        return None;
529    }
530    Some(format!(
531        "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
532        script.body, constraint,
533    ))
534}
535
536fn apply_template_usage(
537    kind: SfcKind,
538    source: &str,
539    template_visible_imports: &FxHashSet<String>,
540    template_visible_bound_targets: &FxHashMap<String, String>,
541    combined: &mut ModuleInfo,
542) {
543    let template_usage = collect_template_usage_with_bound_targets(
544        kind,
545        source,
546        template_visible_imports,
547        template_visible_bound_targets,
548    );
549    combined
550        .unused_import_bindings
551        .retain(|binding| !template_usage.used_bindings.contains(binding));
552    combined
553        .member_accesses
554        .extend(template_usage.member_accesses);
555    combined
556        .whole_object_uses
557        .extend(template_usage.whole_object_uses);
558    if !template_usage.unresolved_tag_names.is_empty() {
559        let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
560        names.sort_unstable();
561        combined.auto_import_candidates.extend(names);
562        combined.auto_import_candidates.dedup();
563    }
564}
565
566fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
567    match kind {
568        SfcKind::Vue => script.is_setup,
569        SfcKind::Svelte => !script.is_context_module,
570    }
571}
572
573#[cfg(all(test, not(miri)))]
574mod tests {
575    use super::*;
576
577    #[test]
578    fn is_sfc_file_vue() {
579        assert!(is_sfc_file(Path::new("App.vue")));
580    }
581
582    #[test]
583    fn is_sfc_file_svelte() {
584        assert!(is_sfc_file(Path::new("Counter.svelte")));
585    }
586
587    #[test]
588    fn is_sfc_file_rejects_ts() {
589        assert!(!is_sfc_file(Path::new("utils.ts")));
590    }
591
592    #[test]
593    fn is_sfc_file_rejects_jsx() {
594        assert!(!is_sfc_file(Path::new("App.jsx")));
595    }
596
597    #[test]
598    fn is_sfc_file_rejects_astro() {
599        assert!(!is_sfc_file(Path::new("Layout.astro")));
600    }
601
602    #[test]
603    fn single_plain_script() {
604        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
605        assert_eq!(scripts.len(), 1);
606        assert_eq!(scripts[0].body, "const x = 1;");
607        assert!(!scripts[0].is_typescript);
608        assert!(!scripts[0].is_jsx);
609        assert!(scripts[0].src.is_none());
610    }
611
612    #[test]
613    fn single_ts_script() {
614        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
615        assert_eq!(scripts.len(), 1);
616        assert!(scripts[0].is_typescript);
617        assert!(!scripts[0].is_jsx);
618    }
619
620    #[test]
621    fn single_tsx_script() {
622        let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
623        assert_eq!(scripts.len(), 1);
624        assert!(scripts[0].is_typescript);
625        assert!(scripts[0].is_jsx);
626    }
627
628    #[test]
629    fn single_jsx_script() {
630        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
631        assert_eq!(scripts.len(), 1);
632        assert!(!scripts[0].is_typescript);
633        assert!(scripts[0].is_jsx);
634    }
635
636    #[test]
637    fn two_script_blocks() {
638        let source = r#"
639<script lang="ts">
640export default {};
641</script>
642<script setup lang="ts">
643const count = 0;
644</script>
645"#;
646        let scripts = extract_sfc_scripts(source);
647        assert_eq!(scripts.len(), 2);
648        assert!(scripts[0].body.contains("export default"));
649        assert!(scripts[1].body.contains("count"));
650    }
651
652    #[test]
653    fn script_setup_extracted() {
654        let scripts =
655            extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
656        assert_eq!(scripts.len(), 1);
657        assert!(scripts[0].body.contains("import"));
658        assert!(scripts[0].is_typescript);
659    }
660
661    #[test]
662    fn script_src_detected() {
663        let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
664        assert_eq!(scripts.len(), 1);
665        assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
666    }
667
668    #[test]
669    fn data_src_not_treated_as_src() {
670        let scripts =
671            extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
672        assert_eq!(scripts.len(), 1);
673        assert!(scripts[0].src.is_none());
674    }
675
676    #[test]
677    fn script_inside_html_comment_filtered() {
678        let source = r#"
679<!-- <script lang="ts">import { bad } from 'bad';</script> -->
680<script lang="ts">import { good } from 'good';</script>
681"#;
682        let scripts = extract_sfc_scripts(source);
683        assert_eq!(scripts.len(), 1);
684        assert!(scripts[0].body.contains("good"));
685    }
686
687    #[test]
688    fn spanning_comment_filters_script() {
689        let source = r#"
690<!-- disabled:
691<script lang="ts">import { bad } from 'bad';</script>
692-->
693<script lang="ts">const ok = true;</script>
694"#;
695        let scripts = extract_sfc_scripts(source);
696        assert_eq!(scripts.len(), 1);
697        assert!(scripts[0].body.contains("ok"));
698    }
699
700    #[test]
701    fn string_containing_comment_markers_not_corrupted() {
702        let source = r#"
703<script setup lang="ts">
704const marker = "<!-- not a comment -->";
705import { ref } from 'vue';
706</script>
707"#;
708        let scripts = extract_sfc_scripts(source);
709        assert_eq!(scripts.len(), 1);
710        assert!(scripts[0].body.contains("import"));
711    }
712
713    #[test]
714    fn generic_attr_with_angle_bracket() {
715        let source =
716            r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
717        let scripts = extract_sfc_scripts(source);
718        assert_eq!(scripts.len(), 1);
719        assert_eq!(scripts[0].body, "const x = 1;");
720    }
721
722    #[test]
723    fn nested_generic_attr() {
724        let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
725        let scripts = extract_sfc_scripts(source);
726        assert_eq!(scripts.len(), 1);
727        assert_eq!(scripts[0].body, "const x = 1;");
728    }
729
730    #[test]
731    fn lang_single_quoted() {
732        let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
733        assert_eq!(scripts.len(), 1);
734        assert!(scripts[0].is_typescript);
735    }
736
737    #[test]
738    fn uppercase_script_tag() {
739        let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
740        assert_eq!(scripts.len(), 1);
741        assert!(scripts[0].is_typescript);
742    }
743
744    #[test]
745    fn no_script_block() {
746        let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
747        assert!(scripts.is_empty());
748    }
749
750    #[test]
751    fn empty_script_body() {
752        let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
753        assert_eq!(scripts.len(), 1);
754        assert!(scripts[0].body.is_empty());
755    }
756
757    #[test]
758    fn whitespace_only_script() {
759        let scripts = extract_sfc_scripts("<script lang=\"ts\">\n  \n</script>");
760        assert_eq!(scripts.len(), 1);
761        assert!(scripts[0].body.trim().is_empty());
762    }
763
764    #[test]
765    fn byte_offset_is_set() {
766        let source = r#"<template><div/></template><script lang="ts">code</script>"#;
767        let scripts = extract_sfc_scripts(source);
768        assert_eq!(scripts.len(), 1);
769        let offset = scripts[0].byte_offset;
770        assert_eq!(&source[offset..offset + 4], "code");
771    }
772
773    #[test]
774    fn script_with_extra_attributes() {
775        let scripts = extract_sfc_scripts(
776            r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
777        );
778        assert_eq!(scripts.len(), 1);
779        assert!(scripts[0].is_typescript);
780        assert!(scripts[0].src.is_none());
781    }
782
783    #[test]
784    fn multiple_script_blocks_exports_combined() {
785        let source = r#"
786<script lang="ts">
787export const version = '1.0';
788</script>
789<script setup lang="ts">
790import { ref } from 'vue';
791const count = ref(0);
792</script>
793"#;
794        let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
795        assert!(
796            info.exports
797                .iter()
798                .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
799            "export from <script> block should be extracted"
800        );
801        assert!(
802            info.imports.iter().any(|i| i.source == "vue"),
803            "import from <script setup> block should be extracted"
804        );
805    }
806
807    #[test]
808    fn lang_tsx_detected_as_typescript_jsx() {
809        let scripts =
810            extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
811        assert_eq!(scripts.len(), 1);
812        assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
813        assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
814    }
815
816    #[test]
817    fn multiline_html_comment_filters_all_script_blocks_inside() {
818        let source = r#"
819<!--
820  This whole section is disabled:
821  <script lang="ts">import { bad1 } from 'bad1';</script>
822  <script lang="ts">import { bad2 } from 'bad2';</script>
823-->
824<script lang="ts">import { good } from 'good';</script>
825"#;
826        let scripts = extract_sfc_scripts(source);
827        assert_eq!(scripts.len(), 1);
828        assert!(scripts[0].body.contains("good"));
829    }
830
831    #[test]
832    fn script_src_generates_side_effect_import() {
833        let info = parse_sfc_to_module(
834            FileId(0),
835            Path::new("External.vue"),
836            r#"<script src="./external-logic.ts" lang="ts"></script>"#,
837            0,
838            false,
839        );
840        assert!(
841            info.imports
842                .iter()
843                .any(|i| i.source == "./external-logic.ts"
844                    && matches!(i.imported_name, ImportedName::SideEffect)),
845            "script src should generate a side-effect import"
846        );
847    }
848
849    #[test]
850    fn parse_sfc_no_script_returns_empty_module() {
851        let info = parse_sfc_to_module(
852            FileId(0),
853            Path::new("Empty.vue"),
854            "<template><div>Hello</div></template>",
855            42,
856            false,
857        );
858        assert!(info.imports.is_empty());
859        assert!(info.exports.is_empty());
860        assert_eq!(info.content_hash, 42);
861        assert_eq!(info.file_id, FileId(0));
862    }
863
864    #[test]
865    fn parse_sfc_has_line_offsets() {
866        let info = parse_sfc_to_module(
867            FileId(0),
868            Path::new("LineOffsets.vue"),
869            r#"<script lang="ts">const x = 1;</script>"#,
870            0,
871            false,
872        );
873        assert!(!info.line_offsets.is_empty());
874    }
875
876    #[test]
877    fn parse_sfc_has_suppressions() {
878        let info = parse_sfc_to_module(
879            FileId(0),
880            Path::new("Suppressions.vue"),
881            r#"<script lang="ts">
882// fallow-ignore-file
883export const foo = 1;
884</script>"#,
885            0,
886            false,
887        );
888        assert!(!info.suppressions.is_empty());
889    }
890
891    #[test]
892    fn source_type_jsx_detection() {
893        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
894        assert_eq!(scripts.len(), 1);
895        assert!(!scripts[0].is_typescript);
896        assert!(scripts[0].is_jsx);
897    }
898
899    #[test]
900    fn source_type_plain_js_detection() {
901        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
902        assert_eq!(scripts.len(), 1);
903        assert!(!scripts[0].is_typescript);
904        assert!(!scripts[0].is_jsx);
905    }
906
907    #[test]
908    fn is_sfc_file_rejects_no_extension() {
909        assert!(!is_sfc_file(Path::new("Makefile")));
910    }
911
912    #[test]
913    fn is_sfc_file_rejects_mdx() {
914        assert!(!is_sfc_file(Path::new("post.mdx")));
915    }
916
917    #[test]
918    fn is_sfc_file_rejects_css() {
919        assert!(!is_sfc_file(Path::new("styles.css")));
920    }
921
922    #[test]
923    fn multiple_script_blocks_both_have_offsets() {
924        let source = r#"<script lang="ts">const a = 1;</script>
925<script setup lang="ts">const b = 2;</script>"#;
926        let scripts = extract_sfc_scripts(source);
927        assert_eq!(scripts.len(), 2);
928        let offset0 = scripts[0].byte_offset;
929        let offset1 = scripts[1].byte_offset;
930        assert_eq!(
931            &source[offset0..offset0 + "const a = 1;".len()],
932            "const a = 1;"
933        );
934        assert_eq!(
935            &source[offset1..offset1 + "const b = 2;".len()],
936            "const b = 2;"
937        );
938    }
939
940    #[test]
941    fn script_with_src_and_lang() {
942        let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
943        assert_eq!(scripts.len(), 1);
944        assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
945        assert!(scripts[0].is_typescript);
946        assert!(scripts[0].is_jsx);
947    }
948
949    #[test]
950    fn extract_style_block_lang_scss() {
951        let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
952        let styles = extract_sfc_styles(source);
953        assert_eq!(styles.len(), 1);
954        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
955        assert!(styles[0].body.contains("@import"));
956        assert!(styles[0].src.is_none());
957    }
958
959    #[test]
960    fn extract_style_block_with_src() {
961        let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
962        let styles = extract_sfc_styles(source);
963        assert_eq!(styles.len(), 1);
964        assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
965        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
966    }
967
968    #[test]
969    fn extract_style_block_plain_no_lang() {
970        let source = r"<style>.foo { color: red; }</style>";
971        let styles = extract_sfc_styles(source);
972        assert_eq!(styles.len(), 1);
973        assert!(styles[0].lang.is_none());
974    }
975
976    #[test]
977    fn extract_multiple_style_blocks() {
978        let source = r#"<style lang="scss">@import 'a';</style>
979<style scoped lang="scss">@import 'b';</style>"#;
980        let styles = extract_sfc_styles(source);
981        assert_eq!(styles.len(), 2);
982    }
983
984    #[test]
985    fn style_block_inside_html_comment_filtered() {
986        let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
987<style lang="scss">@import 'good';</style>"#;
988        let styles = extract_sfc_styles(source);
989        assert_eq!(styles.len(), 1);
990        assert!(styles[0].body.contains("good"));
991    }
992
993    #[test]
994    fn parse_sfc_extracts_style_imports_with_from_style_flag() {
995        let info = parse_sfc_to_module(
996            FileId(0),
997            Path::new("Foo.vue"),
998            r#"<template/><style lang="scss">@import 'Foo';</style>"#,
999            0,
1000            false,
1001        );
1002        let style_import = info
1003            .imports
1004            .iter()
1005            .find(|i| i.source == "./Foo")
1006            .expect("scss @import 'Foo' should be normalized to ./Foo");
1007        assert!(
1008            style_import.from_style,
1009            "imports from <style> blocks must carry from_style=true so the resolver \
1010             enables SCSS partial fallback for the SFC importer"
1011        );
1012        assert!(matches!(
1013            style_import.imported_name,
1014            ImportedName::SideEffect
1015        ));
1016    }
1017
1018    #[test]
1019    fn parse_sfc_extracts_style_plugin_as_default_import() {
1020        let info = parse_sfc_to_module(
1021            FileId(0),
1022            Path::new("Foo.vue"),
1023            r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1024            0,
1025            false,
1026        );
1027        let plugin_import = info
1028            .imports
1029            .iter()
1030            .find(|i| i.source == "./tailwind-plugin.js")
1031            .expect("style @plugin should create an import");
1032        assert!(plugin_import.from_style);
1033        assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1034    }
1035
1036    #[test]
1037    fn parse_sfc_extracts_style_src_with_from_style_flag() {
1038        let info = parse_sfc_to_module(
1039            FileId(0),
1040            Path::new("Bar.vue"),
1041            r#"<style src="./Bar.scss" lang="scss"></style>"#,
1042            0,
1043            false,
1044        );
1045        let style_src = info
1046            .imports
1047            .iter()
1048            .find(|i| i.source == "./Bar.scss")
1049            .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1050        assert!(style_src.from_style);
1051    }
1052
1053    #[test]
1054    fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1055        let info = parse_sfc_to_module(
1056            FileId(0),
1057            Path::new("Baz.vue"),
1058            r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1059            0,
1060            false,
1061        );
1062        assert!(
1063            info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1064            "src reference should still be seeded for unsupported lang"
1065        );
1066        assert!(
1067            !info.imports.iter().any(|i| i.source.contains("skipped")),
1068            "postcss body should not be scanned for @import directives"
1069        );
1070    }
1071}