Skip to main content

fallow_extract/
sfc.rs

1//! Vue/Svelte Single File Component (SFC) script and style extraction.
2//!
3//! Extracts `<script>` block content from `.vue` and `.svelte` files using regex,
4//! handling `lang`, `src` metadata, and `generic` attributes, and filtering
5//! HTML comments. Vue external script references are emitted as graph edges;
6//! Svelte markup-level script `src` references are treated as runtime HTML.
7//! Also extracts `<style>` block sources (`@import` / `@use` / `@forward` /
8//! `@plugin` and `<style src="...">`) so referenced CSS / SCSS files become
9//! reachable from the component, preventing false `unused-files` reports on
10//! co-located styles.
11
12use std::path::Path;
13use std::sync::LazyLock;
14
15use oxc_allocator::Allocator;
16use oxc_ast_visit::Visit;
17use oxc_parser::Parser;
18use oxc_span::SourceType;
19use rustc_hash::{FxHashMap, FxHashSet};
20
21use crate::asset_url::normalize_asset_url;
22use crate::parse::compute_import_binding_usage;
23use crate::sfc_template::{SfcKind, collect_template_usage_with_bound_targets};
24use crate::source_map::ExtractionResult;
25use crate::visitor::ModuleInfoExtractor;
26use crate::{ImportInfo, ImportedName, ModuleInfo};
27use fallow_types::discover::FileId;
28use fallow_types::extract::{FunctionComplexity, byte_offset_to_line_col, compute_line_offsets};
29use oxc_span::Span;
30
31/// Regex to extract `<script>` block content from Vue/Svelte SFCs.
32/// The attrs pattern skips `>` in quoted values and in brace expressions up to 3 levels deep (#4828).
33static SCRIPT_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
34    crate::static_regex(
35        r#"(?is)<script\b(?P<attrs>(?:[^>"'{]|"[^"]*"|'[^']*'|\{(?:[^{}"'`]|"[^"]*"|'[^']*'|`[^`]*`|\{(?:[^{}"'`]|"[^"]*"|'[^']*'|`[^`]*`|\{[^{}]*\})*\})*\}|\{)*)>(?P<body>[\s\S]*?)</script>"#,
36    )
37});
38
39/// Regex to extract the `lang` attribute value from a script tag.
40static LANG_ATTR_RE: LazyLock<regex::Regex> =
41    LazyLock::new(|| crate::static_regex(r#"lang\s*=\s*["'](\w+)["']"#));
42
43/// Regex to extract the `src` attribute value from a script tag.
44/// Requires whitespace (or start of string) before `src` to avoid matching `data-src` etc.
45static SRC_ATTR_RE: LazyLock<regex::Regex> =
46    LazyLock::new(|| crate::static_regex(r#"(?:^|\s)src\s*=\s*["']([^"']+)["']"#));
47
48/// Regex to detect Vue's bare `setup` attribute.
49static SETUP_ATTR_RE: LazyLock<regex::Regex> =
50    LazyLock::new(|| crate::static_regex(r"(?:^|\s)setup(?:\s|$)"));
51
52/// Regex to detect Svelte's `context="module"` attribute (Svelte 4).
53static CONTEXT_MODULE_ATTR_RE: LazyLock<regex::Regex> =
54    LazyLock::new(|| crate::static_regex(r#"context\s*=\s*["']module["']"#));
55
56/// Regex to detect Svelte 5's bare `module` script attribute (`<script module>`,
57/// `<script module lang="ts">`). Anchored like [`SETUP_ATTR_RE`] so `module` must
58/// be a standalone attribute, not a substring of another attr name (e.g.
59/// `data-module`) or value.
60static SVELTE_MODULE_ATTR_RE: LazyLock<regex::Regex> =
61    LazyLock::new(|| crate::static_regex(r"(?:^|\s)module(?:\s|$|=)"));
62
63/// Regex to extract Vue's `generic="..."` attribute value (script-setup
64/// generics). Matches the contents between the quotes and stops at the
65/// closing quote, mirroring `LANG_ATTR_RE`.
66static VUE_GENERIC_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
67    crate::static_regex(r#"(?:^|\s)generic\s*=\s*"([^"]*)"|(?:^|\s)generic\s*=\s*'([^']*)'"#)
68});
69
70/// Regex to extract Svelte's `generics="..."` attribute value (Svelte 4
71/// generic script attribute, repurposed by some Svelte 5 code).
72static SVELTE_GENERICS_ATTR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
73    crate::static_regex(r#"(?:^|\s)generics\s*=\s*"([^"]*)"|(?:^|\s)generics\s*=\s*'([^']*)'"#)
74});
75
76/// Regex to match HTML comments for filtering script blocks inside comments.
77static HTML_COMMENT_RE: LazyLock<regex::Regex> =
78    LazyLock::new(|| crate::static_regex(r"(?s)<!--.*?-->"));
79
80/// Regex to detect a whole-object prop/attr spread in a Vue template:
81/// `v-bind="$attrs"`, `v-bind="$props"`, or `v-bind="props"` (with single or
82/// double quotes). A bound prop may be consumed indirectly, so the
83/// `unused-component-prop` detector abstains on the whole file when this matches.
84static PROPS_ATTRS_SPREAD_RE: LazyLock<regex::Regex> =
85    LazyLock::new(|| crate::static_regex(r#"v-bind\s*=\s*["'](?:\$attrs|\$props|props)["']"#));
86
87/// FP-1 (unused-load-data-key): a SvelteKit route component passing the whole
88/// `data` prop opaquely in MARKUP, where a child reads arbitrary keys the
89/// detector cannot see. Matches `data={data}` (whole-prop pass to a child) and
90/// `{...data}` (Svelte template spread). The script-side `const x = {...data}` /
91/// `fn(data)` / `const X = data` forms are captured by the JS visitor instead.
92/// Only a whole-`data` pass forces the abstain; `data.x` member access stays a
93/// credited consumer.
94static SVELTE_TEMPLATE_DATA_WHOLE_USE_RE: LazyLock<regex::Regex> =
95    LazyLock::new(|| crate::static_regex(r"(?:=\s*\{\s*data\s*\}|\{\s*\.\.\.\s*data\s*\})"));
96
97/// Matches an emit-style call in template markup: a callee identifier (or
98/// `$emit`) followed by `(` and its first argument. Group 1 is the callee name
99/// (filtered against the harvested emit binding / `$emit` by the caller), groups
100/// 2 and 3 are a string-literal first arg (single- or double-quoted: the event
101/// name, credited as used), and group 4 is the first non-space character of a
102/// NON-literal first arg (a dynamic emit, whose event name is unknowable, forcing
103/// a whole-file abstain). Event names allow kebab and namespaced forms
104/// (`update:modelValue`, `my-event`). The Rust `regex` crate has no
105/// backreferences, so the two quote styles are separate alternatives.
106static TEMPLATE_EMIT_CALL_RE: LazyLock<regex::Regex> =
107    LazyLock::new(|| crate::static_regex(r#"([\w$]+)\s*\(\s*(?:'([\w:-]*)'|"([\w:-]*)"|(\S))"#));
108
109/// Regex to extract `<style>` block content from Vue/Svelte SFCs.
110/// Mirrors `SCRIPT_BLOCK_RE`: handles `>` inside quoted attribute values and
111/// captures the body so `@import` / `@use` / `@forward` directives can be parsed.
112static STYLE_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
113    crate::static_regex(
114        r#"(?is)<style\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</style>"#,
115    )
116});
117
118/// Static asset references in SFC markup: `<img src="./logo.png">`,
119/// `<source src="...">`, `<video poster="...">`, etc.
120///
121/// Scoped to genuine asset elements (`img` / `source` / `video` / `audio` /
122/// `track` / `embed`) so a custom component's `src` PROP (`<MyImage src="./x">`)
123/// is never misread as an asset edge. ONLY plain relative literals (`./` or
124/// `../`) are captured: dynamic bindings (`:src`, `v-bind:src`, `bind:src`,
125/// `src={...}`, `data-src`), alias-prefixed (`@/`), root-relative (`/foo`),
126/// remote, interpolated (`{{ }}` / `{ }`), and query/hash-suffixed values are
127/// all skipped (the value class excludes `{`, `?`, `#`, whitespace, and angle
128/// brackets, and the alternation anchors on a leading `./` or `../`). A
129/// captured ref becomes a `SideEffect` import; an existing asset resolves to
130/// `ExternalFile` (no finding) and a genuinely-missing one surfaces as
131/// `unresolved-import` on the trusted resolver path.
132static TEMPLATE_ASSET_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
133    crate::static_regex(
134        r#"(?si)<(?:img|source|video|audio|track|embed)\b(?:[^>"']|"[^"]*"|'[^']*')*?\s(?:src|poster)\s*=\s*(?:"((?:\./|\.\./)[^"<>{}?#\s]*)"|'((?:\./|\.\./)[^'<>{}?#\s]*)')"#,
135    )
136});
137
138/// Mask `<script>` / `<style>` blocks and HTML comments to equal-length spaces
139/// so a markup-region scan (asset refs) sees only the template, while byte
140/// offsets still map 1:1 into the original source for line/col reporting.
141fn mask_non_markup_regions(source: &str) -> String {
142    let mut masked = source.to_string();
143    for re in [&*SCRIPT_BLOCK_RE, &*STYLE_BLOCK_RE, &*HTML_COMMENT_RE] {
144        masked = re
145            .replace_all(&masked, |caps: &regex::Captures<'_>| {
146                " ".repeat(caps[0].len())
147            })
148            .into_owned();
149    }
150    masked
151}
152
153/// Collect static relative asset references from SFC markup as
154/// `(normalized_specifier, value_span)` pairs. See [`TEMPLATE_ASSET_RE`].
155fn collect_template_asset_refs(source: &str) -> Vec<(String, Span)> {
156    let masked = mask_non_markup_regions(source);
157    let mut refs = Vec::new();
158    for caps in TEMPLATE_ASSET_RE.captures_iter(&masked) {
159        let Some(value) = caps.get(1).or_else(|| caps.get(2)) else {
160            continue;
161        };
162        let raw = value.as_str();
163        if raw.is_empty() {
164            continue;
165        }
166        refs.push((
167            normalize_asset_url(raw),
168            Span::new(value.start() as u32, value.end() as u32),
169        ));
170    }
171    refs
172}
173
174/// An extracted `<script>` block from a Vue or Svelte SFC.
175pub struct SfcScript {
176    /// The script body text.
177    pub body: String,
178    /// Whether the script uses TypeScript (`lang="ts"` or `lang="tsx"`).
179    pub is_typescript: bool,
180    /// Whether the script uses JSX syntax (`lang="tsx"` or `lang="jsx"`).
181    pub is_jsx: bool,
182    /// Byte offset of the script body within the full SFC source.
183    pub byte_offset: usize,
184    /// External script source path from `src` attribute.
185    pub src: Option<String>,
186    /// Span of the `src` attribute value in the full SFC source.
187    pub src_span: Option<Span>,
188    /// Whether this script is a Vue `<script setup>` block.
189    pub is_setup: bool,
190    /// Whether this script is a Svelte module-context block.
191    pub is_context_module: bool,
192    /// Type-parameter list from a `generic="..."` (Vue) or `generics="..."`
193    /// (Svelte) attribute on the script tag. Holds the bare constraint, no
194    /// surrounding angle brackets, e.g. `T extends Test<boolean>`.
195    pub generic_attr: Option<String>,
196}
197
198/// Extract all `<script>` blocks from a Vue/Svelte SFC source string.
199pub fn extract_sfc_scripts(source: &str) -> Vec<SfcScript> {
200    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
201        .find_iter(source)
202        .map(|m| (m.start(), m.end()))
203        .collect();
204
205    SCRIPT_BLOCK_RE
206        .captures_iter(source)
207        .filter(|cap| {
208            let start = cap.get(0).map_or(0, |m| m.start());
209            !comment_ranges
210                .iter()
211                .any(|&(cs, ce)| start >= cs && start < ce)
212        })
213        .map(|cap| {
214            let attrs = cap.name("attrs").map_or("", |m| m.as_str());
215            let body_match = cap.name("body");
216            let byte_offset = body_match.map_or(0, |m| m.start());
217            let body = body_match.map_or("", |m| m.as_str()).to_string();
218            let lang = LANG_ATTR_RE
219                .captures(attrs)
220                .and_then(|c| c.get(1))
221                .map(|m| m.as_str());
222            let is_typescript = matches!(lang, Some("ts" | "tsx"));
223            let is_jsx = matches!(lang, Some("tsx" | "jsx"));
224            let src = SRC_ATTR_RE
225                .captures(attrs)
226                .and_then(|c| c.get(1))
227                .map(|m| m.as_str().to_string());
228            let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
229            let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
230                Span::new(
231                    (attrs_start + m.start()) as u32,
232                    (attrs_start + m.end()) as u32,
233                )
234            });
235            let is_setup = SETUP_ATTR_RE.is_match(attrs);
236            // Svelte module context: Svelte 4 `context="module"` OR Svelte 5's
237            // bare `module` attribute. Both scope declarations to the module
238            // script (not the instance), so `is_template_visible_script` returns
239            // false and the instance/module split for runes harvest is correct.
240            let is_context_module =
241                CONTEXT_MODULE_ATTR_RE.is_match(attrs) || SVELTE_MODULE_ATTR_RE.is_match(attrs);
242            let generic_attr = VUE_GENERIC_ATTR_RE
243                .captures(attrs)
244                .or_else(|| SVELTE_GENERICS_ATTR_RE.captures(attrs))
245                .and_then(|cap| cap.get(1).or_else(|| cap.get(2)))
246                .map(|m| m.as_str().to_string())
247                .filter(|value| !value.trim().is_empty());
248            SfcScript {
249                body,
250                is_typescript,
251                is_jsx,
252                byte_offset,
253                src,
254                src_span,
255                is_setup,
256                is_context_module,
257                generic_attr,
258            }
259        })
260        .collect()
261}
262
263/// An extracted `<style>` block from a Vue or Svelte SFC.
264pub struct SfcStyle {
265    /// The style body text (CSS / SCSS / Sass / Less / Stylus / PostCSS source).
266    pub body: String,
267    /// The `lang` attribute value (`scss`, `sass`, `less`, `stylus`, `postcss`, ...).
268    /// `None` for plain `<style>` (CSS).
269    pub lang: Option<String>,
270    /// External style source path from the `src` attribute (`<style src="./theme.scss">`).
271    pub src: Option<String>,
272    /// Span of the `src` attribute value in the full SFC source.
273    pub src_span: Option<Span>,
274    /// Byte offset of the style body within the full SFC source.
275    pub byte_offset: usize,
276}
277
278/// A source region extracted from a larger file while preserving the byte
279/// offset of the region body in the original source.
280pub struct SourceRegion {
281    /// Region body text.
282    pub body: String,
283    /// Byte offset of `body` within the original source.
284    pub byte_offset: usize,
285}
286
287/// Extract template markup regions from a Vue/Svelte SFC.
288///
289/// The returned regions exclude `<script>` blocks, `<style>` blocks, and HTML
290/// comments, so callers can tokenize authored markup without reading code or
291/// comments as template text. Offsets always point into the original SFC source.
292#[must_use]
293pub fn extract_sfc_template_regions(source: &str) -> Vec<SourceRegion> {
294    let mut ranges: Vec<(usize, usize)> = SCRIPT_BLOCK_RE
295        .find_iter(source)
296        .chain(STYLE_BLOCK_RE.find_iter(source))
297        .chain(HTML_COMMENT_RE.find_iter(source))
298        .map(|m| (m.start(), m.end()))
299        .collect();
300    ranges.sort_unstable_by_key(|(start, _)| *start);
301    ranges_to_gaps(source, &ranges)
302}
303
304/// Extract all `<style>` blocks from a Vue/Svelte SFC source string.
305///
306/// Mirrors [`extract_sfc_scripts`]: filters blocks inside HTML comments and
307/// captures the `lang` and `src` attributes so the caller can route the body to
308/// the right preprocessor's import scanner (currently only CSS / SCSS / Sass) or
309/// seed the `src` reference as a side-effect import.
310pub fn extract_sfc_styles(source: &str) -> Vec<SfcStyle> {
311    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
312        .find_iter(source)
313        .map(|m| (m.start(), m.end()))
314        .collect();
315
316    STYLE_BLOCK_RE
317        .captures_iter(source)
318        .filter(|cap| {
319            let start = cap.get(0).map_or(0, |m| m.start());
320            !comment_ranges
321                .iter()
322                .any(|&(cs, ce)| start >= cs && start < ce)
323        })
324        .map(|cap| {
325            let attrs = cap.name("attrs").map_or("", |m| m.as_str());
326            let body = cap.name("body").map_or("", |m| m.as_str()).to_string();
327            let byte_offset = cap.name("body").map_or(0, |m| m.start());
328            let lang = LANG_ATTR_RE
329                .captures(attrs)
330                .and_then(|c| c.get(1))
331                .map(|m| m.as_str().to_string());
332            let src = SRC_ATTR_RE
333                .captures(attrs)
334                .and_then(|c| c.get(1))
335                .map(|m| m.as_str().to_string());
336            let attrs_start = cap.name("attrs").map_or(0, |m| m.start());
337            let src_span = SRC_ATTR_RE.captures(attrs).and_then(|c| c.get(1)).map(|m| {
338                Span::new(
339                    (attrs_start + m.start()) as u32,
340                    (attrs_start + m.end()) as u32,
341                )
342            });
343            SfcStyle {
344                body,
345                lang,
346                src,
347                src_span,
348                byte_offset,
349            }
350        })
351        .collect()
352}
353
354/// Turn masked `ranges` into the gap regions between them, preserving byte
355/// offsets. `ranges` must be sorted by start offset; unsorted input silently
356/// drops the gaps that precede an out-of-order range.
357pub(crate) fn ranges_to_gaps(source: &str, ranges: &[(usize, usize)]) -> Vec<SourceRegion> {
358    let mut regions = Vec::new();
359    let mut cursor = 0;
360    for &(start, end) in ranges {
361        if start > cursor {
362            push_region(source, cursor, start, &mut regions);
363        }
364        cursor = cursor.max(end);
365    }
366    if cursor < source.len() {
367        push_region(source, cursor, source.len(), &mut regions);
368    }
369    regions
370}
371
372fn push_region(source: &str, start: usize, end: usize, regions: &mut Vec<SourceRegion>) {
373    let Some(body) = source.get(start..end) else {
374        return;
375    };
376    if body.trim().is_empty() {
377        return;
378    }
379    regions.push(SourceRegion {
380        body: body.to_string(),
381        byte_offset: start,
382    });
383}
384
385/// Check if a file path is a Vue or Svelte SFC (`.vue` or `.svelte`).
386#[must_use]
387pub fn is_sfc_file(path: &Path) -> bool {
388    path.extension()
389        .and_then(|e| e.to_str())
390        .is_some_and(|ext| ext == "vue" || ext == "svelte")
391}
392
393/// Parse an SFC file by extracting and combining all `<script>` and `<style>` blocks.
394#[cfg(test)]
395fn parse_sfc_to_module(
396    file_id: FileId,
397    path: &Path,
398    source: &str,
399    content_hash: u64,
400    need_complexity: bool,
401) -> ModuleInfo {
402    parse_sfc_to_module_with_mode(
403        file_id,
404        path,
405        source,
406        content_hash,
407        need_complexity,
408        fallow_types::shared_state::ExtractionMode::Standard,
409    )
410}
411
412pub(crate) fn parse_sfc_to_module_with_mode(
413    file_id: FileId,
414    path: &Path,
415    source: &str,
416    content_hash: u64,
417    need_complexity: bool,
418    mode: fallow_types::shared_state::ExtractionMode,
419) -> ModuleInfo {
420    let scripts = extract_sfc_scripts(source);
421    let styles = extract_sfc_styles(source);
422    let kind = sfc_kind(path);
423    let mut combined = empty_sfc_module(file_id, source, content_hash);
424    let mut template_visible_imports: FxHashSet<String> = FxHashSet::default();
425    let mut template_visible_bound_targets: FxHashMap<String, String> = FxHashMap::default();
426    let mut template_visible_iterable_types: FxHashMap<String, String> = FxHashMap::default();
427    let mut props_return_binding: Option<String> = None;
428    let mut emit_return_binding: Option<String> = None;
429    let mut shared_scope_references = SharedScopeReferences::default();
430    let has_setup_script = scripts.iter().any(|script| script.is_setup);
431
432    for script in &scripts {
433        merge_script_into_module(&mut SfcScriptMergeInput {
434            kind,
435            script,
436            has_setup_script,
437            combined: &mut combined,
438            shared_scope_references: &mut shared_scope_references,
439            template_visible_imports: &mut template_visible_imports,
440            template_visible_bound_targets: &mut template_visible_bound_targets,
441            template_visible_iterable_types: &mut template_visible_iterable_types,
442            props_return_binding: &mut props_return_binding,
443            emit_return_binding: &mut emit_return_binding,
444            need_complexity,
445            mode,
446        });
447    }
448    if scripts.len() > 1 {
449        credit_shared_scope_references(&shared_scope_references, &mut combined);
450    }
451
452    for style in &styles {
453        merge_style_into_module(style, &mut combined);
454    }
455
456    // Whole-object prop/attr spread in the template (`v-bind="$attrs"`,
457    // `v-bind="$props"`, `v-bind="props"`) can consume a prop indirectly, so the
458    // `unused-component-prop` detector must abstain on the whole file.
459    if kind == SfcKind::Vue
460        && !combined.component_props.is_empty()
461        && PROPS_ATTRS_SPREAD_RE.is_match(source)
462    {
463        combined.has_props_attrs_fallthrough = true;
464    }
465
466    apply_template_usage(TemplateUsageInput {
467        kind,
468        source,
469        template_visible_imports,
470        template_visible_bound_targets,
471        template_visible_iterable_types: &template_visible_iterable_types,
472        props_return_binding: props_return_binding.as_deref(),
473        credit_load_data: kind == SfcKind::Svelte && is_sveltekit_route_data_component(path),
474        combined: &mut combined,
475    });
476
477    if need_complexity {
478        append_template_complexity(kind, source, &mut combined);
479    }
480
481    // Credit `<emit_binding>('event')` / `$emit('event')` calls in the template
482    // (`@click="emit('close')"`), which the script-only emit usage walk cannot
483    // see. A dynamic template emit (`$emit(someVar)`) abstains the whole file.
484    if kind == SfcKind::Vue && !combined.component_emits.is_empty() {
485        apply_template_emit_usage(source, emit_return_binding.as_deref(), &mut combined);
486    }
487
488    // Harvest Svelte template `on:<name>` listener bindings on component tags
489    // into the per-file listened set; the `unused-svelte-event` detector unions
490    // these project-wide to decide which dispatched events are dead.
491    if kind == SfcKind::Svelte {
492        combined.svelte_listened_events =
493            crate::sfc_template::collect_svelte_listened_events(source);
494    }
495
496    append_template_asset_imports(source, &mut combined);
497    dedup_import_binding_lists(&mut combined);
498    apply_component_contracts(kind, source, &mut combined);
499
500    combined
501}
502
503/// Append the synthetic `<template>` complexity entry for the SFC. Counts
504/// template control flow (`v-if`/`v-for`, `{#if}`/`{#each}`) and
505/// bound-expression/interpolation complexity so a template-heavy SFC is not
506/// scored as artificially simple. The scanners mask `<script>`/`<style>`/comments,
507/// so script control flow is NOT double-counted (it is scored by
508/// `translate_script_complexity`). Mirrors Angular's synthetic entry; no new rule
509/// or threshold, the entry folds into the existing complexity aggregate.
510fn append_template_complexity(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
511    match kind {
512        SfcKind::Vue => {
513            combined.complexity.extend(
514                crate::template_complexity::compute_vue_template_complexity(source),
515            );
516        }
517        // Svelte yields the `<template>` unit plus one `<snippet:NAME>` unit
518        // per top-level `{#snippet}` block.
519        SfcKind::Svelte => combined
520            .complexity
521            .extend(crate::template_complexity::compute_svelte_template_complexity(source)),
522    }
523}
524
525/// Turn static relative asset references in markup (`<img src="./logo.png">`)
526/// into `SideEffect` imports so a genuinely-missing asset surfaces as
527/// `unresolved-import` (existing assets resolve to `ExternalFile`, no finding).
528fn append_template_asset_imports(source: &str, combined: &mut ModuleInfo) {
529    for (specifier, span) in collect_template_asset_refs(source) {
530        combined.imports.push(ImportInfo {
531            source: specifier,
532            imported_name: ImportedName::SideEffect,
533            local_name: String::new(),
534            is_type_only: false,
535            is_type_only_star: false,
536            from_style: false,
537            span,
538            source_span: span,
539        });
540    }
541}
542
543/// Sort and dedup the per-script import-binding accumulator lists so the merged
544/// SFC module reports each binding once in a stable order.
545fn dedup_import_binding_lists(combined: &mut ModuleInfo) {
546    combined.unused_import_bindings.sort_unstable();
547    combined.unused_import_bindings.dedup();
548    combined.type_referenced_import_bindings.sort_unstable();
549    combined.type_referenced_import_bindings.dedup();
550    combined.value_referenced_import_bindings.sort_unstable();
551    combined.value_referenced_import_bindings.dedup();
552    combined.auto_import_candidates.sort_unstable();
553    combined.auto_import_candidates.dedup();
554}
555
556fn sfc_kind(path: &Path) -> SfcKind {
557    if path.extension().and_then(|ext| ext.to_str()) == Some("vue") {
558        SfcKind::Vue
559    } else {
560        SfcKind::Svelte
561    }
562}
563
564/// SvelteKit route components receive a `data` prop populated by the route's
565/// `load()` return object. This predicate gates the `data`-as-template-root
566/// credit (unused-load-data-key Primitive B) to exactly those files. It matches
567/// `+page.svelte` / `+layout.svelte` AND their layout-reset variants
568/// (`+page@.svelte`, `+page@named.svelte`, `+page@(group).svelte`, and the
569/// `+layout@...` forms), all of which still receive the `data` prop. `+error.svelte`
570/// is excluded (it receives `$page.error`, not the `load()` `data` prop), and a
571/// non-route file like `+pageHelper.svelte` is excluded by the grammar (the part
572/// after `+page` must be empty or start with `@`). The leading `+` is a
573/// SvelteKit-only filename convention, so no ordinary `.svelte` component matches.
574fn is_sveltekit_route_data_component(path: &Path) -> bool {
575    let Some(stem) = path
576        .file_name()
577        .and_then(|name| name.to_str())
578        .and_then(|name| name.strip_suffix(".svelte"))
579    else {
580        return false;
581    };
582    ["+page", "+layout"].iter().any(|prefix| {
583        stem.strip_prefix(prefix)
584            .is_some_and(|rest| rest.is_empty() || rest.starts_with('@'))
585    })
586}
587
588fn empty_sfc_module(file_id: FileId, source: &str, content_hash: u64) -> ModuleInfo {
589    let parsed = crate::suppress_literals::parse_sfc_suppressions(source);
590
591    crate::module_info::non_js_module_info(crate::module_info::NonJsModuleInfoInput {
592        file_id,
593        content_hash,
594        source,
595        parsed_suppressions: parsed,
596        imports: Vec::new(),
597        exports: Vec::new(),
598    })
599}
600
601#[path = "sfc_script_merge.rs"]
602mod script_merge;
603use script_merge::{
604    SfcScriptMergeInput, SharedScopeReferences, credit_shared_scope_references,
605    merge_script_into_module,
606};
607
608/// Compute and merge this script's import-binding usage (unused / type- and
609/// value-referenced) plus auto-import candidates into `combined`. A
610/// `generic="..."` attribute re-parses an augmented body so a type-only import
611/// consumed solely inside the constraint stays classified as type-referenced.
612///
613/// The re-parse recomputes the whole verdict, so it is handed the
614/// `import X = require('./x')` locals as well: those live outside `imports`,
615/// and without them such a binding would keep crediting its target on a
616/// `generic="..."` script while the plain `<script setup>` next to it reports
617/// (issue #2365).
618fn merge_script_binding_usage(
619    input: &mut SfcScriptMergeInput<'_>,
620    allocator: &Allocator,
621    imports: &[ImportInfo],
622    import_equals_bindings: &[String],
623    semantic_usage: crate::parse::SemanticUsage,
624) {
625    let augmented_body = build_generic_attr_probe_source(input.script);
626    let binding_usage = if let Some(augmented) = augmented_body.as_deref() {
627        let augmented_return =
628            Parser::new(allocator, augmented, source_type_for_script(input.script)).parse();
629        let mut probe = compute_import_binding_usage(
630            &augmented_return.program,
631            imports,
632            import_equals_bindings,
633            &FxHashSet::default(),
634        );
635        input
636            .shared_scope_references
637            .record_references(input.kind, &mut probe);
638        probe.import_binding_usage
639    } else {
640        semantic_usage.import_binding_usage
641    };
642    let auto_import_candidates = semantic_usage.auto_import_candidates;
643    crate::parse::append_declaration_merge_facts(
644        &mut input.combined.semantic_facts,
645        semantic_usage.declaration_merges,
646        input.script.byte_offset as u32,
647    );
648    input
649        .combined
650        .unused_import_bindings
651        .extend(binding_usage.unused.iter().cloned());
652    input
653        .combined
654        .type_referenced_import_bindings
655        .extend(binding_usage.type_referenced.iter().cloned());
656    input
657        .combined
658        .value_referenced_import_bindings
659        .extend(binding_usage.value_referenced.iter().cloned());
660    input
661        .combined
662        .auto_import_candidates
663        .extend(auto_import_candidates);
664}
665
666/// Carry an instance script's import locals and binding-target names into the
667/// template-visible sets (dropping empty locals and `this.`-prefixed targets) so
668/// the template scanner can credit them.
669fn harvest_template_visible_bindings(
670    input: &mut SfcScriptMergeInput<'_>,
671    extractor: &ModuleInfoExtractor,
672) {
673    input.template_visible_imports.extend(
674        extractor
675            .imports
676            .iter()
677            .filter(|import| !import.local_name.is_empty())
678            .map(|import| import.local_name.clone()),
679    );
680    input.template_visible_bound_targets.extend(
681        extractor
682            .binding_target_names()
683            .iter()
684            .filter(|(local, _)| !local.starts_with("this."))
685            .filter_map(|(local, target)| {
686                target
687                    .class_name()
688                    .map(|class_name| (local.clone(), class_name.to_string()))
689            }),
690    );
691    // Array / reactive-array binding element classes, so the Vue template
692    // scanner can type a `v-for` loop variable to its source's element class
693    // (issue #1707). `this.`-filtered for parity with bound targets.
694    input.template_visible_iterable_types.extend(
695        extractor
696            .array_binding_element_types()
697            .iter()
698            .filter(|(local, _)| !local.starts_with("this."))
699            .map(|(local, element)| (local.clone(), element.clone())),
700    );
701}
702
703/// Harvest Svelte 5 `$props()` declared props from an instance `<script>`
704/// program into `combined.component_props` (reusing the Vue IR + abstain flags),
705/// remapping each prop's body-relative span onto the SFC source via `byte_offset`.
706fn merge_svelte_props_into(
707    combined: &mut ModuleInfo,
708    program: &oxc_ast::ast::Program<'_>,
709    byte_offset: usize,
710) {
711    let harvest = crate::sfc_props::harvest_svelte_props(program);
712    if harvest.has_unharvestable_props {
713        combined.has_unharvestable_props = true;
714    }
715    if harvest.has_props_attrs_fallthrough {
716        combined.has_props_attrs_fallthrough = true;
717    }
718    for mut prop in harvest.props {
719        prop.span_start += byte_offset as u32;
720        combined.component_props.push(prop);
721    }
722}
723
724/// Harvest Vue prop/emit declarations into `combined`, remapping body-relative
725/// spans onto the SFC source via the script byte offset. The `<script setup>`
726/// path harvests `defineProps` / `defineEmits` (and the `defineExpose` /
727/// `defineModel` abstain flags + return bindings); the non-setup path harvests
728/// the Options API `props:` / `emits:` (same IR, same abstain flags, same remap,
729/// only the harvest source differs).
730fn merge_vue_props_emits_into(
731    input: &mut SfcScriptMergeInput<'_>,
732    program: &oxc_ast::ast::Program<'_>,
733    extractor: &mut ModuleInfoExtractor,
734) {
735    let byte_offset = input.script.byte_offset as u32;
736    if input.script.is_setup {
737        apply_props_harvest(
738            input,
739            crate::sfc_props::harvest_define_props(program),
740            byte_offset,
741            extractor,
742        );
743        apply_emits_harvest(
744            input,
745            crate::sfc_props::harvest_define_emits(program),
746            byte_offset,
747        );
748    } else {
749        apply_props_harvest(
750            input,
751            crate::sfc_props::harvest_options_api_props(program),
752            byte_offset,
753            extractor,
754        );
755        apply_emits_harvest(
756            input,
757            crate::sfc_props::harvest_options_api_emits(program),
758            byte_offset,
759        );
760    }
761}
762
763/// Fold a prop harvest (setup `defineProps` or Options-API `props:`) into
764/// `combined`: copy the abstain flags and `defineProps` return binding, then push
765/// each prop with its span remapped onto the SFC source. The setup-only fields
766/// (`has_define_expose` / `has_define_model` / `props_return_binding`) default to
767/// `false`/`None` in the Options-API harvest, so the shared copy is inert there.
768fn apply_props_harvest(
769    input: &mut SfcScriptMergeInput<'_>,
770    harvest: crate::sfc_props::DefinePropsHarvest,
771    byte_offset: u32,
772    extractor: &mut ModuleInfoExtractor,
773) {
774    if harvest.has_unharvestable_props {
775        input.combined.has_unharvestable_props = true;
776    }
777    if harvest.has_props_attrs_fallthrough {
778        input.combined.has_props_attrs_fallthrough = true;
779    }
780    if harvest.has_define_expose {
781        input.combined.has_define_expose = true;
782    }
783    if harvest.has_define_model {
784        input.combined.has_define_model = true;
785    }
786    if let Some(binding) = harvest.props_return_binding {
787        *input.props_return_binding = Some(binding);
788    }
789    // Record each props array field's element class keyed `props.<field>` into the
790    // visitor's array-binding element-types map (issue #1711). This runs before
791    // `harvest_template_visible_bindings` reads that map into
792    // `template_visible_iterable_types`, so a `v-for="(util) of props.items"`
793    // matches the `"props.items"` key and types `util` to the element class.
794    // Over-credit only: the harvest records a field only when its type resolved
795    // to a non-builtin array element class, so this can never add a finding.
796    for (field_name, element_type) in harvest.props_array_element_types {
797        extractor
798            .array_binding_element_types_mut()
799            .insert(format!("props.{field_name}"), element_type);
800    }
801    for mut prop in harvest.props {
802        prop.span_start += byte_offset;
803        input.combined.component_props.push(prop);
804    }
805}
806
807/// Fold an emit harvest (setup `defineEmits` or Options-API `emits:`) into
808/// `combined`: copy the abstain flags and emit return binding, then push each
809/// emit with its span remapped onto the SFC source. The setup-only fields
810/// (`has_emit_whole_object_use` / `emit_binding`) default to `false`/`None` in
811/// the Options-API harvest, so the shared copy is inert there.
812fn apply_emits_harvest(
813    input: &mut SfcScriptMergeInput<'_>,
814    harvest: crate::sfc_props::DefineEmitsHarvest,
815    byte_offset: u32,
816) {
817    if harvest.has_unharvestable_emits {
818        input.combined.has_unharvestable_emits = true;
819    }
820    if harvest.has_dynamic_emit {
821        input.combined.has_dynamic_emit = true;
822    }
823    if harvest.has_emit_whole_object_use {
824        input.combined.has_emit_whole_object_use = true;
825    }
826    if let Some(binding) = harvest.emit_binding {
827        *input.emit_return_binding = Some(binding);
828    }
829    for mut emit in harvest.emits {
830        emit.span_start += byte_offset;
831        input.combined.component_emits.push(emit);
832    }
833}
834
835/// Score the functions of an SFC `<script>` or an Astro frontmatter
836/// (cyclomatic and cognitive complexity). Each function line and column moves
837/// from the script-body coordinates to the coordinates of the full source file.
838pub(crate) fn translate_script_complexity(
839    script: &SfcScript,
840    program: &oxc_ast::ast::Program<'_>,
841    sfc_line_offsets: &[u32],
842) -> Vec<FunctionComplexity> {
843    let script_line_offsets = compute_line_offsets(&script.body);
844    let mut complexity =
845        crate::complexity::compute_complexity(program, &script.body, &script_line_offsets);
846    let (body_start_line, body_start_col) = byte_offset_to_line_col(
847        sfc_line_offsets,
848        u32::try_from(script.byte_offset).unwrap_or(u32::MAX),
849    );
850
851    for function in &mut complexity {
852        function.line = body_start_line + function.line.saturating_sub(1);
853        if function.line == body_start_line {
854            function.col += body_start_col;
855        }
856    }
857
858    complexity
859}
860
861fn add_script_src_import(module: &mut ModuleInfo, source: &str, source_span: Option<Span>) {
862    let span = source_span.unwrap_or_default();
863    module.imports.push(ImportInfo {
864        source: normalize_asset_url(source),
865        imported_name: ImportedName::SideEffect,
866        local_name: String::new(),
867        is_type_only: false,
868        is_type_only_star: false,
869        from_style: false,
870        span,
871        source_span: span,
872    });
873}
874
875/// `lang` attribute values whose body we know how to scan for `@import` /
876/// `@use` / `@forward` / `@plugin` directives. Plain `<style>` (no `lang`) is treated as
877/// CSS. `less`, `stylus`, and `postcss` bodies are NOT scanned because their
878/// import syntax differs (`@import (reference)` modifiers, etc.); their
879/// `<style src="...">` references are still seeded.
880fn style_lang_is_scss(lang: Option<&str>) -> bool {
881    matches!(lang, Some("scss" | "sass"))
882}
883
884fn style_lang_is_css_like(lang: Option<&str>) -> bool {
885    lang.is_none() || matches!(lang, Some("css"))
886}
887
888fn merge_style_into_module(style: &SfcStyle, combined: &mut ModuleInfo) {
889    if let Some(src) = &style.src {
890        let span = style.src_span.unwrap_or_default();
891        combined.imports.push(ImportInfo {
892            source: normalize_asset_url(src),
893            imported_name: ImportedName::SideEffect,
894            local_name: String::new(),
895            is_type_only: false,
896            is_type_only_star: false,
897            from_style: true,
898            span,
899            source_span: span,
900        });
901    }
902
903    let lang = style.lang.as_deref();
904    let is_scss = style_lang_is_scss(lang);
905    if !is_scss && !style_lang_is_css_like(lang) {
906        return;
907    }
908
909    let masked = crate::css_url::mask_style_block(&style.body, is_scss, combined);
910    for source in crate::css::import_sources_from_masked(&masked, is_scss) {
911        let source_span = Span::new(
912            style.byte_offset as u32 + source.span.start,
913            style.byte_offset as u32 + source.span.end,
914        );
915        combined.imports.push(ImportInfo {
916            source: source.normalized,
917            imported_name: if source.is_plugin {
918                ImportedName::Default
919            } else {
920                ImportedName::SideEffect
921            },
922            local_name: String::new(),
923            is_type_only: false,
924            is_type_only_star: false,
925            from_style: true,
926            span: source_span,
927            source_span,
928        });
929    }
930}
931
932pub(crate) fn source_type_for_script(script: &SfcScript) -> SourceType {
933    source_type_for(script.is_typescript, script.is_jsx)
934}
935
936fn source_type_for(is_typescript: bool, is_jsx: bool) -> SourceType {
937    match (is_typescript, is_jsx) {
938        (true, true) => SourceType::tsx(),
939        (true, false) => SourceType::ts(),
940        (false, true) => SourceType::jsx(),
941        (false, false) => SourceType::mjs(),
942    }
943}
944
945/// Join the inline `<script>` blocks of a Vue or Svelte SFC into one program
946/// source for whole-file binding analysis.
947///
948/// The SFC compilers merge `<script>` and `<script setup>` (Vue) or the module
949/// and instance scripts (Svelte) into one module, so a binding in one block is
950/// visible in the other. Each `generic="..."` constraint is kept as an
951/// unexported type alias, so a type that only the constraint uses still has a
952/// reference. The result uses TypeScript when any block uses TypeScript.
953/// Returns `None` when the SFC has no inline script.
954#[must_use]
955pub fn sfc_merged_script_source(source: &str) -> Option<(String, SourceType)> {
956    let scripts: Vec<SfcScript> = extract_sfc_scripts(source)
957        .into_iter()
958        .filter(|script| script.src.is_none())
959        .collect();
960    if scripts.is_empty() {
961        return None;
962    }
963    let is_typescript = scripts.iter().any(|script| script.is_typescript);
964    let is_jsx = scripts.iter().any(|script| script.is_jsx);
965    let mut merged = String::new();
966    for script in &scripts {
967        let body = build_generic_attr_probe_source(script);
968        merged.push_str(body.as_deref().unwrap_or(&script.body));
969        merged.push_str("\n;\n");
970    }
971    Some((merged, source_type_for(is_typescript, is_jsx)))
972}
973
974/// Build an augmented script body that pins the `generic="..."` constraint as
975/// a synthetic local type alias. The alias is unexported and uses a sentinel
976/// name so it can't collide with user code. Returns `None` when there is no
977/// generic attribute to pin (the common case), so callers fall back to the
978/// raw body without paying for a second parse.
979fn build_generic_attr_probe_source(script: &SfcScript) -> Option<String> {
980    let constraint = script.generic_attr.as_deref()?.trim();
981    if constraint.is_empty() {
982        return None;
983    }
984    Some(format!(
985        "{}\n;type __FALLOW_GENERIC_ATTR_PROBE<{}> = unknown;\n",
986        script.body, constraint,
987    ))
988}
989
990struct TemplateUsageInput<'a> {
991    kind: SfcKind,
992    source: &'a str,
993    template_visible_imports: FxHashSet<String>,
994    template_visible_bound_targets: FxHashMap<String, String>,
995    template_visible_iterable_types: &'a FxHashMap<String, String>,
996    props_return_binding: Option<&'a str>,
997    credit_load_data: bool,
998    combined: &'a mut ModuleInfo,
999}
1000
1001fn apply_template_usage(input: TemplateUsageInput<'_>) {
1002    let TemplateUsageInput {
1003        kind,
1004        source,
1005        template_visible_imports,
1006        template_visible_bound_targets,
1007        template_visible_iterable_types,
1008        props_return_binding,
1009        credit_load_data,
1010        combined,
1011    } = input;
1012    let credited = build_template_credited_set(
1013        template_visible_imports,
1014        props_return_binding,
1015        credit_load_data,
1016        source,
1017        combined,
1018    );
1019    let template_usage = compute_template_usage(
1020        kind,
1021        source,
1022        &credited,
1023        template_visible_bound_targets,
1024        template_visible_iterable_types,
1025        credit_load_data,
1026    );
1027    apply_prop_template_credit(&template_usage, props_return_binding, combined);
1028    merge_template_usage_into_combined(template_usage, combined);
1029}
1030
1031/// Build the set of template-credited names: the template-visible imports plus
1032/// each harvested prop name / destructure local, Vue's implicit `$props`, the
1033/// `defineProps` return binding, and (for SvelteKit route components) the `data`
1034/// load prop. Crediting a prop name against an import is inert. Also sets
1035/// `has_load_data_whole_use` when a route spreads / passes the whole `data` prop.
1036fn build_template_credited_set(
1037    template_visible_imports: FxHashSet<String>,
1038    props_return_binding: Option<&str>,
1039    credit_load_data: bool,
1040    source: &str,
1041    combined: &mut ModuleInfo,
1042) -> FxHashSet<String> {
1043    let mut credited = template_visible_imports;
1044    // unused-load-data-key Primitive B: a SvelteKit route component receives a
1045    // `data` prop populated by the route's `load()` return object. Credit `data`
1046    // as a recognized root so its template member accesses (`data.<key>`) are
1047    // emitted for the cross-file load-data-key join, gated to route components.
1048    if credit_load_data {
1049        credited.insert("data".to_string());
1050        // FP-1: a route component spreading / passing the whole `data` prop in
1051        // markup consumes arbitrary keys opaquely; force the detector to abstain.
1052        if SVELTE_TEMPLATE_DATA_WHOLE_USE_RE.is_match(source) {
1053            combined.has_load_data_whole_use = true;
1054        }
1055    }
1056    if !combined.component_props.is_empty() {
1057        for prop in &combined.component_props {
1058            // Credit both the declared name (Vue exposes props by name in the
1059            // template) and the destructure local (a renamed prop is used via it).
1060            credited.insert(prop.name.clone());
1061            credited.insert(prop.local.clone());
1062        }
1063        // Vue's implicit `$props` whole-props object is always available in a
1064        // template; credit `$props.<name>` member accesses too.
1065        credited.insert("$props".to_string());
1066        if let Some(binding) = props_return_binding {
1067            credited.insert(binding.to_string());
1068        }
1069    }
1070    credited
1071}
1072
1073/// Scan the template for usage of the credited names and bound targets. For a
1074/// SvelteKit route, `data` is dropped from the bound targets so its template
1075/// member accesses stay keyed on `data` (not remapped onto the generated
1076/// `PageData` / `LayoutData` type) for the cross-file load-data join.
1077fn compute_template_usage(
1078    kind: SfcKind,
1079    source: &str,
1080    credited: &FxHashSet<String>,
1081    mut template_visible_bound_targets: FxHashMap<String, String>,
1082    template_visible_iterable_types: &FxHashMap<String, String>,
1083    credit_load_data: bool,
1084) -> crate::template_usage::TemplateUsage {
1085    if credit_load_data {
1086        template_visible_bound_targets.remove("data");
1087    }
1088    collect_template_usage_with_bound_targets(
1089        kind,
1090        source,
1091        credited,
1092        &template_visible_bound_targets,
1093        template_visible_iterable_types,
1094    )
1095}
1096
1097/// Mark each harvested prop `used_in_template` when the template references it by
1098/// bare name (destructure form) or via a `<props>.<name>` / `$props.<name>`
1099/// member access. A bare reference to a custom `defineProps` return binding as a
1100/// whole object means abstain on the whole file (`has_props_attrs_fallthrough`).
1101fn apply_prop_template_credit(
1102    template_usage: &crate::template_usage::TemplateUsage,
1103    props_return_binding: Option<&str>,
1104    combined: &mut ModuleInfo,
1105) {
1106    if !combined.component_props.is_empty() {
1107        let member_used: FxHashSet<&str> = template_usage
1108            .member_accesses
1109            .iter()
1110            .filter(|access| {
1111                access.object == "$props"
1112                    || props_return_binding.is_some_and(|binding| access.object == binding)
1113            })
1114            .map(|access| access.member.as_str())
1115            .collect();
1116        for prop in &mut combined.component_props {
1117            if template_usage.used_bindings.contains(&prop.name)
1118                || template_usage.used_bindings.contains(&prop.local)
1119                || member_used.contains(prop.name.as_str())
1120            {
1121                prop.used_in_template = true;
1122            }
1123        }
1124    }
1125
1126    if let Some(binding) = props_return_binding
1127        && (template_usage.used_bindings.contains(binding)
1128            || template_usage
1129                .whole_object_uses
1130                .iter()
1131                .any(|used| used == binding))
1132    {
1133        combined.has_props_attrs_fallthrough = true;
1134    }
1135}
1136
1137/// Drain the scanned template usage into `combined`: retain unused-import
1138/// bindings the template did not consume, extend member accesses / whole-object
1139/// uses / security sinks, and fold unresolved tag names into auto-import
1140/// candidates (sorted + deduped).
1141fn merge_template_usage_into_combined(
1142    template_usage: crate::template_usage::TemplateUsage,
1143    combined: &mut ModuleInfo,
1144) {
1145    combined
1146        .unused_import_bindings
1147        .retain(|binding| !template_usage.used_bindings.contains(binding));
1148    let mut member_accesses = std::mem::take(&mut combined.member_accesses).to_vec();
1149    member_accesses.extend(template_usage.member_accesses);
1150    combined.member_accesses = member_accesses.into();
1151    let mut whole_object_uses = std::mem::take(&mut combined.whole_object_uses).to_vec();
1152    whole_object_uses.extend(template_usage.whole_object_uses);
1153    combined.whole_object_uses = whole_object_uses.into();
1154    combined
1155        .security_sinks
1156        .extend(template_usage.security_sinks);
1157    if !template_usage.unresolved_tag_names.is_empty() {
1158        let mut names: Vec<String> = template_usage.unresolved_tag_names.into_iter().collect();
1159        names.sort_unstable();
1160        combined.auto_import_candidates.extend(names);
1161        combined.auto_import_candidates.dedup();
1162    }
1163}
1164
1165/// Credit emit events fired from the `<template>` (`@click="emit('close')"`,
1166/// `@click="$emit('remove')"`, `:close="{ onClick: () => emit('close') }"`),
1167/// which the script-only emit usage walk in `harvest_define_emits` cannot see.
1168///
1169/// Scans the template-only region (scripts/styles/comments masked) for
1170/// [`TEMPLATE_EMIT_CALL_RE`]: a call whose callee is the harvested emit binding
1171/// (`emit` / `emits` / whatever it was bound to) or the implicit `$emit` (always
1172/// available in a Vue template regardless of `<script setup>` binding). A
1173/// string-literal first arg credits the matching `ComponentEmit` as used; a
1174/// non-literal first arg (a variable / template-literal) is a dynamic template
1175/// emit whose event is unknowable, so the whole file abstains (`has_dynamic_emit`)
1176/// to preserve the zero-FP doctrine.
1177///
1178/// Over-crediting is the safe direction (it only suppresses a finding), so a
1179/// liberal raw-source scan is intentional here. The scan is byte-safe: the regex
1180/// runs over the `&str` template and only reads captured-group text, never
1181/// slicing at arbitrary byte offsets.
1182fn apply_template_emit_usage(
1183    source: &str,
1184    emit_return_binding: Option<&str>,
1185    combined: &mut ModuleInfo,
1186) {
1187    let masked = mask_non_markup_regions(source);
1188    let mut used: FxHashSet<String> = FxHashSet::default();
1189    let mut dynamic = false;
1190
1191    for caps in TEMPLATE_EMIT_CALL_RE.captures_iter(&masked) {
1192        let Some(callee) = caps.get(1) else {
1193            continue;
1194        };
1195        let callee = callee.as_str();
1196        let is_emit_call =
1197            callee == "$emit" || emit_return_binding.is_some_and(|binding| callee == binding);
1198        if !is_emit_call {
1199            continue;
1200        }
1201        if let Some(event) = caps.get(2).or_else(|| caps.get(3)) {
1202            // String-literal first arg (single- or double-quoted): the event
1203            // name. Credit it as used.
1204            used.insert(event.as_str().to_string());
1205        } else if caps.get(4).is_some() {
1206            // Non-literal first arg (`$emit(someVar)`, `emit(\`x\`)`): the event
1207            // cannot be known. Abstain on the whole file.
1208            dynamic = true;
1209        }
1210    }
1211
1212    if dynamic {
1213        combined.has_dynamic_emit = true;
1214    }
1215    if !used.is_empty() {
1216        for emit in &mut combined.component_emits {
1217            if used.contains(&emit.name) {
1218                emit.used = true;
1219            }
1220        }
1221    }
1222}
1223
1224fn is_template_visible_script(kind: SfcKind, script: &SfcScript) -> bool {
1225    match kind {
1226        SfcKind::Vue => script.is_setup,
1227        SfcKind::Svelte => !script.is_context_module,
1228    }
1229}
1230
1231#[cfg(all(test, not(miri)))]
1232mod tests {
1233    use super::*;
1234    use fallow_types::extract::{
1235        ClassThisMemberAccessFact, ClassThisWholeObjectUseFact, SemanticFactView,
1236    };
1237
1238    #[test]
1239    fn merged_script_source_joins_inline_blocks_as_typescript() {
1240        let source = r#"<script>export const a = 1;</script>
1241<script setup lang="ts" generic="T extends Item">defineProps<{ a: T }>();</script>
1242<script src="./external.ts"></script>"#;
1243        let (merged, source_type) =
1244            sfc_merged_script_source(source).expect("inline scripts give a source");
1245        assert!(source_type.is_typescript());
1246        assert!(merged.contains("export const a = 1;"));
1247        assert!(merged.contains("defineProps<{ a: T }>();"));
1248        assert!(merged.contains("<T extends Item>"));
1249        assert!(!merged.contains("external"));
1250    }
1251
1252    #[test]
1253    fn merged_script_source_is_none_without_inline_script() {
1254        assert!(sfc_merged_script_source("<template><div /></template>").is_none());
1255        assert!(sfc_merged_script_source(r#"<script src="./a.ts"></script>"#).is_none());
1256    }
1257
1258    #[test]
1259    fn is_sfc_file_vue() {
1260        assert!(is_sfc_file(Path::new("App.vue")));
1261    }
1262
1263    #[test]
1264    fn is_sfc_file_svelte() {
1265        assert!(is_sfc_file(Path::new("Counter.svelte")));
1266    }
1267
1268    #[test]
1269    fn is_sfc_file_rejects_ts() {
1270        assert!(!is_sfc_file(Path::new("utils.ts")));
1271    }
1272
1273    #[test]
1274    fn is_sfc_file_rejects_jsx() {
1275        assert!(!is_sfc_file(Path::new("App.jsx")));
1276    }
1277
1278    #[test]
1279    fn is_sfc_file_rejects_astro() {
1280        assert!(!is_sfc_file(Path::new("Layout.astro")));
1281    }
1282
1283    #[test]
1284    fn single_plain_script() {
1285        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1286        assert_eq!(scripts.len(), 1);
1287        assert_eq!(scripts[0].body, "const x = 1;");
1288        assert!(!scripts[0].is_typescript);
1289        assert!(!scripts[0].is_jsx);
1290        assert!(scripts[0].src.is_none());
1291    }
1292
1293    #[test]
1294    fn single_ts_script() {
1295        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x: number = 1;</script>"#);
1296        assert_eq!(scripts.len(), 1);
1297        assert!(scripts[0].is_typescript);
1298        assert!(!scripts[0].is_jsx);
1299    }
1300
1301    #[test]
1302    fn single_tsx_script() {
1303        let scripts = extract_sfc_scripts(r#"<script lang="tsx">const el = <div />;</script>"#);
1304        assert_eq!(scripts.len(), 1);
1305        assert!(scripts[0].is_typescript);
1306        assert!(scripts[0].is_jsx);
1307    }
1308
1309    #[test]
1310    fn single_jsx_script() {
1311        let scripts = extract_sfc_scripts(r#"<script lang="jsx">const el = <div />;</script>"#);
1312        assert_eq!(scripts.len(), 1);
1313        assert!(!scripts[0].is_typescript);
1314        assert!(scripts[0].is_jsx);
1315    }
1316
1317    #[test]
1318    fn two_script_blocks() {
1319        let source = r#"
1320<script lang="ts">
1321export default {};
1322</script>
1323<script setup lang="ts">
1324const count = 0;
1325</script>
1326"#;
1327        let scripts = extract_sfc_scripts(source);
1328        assert_eq!(scripts.len(), 2);
1329        assert!(scripts[0].body.contains("export default"));
1330        assert!(scripts[1].body.contains("count"));
1331    }
1332
1333    #[test]
1334    fn script_setup_extracted() {
1335        let scripts =
1336            extract_sfc_scripts(r#"<script setup lang="ts">import { ref } from 'vue';</script>"#);
1337        assert_eq!(scripts.len(), 1);
1338        assert!(scripts[0].body.contains("import"));
1339        assert!(scripts[0].is_typescript);
1340    }
1341
1342    #[test]
1343    fn script_src_detected() {
1344        let scripts = extract_sfc_scripts(r#"<script src="./component.ts" lang="ts"></script>"#);
1345        assert_eq!(scripts.len(), 1);
1346        assert_eq!(scripts[0].src.as_deref(), Some("./component.ts"));
1347    }
1348
1349    // -- Svelte module-context recognition (W1.1 piece 1) ----------------------
1350
1351    #[test]
1352    fn svelte4_context_module_is_module_context() {
1353        let scripts =
1354            extract_sfc_scripts(r#"<script context="module">export const x = 1;</script>"#);
1355        assert_eq!(scripts.len(), 1);
1356        assert!(scripts[0].is_context_module);
1357    }
1358
1359    #[test]
1360    fn svelte5_bare_module_attr_is_module_context() {
1361        let scripts = extract_sfc_scripts(r"<script module>export const x = 1;</script>");
1362        assert_eq!(scripts.len(), 1);
1363        assert!(scripts[0].is_context_module);
1364    }
1365
1366    #[test]
1367    fn svelte5_module_with_lang_is_module_context() {
1368        let scripts =
1369            extract_sfc_scripts(r#"<script module lang="ts">export const x = 1;</script>"#);
1370        assert_eq!(scripts.len(), 1);
1371        assert!(scripts[0].is_context_module);
1372        assert!(scripts[0].is_typescript);
1373    }
1374
1375    #[test]
1376    fn plain_script_is_not_module_context() {
1377        let scripts = extract_sfc_scripts(r"<script>const x = 1;</script>");
1378        assert_eq!(scripts.len(), 1);
1379        assert!(!scripts[0].is_context_module);
1380    }
1381
1382    #[test]
1383    fn lang_ts_script_is_not_module_context() {
1384        let scripts = extract_sfc_scripts(r#"<script lang="ts">const x = 1;</script>"#);
1385        assert_eq!(scripts.len(), 1);
1386        assert!(!scripts[0].is_context_module);
1387    }
1388
1389    #[test]
1390    fn data_module_attr_is_not_module_context() {
1391        // The `(?:^|\s)module(?:\s|$|=)` anchor must not match `data-module`.
1392        let scripts =
1393            extract_sfc_scripts(r#"<script data-module="x" lang="ts">const x = 1;</script>"#);
1394        assert_eq!(scripts.len(), 1);
1395        assert!(!scripts[0].is_context_module);
1396    }
1397
1398    #[test]
1399    fn bare_module_script_is_not_template_visible() {
1400        // AC-2: a bare `<script module>` is scoped as module context, so its
1401        // imports are NOT credited as template-visible (matching `context="module"`).
1402        let module_script = SfcScript {
1403            body: String::new(),
1404            is_typescript: false,
1405            is_jsx: false,
1406            byte_offset: 0,
1407            src: None,
1408            src_span: None,
1409            is_setup: false,
1410            is_context_module: true,
1411            generic_attr: None,
1412        };
1413        assert!(!is_template_visible_script(SfcKind::Svelte, &module_script));
1414        let instance_script = SfcScript {
1415            is_context_module: false,
1416            ..module_script
1417        };
1418        assert!(is_template_visible_script(
1419            SfcKind::Svelte,
1420            &instance_script
1421        ));
1422    }
1423
1424    #[test]
1425    fn data_src_not_treated_as_src() {
1426        let scripts =
1427            extract_sfc_scripts(r#"<script lang="ts" data-src="./nope.ts">const x = 1;</script>"#);
1428        assert_eq!(scripts.len(), 1);
1429        assert!(scripts[0].src.is_none());
1430    }
1431
1432    #[test]
1433    fn script_inside_html_comment_filtered() {
1434        let source = r#"
1435<!-- <script lang="ts">import { bad } from 'bad';</script> -->
1436<script lang="ts">import { good } from 'good';</script>
1437"#;
1438        let scripts = extract_sfc_scripts(source);
1439        assert_eq!(scripts.len(), 1);
1440        assert!(scripts[0].body.contains("good"));
1441    }
1442
1443    #[test]
1444    fn spanning_comment_filters_script() {
1445        let source = r#"
1446<!-- disabled:
1447<script lang="ts">import { bad } from 'bad';</script>
1448-->
1449<script lang="ts">const ok = true;</script>
1450"#;
1451        let scripts = extract_sfc_scripts(source);
1452        assert_eq!(scripts.len(), 1);
1453        assert!(scripts[0].body.contains("ok"));
1454    }
1455
1456    #[test]
1457    fn string_containing_comment_markers_not_corrupted() {
1458        let source = r#"
1459<script setup lang="ts">
1460const marker = "<!-- not a comment -->";
1461import { ref } from 'vue';
1462</script>
1463"#;
1464        let scripts = extract_sfc_scripts(source);
1465        assert_eq!(scripts.len(), 1);
1466        assert!(scripts[0].body.contains("import"));
1467    }
1468
1469    #[test]
1470    fn generic_attr_with_angle_bracket() {
1471        let source =
1472            r#"<script setup lang="ts" generic="T extends Foo<Bar>">const x = 1;</script>"#;
1473        let scripts = extract_sfc_scripts(source);
1474        assert_eq!(scripts.len(), 1);
1475        assert_eq!(scripts[0].body, "const x = 1;");
1476    }
1477
1478    #[test]
1479    fn nested_generic_attr() {
1480        let source = r#"<script setup lang="ts" generic="T extends Map<string, Set<number>>">const x = 1;</script>"#;
1481        let scripts = extract_sfc_scripts(source);
1482        assert_eq!(scripts.len(), 1);
1483        assert_eq!(scripts[0].body, "const x = 1;");
1484    }
1485
1486    #[test]
1487    fn lang_single_quoted() {
1488        let scripts = extract_sfc_scripts("<script lang='ts'>const x = 1;</script>");
1489        assert_eq!(scripts.len(), 1);
1490        assert!(scripts[0].is_typescript);
1491    }
1492
1493    #[test]
1494    fn uppercase_script_tag() {
1495        let scripts = extract_sfc_scripts(r#"<SCRIPT lang="ts">const x = 1;</SCRIPT>"#);
1496        assert_eq!(scripts.len(), 1);
1497        assert!(scripts[0].is_typescript);
1498    }
1499
1500    #[test]
1501    fn no_script_block() {
1502        let scripts = extract_sfc_scripts("<template><div>Hello</div></template>");
1503        assert!(scripts.is_empty());
1504    }
1505
1506    #[test]
1507    fn empty_script_body() {
1508        let scripts = extract_sfc_scripts(r#"<script lang="ts"></script>"#);
1509        assert_eq!(scripts.len(), 1);
1510        assert!(scripts[0].body.is_empty());
1511    }
1512
1513    #[test]
1514    fn whitespace_only_script() {
1515        let scripts = extract_sfc_scripts("<script lang=\"ts\">\n  \n</script>");
1516        assert_eq!(scripts.len(), 1);
1517        assert!(scripts[0].body.trim().is_empty());
1518    }
1519
1520    #[test]
1521    fn byte_offset_is_set() {
1522        let source = r#"<template><div/></template><script lang="ts">code</script>"#;
1523        let scripts = extract_sfc_scripts(source);
1524        assert_eq!(scripts.len(), 1);
1525        let offset = scripts[0].byte_offset;
1526        assert_eq!(&source[offset..offset + 4], "code");
1527    }
1528
1529    #[test]
1530    fn script_with_extra_attributes() {
1531        let scripts = extract_sfc_scripts(
1532            r#"<script lang="ts" id="app" type="module" data-custom="val">const x = 1;</script>"#,
1533        );
1534        assert_eq!(scripts.len(), 1);
1535        assert!(scripts[0].is_typescript);
1536        assert!(scripts[0].src.is_none());
1537    }
1538
1539    #[test]
1540    fn multiple_script_blocks_exports_combined() {
1541        let source = r#"
1542<script lang="ts">
1543export const version = '1.0';
1544</script>
1545<script setup lang="ts">
1546import { ref } from 'vue';
1547const count = ref(0);
1548</script>
1549"#;
1550        let info = parse_sfc_to_module(FileId(0), Path::new("Dual.vue"), source, 0, false);
1551        assert!(
1552            info.exports
1553                .iter()
1554                .any(|e| matches!(&e.name, crate::ExportName::Named(n) if n == "version")),
1555            "export from <script> block should be extracted"
1556        );
1557        assert!(
1558            info.imports.iter().any(|i| i.source == "vue"),
1559            "import from <script setup> block should be extracted"
1560        );
1561    }
1562
1563    #[test]
1564    fn class_this_facts_survive_sfc_script_merge() {
1565        let source = r#"
1566<script lang="ts">
1567export class Service {
1568    client!: Client;
1569
1570    run() {
1571        this.client.execute();
1572        Object.keys(this.client);
1573    }
1574}
1575</script>
1576"#;
1577        let info = parse_sfc_to_module(FileId(0), Path::new("Service.vue"), source, 0, false);
1578        let facts = SemanticFactView::new(&info.semantic_facts, &info.member_accesses);
1579
1580        assert_eq!(
1581            facts.class_this_member_accesses(),
1582            vec![ClassThisMemberAccessFact {
1583                class_local_name: "Service".to_string(),
1584                object: "this.client".to_string(),
1585                member: "execute".to_string(),
1586            }]
1587        );
1588        assert_eq!(
1589            facts.class_this_whole_object_uses(),
1590            vec![ClassThisWholeObjectUseFact {
1591                class_local_name: "Service".to_string(),
1592                object: "this.client".to_string(),
1593            }]
1594        );
1595    }
1596
1597    #[test]
1598    fn lang_tsx_detected_as_typescript_jsx() {
1599        let scripts =
1600            extract_sfc_scripts(r#"<script lang="tsx">const el = <div>{x}</div>;</script>"#);
1601        assert_eq!(scripts.len(), 1);
1602        assert!(scripts[0].is_typescript, "lang=tsx should be typescript");
1603        assert!(scripts[0].is_jsx, "lang=tsx should be jsx");
1604    }
1605
1606    #[test]
1607    fn multiline_html_comment_filters_all_script_blocks_inside() {
1608        let source = r#"
1609<!--
1610  This whole section is disabled:
1611  <script lang="ts">import { bad1 } from 'bad1';</script>
1612  <script lang="ts">import { bad2 } from 'bad2';</script>
1613-->
1614<script lang="ts">import { good } from 'good';</script>
1615"#;
1616        let scripts = extract_sfc_scripts(source);
1617        assert_eq!(scripts.len(), 1);
1618        assert!(scripts[0].body.contains("good"));
1619    }
1620
1621    #[test]
1622    fn script_src_generates_side_effect_import() {
1623        let info = parse_sfc_to_module(
1624            FileId(0),
1625            Path::new("External.vue"),
1626            r#"<script src="./external-logic.ts" lang="ts"></script>"#,
1627            0,
1628            false,
1629        );
1630        assert!(
1631            info.imports
1632                .iter()
1633                .any(|i| i.source == "./external-logic.ts"
1634                    && matches!(i.imported_name, ImportedName::SideEffect)),
1635            "script src should generate a side-effect import"
1636        );
1637    }
1638
1639    #[test]
1640    fn parse_sfc_no_script_returns_empty_module() {
1641        let info = parse_sfc_to_module(
1642            FileId(0),
1643            Path::new("Empty.vue"),
1644            "<template><div>Hello</div></template>",
1645            42,
1646            false,
1647        );
1648        assert!(info.imports.is_empty());
1649        assert!(info.exports.is_empty());
1650        assert_eq!(info.content_hash, 42);
1651        assert_eq!(info.file_id, FileId(0));
1652    }
1653
1654    #[test]
1655    fn parse_sfc_has_line_offsets() {
1656        let info = parse_sfc_to_module(
1657            FileId(0),
1658            Path::new("LineOffsets.vue"),
1659            r#"<script lang="ts">const x = 1;</script>"#,
1660            0,
1661            false,
1662        );
1663        assert!(!info.line_offsets.is_empty());
1664    }
1665
1666    #[test]
1667    fn parse_sfc_has_suppressions() {
1668        let info = parse_sfc_to_module(
1669            FileId(0),
1670            Path::new("Suppressions.vue"),
1671            r#"<script lang="ts">
1672// fallow-ignore-file
1673export const foo = 1;
1674</script>"#,
1675            0,
1676            false,
1677        );
1678        assert!(!info.suppressions.is_empty());
1679    }
1680
1681    #[test]
1682    fn source_type_plain_js_detection() {
1683        let scripts = extract_sfc_scripts("<script>const x = 1;</script>");
1684        assert_eq!(scripts.len(), 1);
1685        assert!(!scripts[0].is_typescript);
1686        assert!(!scripts[0].is_jsx);
1687    }
1688
1689    #[test]
1690    fn is_sfc_file_rejects_no_extension() {
1691        assert!(!is_sfc_file(Path::new("Makefile")));
1692    }
1693
1694    #[test]
1695    fn is_sfc_file_rejects_mdx() {
1696        assert!(!is_sfc_file(Path::new("post.mdx")));
1697    }
1698
1699    #[test]
1700    fn is_sfc_file_rejects_css() {
1701        assert!(!is_sfc_file(Path::new("styles.css")));
1702    }
1703
1704    #[test]
1705    fn multiple_script_blocks_both_have_offsets() {
1706        let source = r#"<script lang="ts">const a = 1;</script>
1707<script setup lang="ts">const b = 2;</script>"#;
1708        let scripts = extract_sfc_scripts(source);
1709        assert_eq!(scripts.len(), 2);
1710        let offset0 = scripts[0].byte_offset;
1711        let offset1 = scripts[1].byte_offset;
1712        assert_eq!(
1713            &source[offset0..offset0 + "const a = 1;".len()],
1714            "const a = 1;"
1715        );
1716        assert_eq!(
1717            &source[offset1..offset1 + "const b = 2;".len()],
1718            "const b = 2;"
1719        );
1720    }
1721
1722    #[test]
1723    fn script_with_src_and_lang() {
1724        let scripts = extract_sfc_scripts(r#"<script src="./logic.ts" lang="tsx"></script>"#);
1725        assert_eq!(scripts.len(), 1);
1726        assert_eq!(scripts[0].src.as_deref(), Some("./logic.ts"));
1727        assert!(scripts[0].is_typescript);
1728        assert!(scripts[0].is_jsx);
1729    }
1730
1731    #[test]
1732    fn extract_style_block_lang_scss() {
1733        let source = r#"<template/><style lang="scss">@import 'Foo';</style>"#;
1734        let styles = extract_sfc_styles(source);
1735        assert_eq!(styles.len(), 1);
1736        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1737        assert!(styles[0].body.contains("@import"));
1738        assert!(styles[0].src.is_none());
1739    }
1740
1741    #[test]
1742    fn extract_style_block_with_src() {
1743        let source = r#"<style src="./theme.scss" lang="scss"></style>"#;
1744        let styles = extract_sfc_styles(source);
1745        assert_eq!(styles.len(), 1);
1746        assert_eq!(styles[0].src.as_deref(), Some("./theme.scss"));
1747        assert_eq!(styles[0].lang.as_deref(), Some("scss"));
1748    }
1749
1750    #[test]
1751    fn extract_style_block_plain_no_lang() {
1752        let source = r"<style>.foo { color: red; }</style>";
1753        let styles = extract_sfc_styles(source);
1754        assert_eq!(styles.len(), 1);
1755        assert!(styles[0].lang.is_none());
1756    }
1757
1758    #[test]
1759    fn extract_multiple_style_blocks() {
1760        let source = r#"<style lang="scss">@import 'a';</style>
1761<style scoped lang="scss">@import 'b';</style>"#;
1762        let styles = extract_sfc_styles(source);
1763        assert_eq!(styles.len(), 2);
1764    }
1765
1766    #[test]
1767    fn style_block_inside_html_comment_filtered() {
1768        let source = r#"<!-- <style lang="scss">@import 'bad';</style> -->
1769<style lang="scss">@import 'good';</style>"#;
1770        let styles = extract_sfc_styles(source);
1771        assert_eq!(styles.len(), 1);
1772        assert!(styles[0].body.contains("good"));
1773    }
1774
1775    #[test]
1776    fn parse_sfc_extracts_style_imports_with_from_style_flag() {
1777        let info = parse_sfc_to_module(
1778            FileId(0),
1779            Path::new("Foo.vue"),
1780            r#"<template/><style lang="scss">@import 'Foo';</style>"#,
1781            0,
1782            false,
1783        );
1784        let style_import = info
1785            .imports
1786            .iter()
1787            .find(|i| i.source == "./Foo")
1788            .expect("scss @import 'Foo' should be normalized to ./Foo");
1789        assert!(
1790            style_import.from_style,
1791            "imports from <style> blocks must carry from_style=true so the resolver \
1792             enables SCSS partial fallback for the SFC importer"
1793        );
1794        assert!(matches!(
1795            style_import.imported_name,
1796            ImportedName::SideEffect
1797        ));
1798    }
1799
1800    #[test]
1801    fn parse_sfc_extracts_style_plugin_as_default_import() {
1802        let info = parse_sfc_to_module(
1803            FileId(0),
1804            Path::new("Foo.vue"),
1805            r#"<template/><style>@plugin "./tailwind-plugin.js";</style>"#,
1806            0,
1807            false,
1808        );
1809        let plugin_import = info
1810            .imports
1811            .iter()
1812            .find(|i| i.source == "./tailwind-plugin.js")
1813            .expect("style @plugin should create an import");
1814        assert!(plugin_import.from_style);
1815        assert!(matches!(plugin_import.imported_name, ImportedName::Default));
1816    }
1817
1818    #[test]
1819    fn parse_sfc_extracts_style_src_with_from_style_flag() {
1820        let info = parse_sfc_to_module(
1821            FileId(0),
1822            Path::new("Bar.vue"),
1823            r#"<style src="./Bar.scss" lang="scss"></style>"#,
1824            0,
1825            false,
1826        );
1827        let style_src = info
1828            .imports
1829            .iter()
1830            .find(|i| i.source == "./Bar.scss")
1831            .expect("<style src=\"./Bar.scss\"> should produce a side-effect import");
1832        assert!(style_src.from_style);
1833    }
1834
1835    #[test]
1836    fn parse_sfc_skips_unsupported_style_lang_body_but_keeps_src() {
1837        let info = parse_sfc_to_module(
1838            FileId(0),
1839            Path::new("Baz.vue"),
1840            r#"<style lang="postcss" src="./Baz.pcss">@custom-rule "skipped";</style>"#,
1841            0,
1842            false,
1843        );
1844        assert!(
1845            info.imports.iter().any(|i| i.source == "./Baz.pcss"),
1846            "src reference should still be seeded for unsupported lang"
1847        );
1848        assert!(
1849            !info.imports.iter().any(|i| i.source.contains("skipped")),
1850            "postcss body should not be scanned for @import directives"
1851        );
1852    }
1853
1854    fn asset_refs(source: &str) -> Vec<String> {
1855        super::collect_template_asset_refs(source)
1856            .into_iter()
1857            .map(|(s, _)| s)
1858            .collect()
1859    }
1860
1861    #[test]
1862    fn captures_static_relative_template_asset_refs() {
1863        assert_eq!(
1864            asset_refs(r#"<template><img src="./logo.png" /></template>"#),
1865            vec!["./logo.png".to_string()]
1866        );
1867        assert_eq!(
1868            asset_refs(r#"<source src="../media/clip.mp4">"#),
1869            vec!["../media/clip.mp4".to_string()]
1870        );
1871        assert_eq!(
1872            asset_refs(r#"<video poster="./thumb.jpg"></video>"#),
1873            vec!["./thumb.jpg".to_string()]
1874        );
1875    }
1876
1877    #[test]
1878    fn skips_dynamic_alias_root_remote_and_query_asset_refs() {
1879        // Dynamic bindings (Vue `:src`, `v-bind:src`, Svelte `bind:src` / `src={}`).
1880        assert!(asset_refs(r#"<img :src="logo" />"#).is_empty());
1881        assert!(asset_refs(r#"<img v-bind:src="logo" />"#).is_empty());
1882        assert!(asset_refs(r#"<img bind:src="logo" />"#).is_empty());
1883        assert!(asset_refs(r"<img src={logo} />").is_empty());
1884        assert!(asset_refs(r#"<img data-src="./x.png" />"#).is_empty());
1885        // Alias-prefixed, root-relative, remote, bare: not plain relative literals.
1886        assert!(asset_refs(r#"<img src="@/assets/x.png" />"#).is_empty());
1887        assert!(asset_refs(r#"<img src="/logo.png" />"#).is_empty());
1888        assert!(asset_refs(r#"<img src="https://cdn/x.png" />"#).is_empty());
1889        // Query / hash suffix abstains (the resolver cannot verify them).
1890        assert!(asset_refs(r#"<img src="./x.png?inline" />"#).is_empty());
1891        // Interpolated value abstains.
1892        assert!(asset_refs(r#"<img src="{{ logo }}" />"#).is_empty());
1893    }
1894
1895    #[test]
1896    fn skips_custom_component_src_prop() {
1897        // A custom component's `src` PROP must never be read as an asset edge.
1898        assert!(asset_refs(r#"<MyImage src="./x.png" />"#).is_empty());
1899        assert!(asset_refs(r#"<AppIcon src="../icons/y.svg" />"#).is_empty());
1900    }
1901
1902    #[test]
1903    fn skips_asset_refs_inside_script_style_and_comments() {
1904        // Masked regions must not contribute asset refs.
1905        assert!(asset_refs(r#"<script>const x = "<img src='./a.png'>"</script>"#).is_empty());
1906        assert!(asset_refs(r#"<style>/* <img src="./b.png"> */ .x{}</style>"#).is_empty());
1907        assert!(asset_refs(r#"<!-- <img src="./c.png" /> -->"#).is_empty());
1908    }
1909
1910    #[test]
1911    fn parse_sfc_emits_template_asset_as_side_effect_import() {
1912        let info = parse_sfc_to_module(
1913            FileId(0),
1914            Path::new("Hero.vue"),
1915            r#"<template><img src="./hero.png" /></template><script>let x=1</script>"#,
1916            0,
1917            false,
1918        );
1919        assert!(
1920            info.imports.iter().any(|i| i.source == "./hero.png"
1921                && matches!(i.imported_name, ImportedName::SideEffect)
1922                && !i.from_style),
1923            "template <img src> should seed a SideEffect import: {:?}",
1924            info.imports
1925        );
1926    }
1927
1928    // -- Svelte 5 `$props()` rune harvest (W1.1 piece 2) -----------------------
1929
1930    fn svelte_props(source: &str) -> Vec<crate::ModuleInfo> {
1931        vec![parse_sfc_to_module(
1932            FileId(0),
1933            Path::new("Component.svelte"),
1934            source,
1935            0,
1936            false,
1937        )]
1938    }
1939
1940    fn prop_names(info: &crate::ModuleInfo) -> Vec<String> {
1941        let mut names: Vec<String> = info
1942            .component_props
1943            .iter()
1944            .map(|p| p.name.clone())
1945            .collect();
1946        names.sort();
1947        names
1948    }
1949
1950    #[test]
1951    fn svelte_shorthand_props_harvested() {
1952        // AC-3: `let { a, b } = $props()` harvests `a`, `b` with `local == name`.
1953        let info = &svelte_props(r"<script>let { a, b } = $props();</script>")[0];
1954        assert_eq!(prop_names(info), vec!["a", "b"]);
1955        for prop in &info.component_props {
1956            assert_eq!(prop.local, prop.name);
1957        }
1958    }
1959
1960    #[test]
1961    fn svelte_renamed_prop_tracks_local_and_script_use() {
1962        // AC-4: `let { a: alias } = $props()` harvests `a` with `local == "alias"`,
1963        // and a reference to `alias` sets `used_in_script` for prop `a`.
1964        let info =
1965            &svelte_props(r"<script>let { a: alias } = $props(); console.log(alias);</script>")[0];
1966        assert_eq!(prop_names(info), vec!["a"]);
1967        let prop = &info.component_props[0];
1968        assert_eq!(prop.local, "alias");
1969        assert!(
1970            prop.used_in_script,
1971            "alias is referenced, so a is used in script"
1972        );
1973    }
1974
1975    #[test]
1976    fn svelte_unreferenced_prop_is_unused_in_script() {
1977        let info = &svelte_props(r"<script>let { a } = $props();</script>")[0];
1978        assert_eq!(prop_names(info), vec!["a"]);
1979        assert!(!info.component_props[0].used_in_script);
1980    }
1981
1982    #[test]
1983    fn svelte_default_prop_peeled() {
1984        // AC-5: `let { a = 1 } = $props()` harvests `a` (default peeled).
1985        let info = &svelte_props(r"<script>let { a = 1 } = $props();</script>")[0];
1986        assert_eq!(prop_names(info), vec!["a"]);
1987    }
1988
1989    #[test]
1990    fn svelte_bindable_default_peeled() {
1991        // The bindable form `let { a = $bindable() } = $props()`: `a` is still a
1992        // declared prop (the default value is irrelevant to the local name).
1993        let info = &svelte_props(r"<script>let { a = $bindable() } = $props();</script>")[0];
1994        assert_eq!(prop_names(info), vec!["a"]);
1995    }
1996
1997    #[test]
1998    fn svelte_rest_element_sets_fallthrough_abstain() {
1999        // AC-6: `let { a, ...rest } = $props()` sets has_props_attrs_fallthrough.
2000        let info = &svelte_props(r"<script>let { a, ...rest } = $props();</script>")[0];
2001        assert!(info.has_props_attrs_fallthrough);
2002    }
2003
2004    #[test]
2005    fn svelte_bare_identifier_binding_sets_unharvestable_abstain() {
2006        // AC-7: `let p = $props()` (no destructure) sets has_unharvestable_props.
2007        let info = &svelte_props(r"<script>let p = $props(); console.log(p.x);</script>")[0];
2008        assert!(info.has_unharvestable_props);
2009        assert!(info.component_props.is_empty());
2010    }
2011
2012    #[test]
2013    fn svelte_nested_destructure_sets_unharvestable_abstain() {
2014        // A nested destructure (`{ a: { x } }`) cannot be flattened. Abstain.
2015        let info = &svelte_props(r"<script>let { a: { x } } = $props();</script>")[0];
2016        assert!(info.has_unharvestable_props);
2017    }
2018
2019    #[test]
2020    fn svelte_prop_used_only_in_markup_credited_as_template_root() {
2021        // AC-8: a prop used only in markup (`{a}`) is credited via
2022        // `apply_template_usage`, so `used_in_template` is set (parity with Vue).
2023        let info = &svelte_props(r"<script>let { a } = $props();</script><p>{a}</p>")[0];
2024        assert_eq!(prop_names(info), vec!["a"]);
2025        assert!(
2026            info.component_props[0].used_in_template,
2027            "a is used in markup, so used_in_template should be true"
2028        );
2029    }
2030
2031    #[test]
2032    fn svelte_module_script_props_not_harvested() {
2033        // `$props()` is instance-only; a module-context script must not harvest.
2034        let info = &svelte_props(
2035            r"<script module>let { a } = $props();</script><script>let { b } = $props();</script>",
2036        )[0];
2037        // Only the instance script's `b` is harvested.
2038        assert_eq!(prop_names(info), vec!["b"]);
2039    }
2040
2041    // -- Svelte custom-event dispatch harvest (unused-svelte-event) ------------
2042
2043    fn dispatched_names(info: &crate::ModuleInfo) -> Vec<String> {
2044        let mut names: Vec<String> = info
2045            .svelte_dispatched_events
2046            .iter()
2047            .map(|e| e.name.clone())
2048            .collect();
2049        names.sort();
2050        names
2051    }
2052
2053    #[test]
2054    fn svelte_dispatch_literal_event_is_harvested() {
2055        let info = &svelte_props(
2056            r"<script>import { createEventDispatcher } from 'svelte';
2057              const dispatch = createEventDispatcher();
2058              function save() { dispatch('save'); }</script>",
2059        )[0];
2060        assert_eq!(dispatched_names(info), vec!["save"]);
2061        assert!(!info.has_dynamic_dispatch);
2062    }
2063
2064    #[test]
2065    fn svelte_dispatch_without_svelte_import_is_ignored() {
2066        // A local `createEventDispatcher` not imported from `svelte` is not a
2067        // dispatcher; the `dispatch('save')` call records nothing.
2068        let info = &svelte_props(
2069            r"<script>function createEventDispatcher() { return () => {}; }
2070              const dispatch = createEventDispatcher();
2071              dispatch('save');</script>",
2072        )[0];
2073        assert!(info.svelte_dispatched_events.is_empty());
2074    }
2075
2076    #[test]
2077    fn svelte_dynamic_dispatch_sets_abstain() {
2078        let info = &svelte_props(
2079            r"<script>import { createEventDispatcher } from 'svelte';
2080              const dispatch = createEventDispatcher();
2081              function fire(name) { dispatch(name); }</script>",
2082        )[0];
2083        assert!(
2084            info.has_dynamic_dispatch,
2085            "a non-literal dispatch arg must set the abstain flag"
2086        );
2087    }
2088
2089    #[test]
2090    fn svelte_dispatch_whole_value_use_sets_abstain() {
2091        let info = &svelte_props(
2092            r"<script>import { createEventDispatcher } from 'svelte';
2093              const dispatch = createEventDispatcher();
2094              forward(dispatch);</script>",
2095        )[0];
2096        assert!(
2097            info.has_dynamic_dispatch,
2098            "passing the dispatch binding as a whole value must set the abstain flag"
2099        );
2100    }
2101
2102    #[test]
2103    fn svelte_listened_event_on_component_is_harvested() {
2104        let info =
2105            &svelte_props(r"<script>import Child from './Child.svelte';</script><Child on:save />")
2106                [0];
2107        assert!(info.svelte_listened_events.contains(&"save".to_string()));
2108    }
2109}
2110
2111fn apply_component_contracts(kind: SfcKind, source: &str, combined: &mut ModuleInfo) {
2112    let framework = match kind {
2113        SfcKind::Vue => fallow_types::extract::ComponentFramework::Vue,
2114        SfcKind::Svelte => fallow_types::extract::ComponentFramework::Svelte,
2115    };
2116    let callers = crate::sfc_template::component_contracts::collect(
2117        &mask_non_markup_regions(source),
2118        &combined.imports,
2119        framework,
2120        0,
2121        combined
2122            .component_contracts
2123            .as_deref()
2124            .map_or(&[], |facts| facts.spread_bindings.as_slice()),
2125        combined
2126            .component_contracts
2127            .as_deref()
2128            .map_or(&[], |facts| facts.aliases.as_slice()),
2129    );
2130    crate::component_contracts::merge(&mut combined.component_contracts, callers, 0, None);
2131    if let Some(facts) = &mut combined.component_contracts {
2132        let credited: FxHashSet<String> = facts
2133            .declarations
2134            .iter()
2135            .flat_map(|prop| [prop.local.clone(), prop.name.clone()])
2136            .collect();
2137        let usage = collect_template_usage_with_bound_targets(
2138            kind,
2139            source,
2140            &credited,
2141            &FxHashMap::default(),
2142            &FxHashMap::default(),
2143        );
2144        for declaration in &mut facts.declarations {
2145            declaration.is_used |= usage.used_bindings.contains(&declaration.local)
2146                || usage.member_accesses.iter().any(|access| {
2147                    access.object == declaration.local && access.member == declaration.name
2148                });
2149        }
2150    }
2151    if let Some(facts) = &mut combined.component_contracts {
2152        for declaration in &mut facts.declarations {
2153            if let Some(prop) = combined
2154                .component_props
2155                .iter()
2156                .find(|prop| prop.name == declaration.name)
2157            {
2158                declaration.is_used |= prop.used_in_template;
2159            }
2160            declaration.incomplete |= combined.has_props_attrs_fallthrough
2161                || combined.has_define_expose
2162                || combined.has_define_model;
2163        }
2164    }
2165
2166    crate::component_contracts::attach_sfc_default_export(combined);
2167}