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