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