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