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