Skip to main content

fallow_extract/
css.rs

1//! CSS/SCSS file parsing and CSS Module class name extraction.
2//!
3//! Handles `@import`, `@use`, `@forward`, `@plugin`, `@apply`, `@tailwind` directives,
4//! and extracts class names as named exports from `.module.css`/`.module.scss` files.
5//!
6//! Extraction is a deliberate hybrid, not a half-finished migration. lightningcss
7//! owns the membership decision for standard CSS (which `.token` occurrences are
8//! genuine class selectors, via `lightningcss_class_set`); the regex scanners own
9//! span location and the entire SCSS path. lightningcss parses standard CSS only,
10//! not SCSS syntax (`@use`, `@forward`, `//` line comments, `$variables`), so SCSS
11//! files are gated away from the parser and the regex chain stays as permanent
12//! infrastructure rather than a transitional step toward an all-parser tokenizer.
13
14use std::path::Path;
15use std::sync::LazyLock;
16
17use lightningcss::rules::CssRule;
18use lightningcss::selector::{Component, PseudoClass, Selector, SelectorList};
19use lightningcss::stylesheet::{ParserOptions, StyleSheet};
20use oxc_span::Span;
21use rustc_hash::FxHashSet;
22
23use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
24use fallow_types::discover::FileId;
25
26/// Regex to extract CSS @import sources.
27/// Matches: @import "path"; @import 'path'; @import url("path"); @import url('path'); @import url(path);
28static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
29    crate::static_regex(
30        r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
31    )
32});
33
34/// Regex to extract SCSS @use and @forward sources.
35/// Matches: @use "path"; @use 'path'; @forward "path"; @forward 'path';
36static SCSS_USE_RE: LazyLock<regex::Regex> =
37    LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
38
39/// Regex to extract Tailwind CSS @plugin sources.
40/// Matches: @plugin "package"; @plugin 'package'; @plugin "./local-plugin.js";
41static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
42    LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
43
44/// Regex to extract @apply class references.
45/// Matches: @apply class1 class2 class3;
46static CSS_APPLY_RE: LazyLock<regex::Regex> =
47    LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
48
49/// Regex to extract @tailwind directives.
50/// Matches: @tailwind base; @tailwind components; @tailwind utilities;
51static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
52    LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
53
54/// Regex to match CSS block comments (`/* ... */`) for stripping before extraction.
55static CSS_COMMENT_RE: LazyLock<regex::Regex> =
56    LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
57
58/// Regex to match SCSS single-line comments (`// ...`) for stripping before extraction.
59static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
60    LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
61
62/// Regex to extract CSS class names from selectors.
63/// Matches `.className` in selectors. Applied after stripping comments, strings, and URLs.
64static CSS_CLASS_RE: LazyLock<regex::Regex> =
65    LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
66
67/// Regex to strip quoted strings and `url(...)` content from CSS before class extraction.
68/// Prevents false positives from `content: ".foo"` and `url(./path/file.ext)`.
69static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
70    LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
71
72/// Regex to strip the prelude of `@layer` and `@import` at-rules before
73/// CSS-Modules class extraction. Matches the `@keyword` plus everything up to
74/// (but not including) the next `;` or `{`, so block bodies are preserved.
75///
76/// Narrow allowlist by design (issue #540): only at-rules whose preludes
77/// legitimately carry dot-separated identifiers without selector semantics are
78/// stripped. `@layer foo.bar` (CSS Cascading & Inheritance L5) lists layer
79/// names; `@import url("x.css") layer(theme.button)` carries a parenthesised
80/// layer reference. `@scope (.foo) to (.bar)` keeps its existing behavior
81/// because the prelude IS a selector list and `.foo` / `.bar` are real class
82/// references that the user may want to surface as exports.
83static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
84    LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
85
86pub(crate) fn is_css_file(path: &Path) -> bool {
87    path.extension()
88        .and_then(|e| e.to_str())
89        .is_some_and(|ext| matches!(ext, "css" | "scss" | "sass" | "less"))
90}
91
92/// A CSS import source with both the literal source and fallow's resolver-normalized form.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct CssImportSource {
95    /// The import source exactly as it appeared in `@import` / `@use` / `@forward` / `@plugin`.
96    pub raw: String,
97    /// The source normalized for fallow's resolver (`variables` -> `./variables` in SCSS).
98    pub normalized: String,
99    /// Whether this source came from Tailwind CSS `@plugin`.
100    pub is_plugin: bool,
101    /// Span of the source specifier in the original CSS/SCSS input.
102    pub span: Span,
103}
104
105fn is_css_module_file(path: &Path) -> bool {
106    is_css_file(path)
107        && path
108            .file_stem()
109            .and_then(|s| s.to_str())
110            .is_some_and(|stem| stem.ends_with(".module"))
111}
112
113/// Returns true if a CSS import source is a remote URL or data URI that should be skipped.
114fn is_css_url_import(source: &str) -> bool {
115    source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
116}
117
118/// Normalize a CSS/SCSS import path to use `./` prefix for relative paths.
119/// Bare file names such as `reset.css` stay relative for CSS ergonomics, while
120/// package subpaths such as `tailwindcss/theme.css` stay bare so bundler-style
121/// package CSS imports resolve through `node_modules`.
122///
123/// When `is_scss` is true, extensionless specifiers that are not SCSS built-in
124/// modules (`sass:*`) are treated as relative imports (SCSS partial convention).
125/// This handles `@use 'variables'` resolving to `./_variables.scss`.
126///
127/// Scoped npm packages (`@scope/pkg`) are always kept bare, even when they have
128/// CSS extensions (e.g., `@fontsource/monaspace-neon/400.css`). Bundlers like
129/// Vite resolve these from node_modules, not as relative paths.
130fn normalize_css_import_path(path: String, is_scss: bool) -> String {
131    if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
132        return path;
133    }
134    if path.starts_with('@') && path.contains('/') {
135        return path;
136    }
137    let path_ref = std::path::Path::new(&path);
138    if !is_scss
139        && path.contains('/')
140        && path_ref
141            .extension()
142            .and_then(|e| e.to_str())
143            .is_some_and(is_style_extension)
144    {
145        return path;
146    }
147    let ext = std::path::Path::new(&path)
148        .extension()
149        .and_then(|e| e.to_str());
150    match ext {
151        Some(e) if is_style_extension(e) => format!("./{path}"),
152        _ => {
153            if is_scss && !path.contains(':') {
154                format!("./{path}")
155            } else {
156                path
157            }
158        }
159    }
160}
161
162fn is_style_extension(ext: &str) -> bool {
163    ext.eq_ignore_ascii_case("css")
164        || ext.eq_ignore_ascii_case("scss")
165        || ext.eq_ignore_ascii_case("sass")
166        || ext.eq_ignore_ascii_case("less")
167}
168
169/// Strip comments from CSS/SCSS source to avoid matching directives inside comments.
170#[cfg(test)]
171fn strip_css_comments(source: &str, is_scss: bool) -> String {
172    let stripped = CSS_COMMENT_RE.replace_all(source, "");
173    if is_scss {
174        SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
175    } else {
176        stripped.into_owned()
177    }
178}
179
180fn mask_css_comments(source: &str, is_scss: bool) -> String {
181    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
182    if is_scss {
183        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
184    }
185    masked
186}
187
188/// Normalize a Tailwind CSS `@plugin` target.
189///
190/// Unlike SCSS `@use`, extensionless targets such as `daisyui` are package
191/// specifiers, not local partials. Keep bare specifiers bare and only preserve
192/// explicit relative/root-relative paths.
193fn normalize_css_plugin_path(path: String) -> String {
194    path
195}
196
197/// Extract `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
198///
199/// Returns both the raw source and the normalized source. URL imports
200/// (`http://`, `https://`, `data:`) are skipped. Use [`extract_css_imports`]
201/// when only the normalized form is needed.
202///
203/// Regex-based by design: this path also handles the SCSS `@use` / `@forward`
204/// forms, which lightningcss does not parse, so unlike class extraction there is
205/// no parser-backed set to defer the membership decision to.
206#[must_use]
207pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
208    let stripped = mask_css_comments(source, is_scss);
209    let mut out = Vec::new();
210
211    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
212        let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
213        if let Some(m) = raw {
214            let (src, span) = trimmed_match_with_span(m);
215            if !src.is_empty() && !is_css_url_import(&src) {
216                out.push(CssImportSource {
217                    normalized: normalize_css_import_path(src.clone(), is_scss),
218                    raw: src,
219                    is_plugin: false,
220                    span,
221                });
222            }
223        }
224    }
225
226    if is_scss {
227        for cap in SCSS_USE_RE.captures_iter(&stripped) {
228            if let Some(m) = cap.get(1) {
229                let (raw, span) = trimmed_match_with_span(m);
230                out.push(CssImportSource {
231                    normalized: normalize_css_import_path(raw.clone(), true),
232                    raw,
233                    is_plugin: false,
234                    span,
235                });
236            }
237        }
238    }
239
240    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
241        if let Some(m) = cap.get(1) {
242            let (raw, span) = trimmed_match_with_span(m);
243            if !raw.is_empty() && !is_css_url_import(&raw) {
244                out.push(CssImportSource {
245                    normalized: normalize_css_plugin_path(raw.clone()),
246                    raw,
247                    is_plugin: true,
248                    span,
249                });
250            }
251        }
252    }
253
254    out
255}
256
257fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
258    let raw = m.as_str();
259    let trimmed_start = raw.len() - raw.trim_start().len();
260    let trimmed_end = raw.trim_end().len();
261    let start = m.start() + trimmed_start;
262    let end = m.start() + trimmed_end;
263    (raw.trim().to_string(), Span::new(start as u32, end as u32))
264}
265
266/// Extract normalized `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
267///
268/// Returns specifiers normalized via `normalize_css_import_path`. URL imports
269/// (`http://`, `https://`, `data:`) are skipped. Used by callers that only need
270/// entry/dependency source paths; callers that need import kind information
271/// should use [`extract_css_import_sources`].
272#[must_use]
273pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
274    extract_css_import_sources(source, is_scss)
275        .into_iter()
276        .map(|source| source.normalized)
277        .collect()
278}
279
280/// Opening of a Tailwind v4 `@theme` block: `@theme`, optional modifier keywords
281/// (`inline` / `static` / `reference` / `default`), then the `{`. Matches up to
282/// and including the brace so the caller can brace-match the body from `end()`.
283static CSS_THEME_OPEN_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
284    crate::static_regex(r"@theme(?:\s+(?:inline|static|reference|default))*\s*\{")
285});
286
287/// A `var(--custom-property)` reference, capturing the dashed-ident name without
288/// the leading `--`. Used only to credit a theme token read by another theme
289/// token inside a `@theme` interior (lightningcss skips the unknown at-rule).
290static CSS_VAR_REF_RE: LazyLock<regex::Regex> =
291    LazyLock::new(|| crate::static_regex(r"var\(\s*--([A-Za-z0-9_-]+)"));
292
293/// A Tailwind v4 `@theme` token definition: the custom-property name WITHOUT the
294/// leading `--` (e.g. `color-brand`) and its 1-based line in the source.
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct ThemeTokenDef {
297    /// The custom-property name with the `--` prefix stripped (`color-brand`).
298    pub name: String,
299    /// 1-based line of the declaration in the original source.
300    pub line: u32,
301}
302
303/// Result of scanning a CSS source for Tailwind v4 `@theme` blocks.
304#[derive(Debug, Clone, Default, PartialEq, Eq)]
305pub struct ThemeScan {
306    /// Custom-property tokens DEFINED at the top level of a `@theme` block, with
307    /// the `*`-reset form (`--color-*: initial`) and bare-namespace declarations
308    /// excluded. Deduped by name (first definition wins for the line).
309    pub tokens: Vec<ThemeTokenDef>,
310    /// Custom-property names (without `--`) READ via `var()` anywhere inside a
311    /// `@theme` block interior. lightningcss does not descend into the unknown
312    /// `@theme` at-rule, so these reads are invisible to `CssAnalytics`; a token
313    /// backing another token (`--color-button: var(--color-brand)`) keeps the
314    /// backing token live.
315    pub theme_var_reads: Vec<String>,
316}
317
318/// Scan a CSS source for Tailwind v4 `@theme` blocks, returning the defined
319/// design tokens plus the custom properties read via `var()` inside those blocks.
320///
321/// Tailwind v4 is CSS-first, so `@theme { --color-brand: #f00; }` is the unit of
322/// a user-authored design token. lightningcss treats `@theme` as an unknown
323/// at-rule and skips it, so this is a separate brace-matching pass (comments and
324/// strings masked first so braces / semicolons inside them never break the block
325/// boundary). Only top-level `--ident: value` declarations are tokens; declarations
326/// inside a nested block (e.g. `@keyframes` for `--animate-*`) are not.
327#[must_use]
328pub fn scan_theme_blocks(source: &str) -> ThemeScan {
329    // Fast path: skip the masking allocation for the common no-`@theme` file.
330    if !source.contains("@theme") {
331        return ThemeScan::default();
332    }
333    // Mask comments AND strings/url() so a brace or semicolon inside either does
334    // not break the block boundary. Both masks preserve byte length, so offsets in the
335    // masked buffer line up 1:1 with the original (line numbers are counted in
336    // the original below).
337    let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
338    let bytes = masked.as_bytes();
339    let mut out = ThemeScan::default();
340    let mut seen: FxHashSet<String> = FxHashSet::default();
341    for open in CSS_THEME_OPEN_RE.find_iter(&masked) {
342        let body_start = open.end();
343        // Brace-match from just after the opening `{` to its partner.
344        let mut depth = 1usize;
345        let mut i = body_start;
346        while i < bytes.len() {
347            match bytes[i] {
348                b'{' => depth += 1,
349                b'}' => {
350                    depth -= 1;
351                    if depth == 0 {
352                        break;
353                    }
354                }
355                _ => {}
356            }
357            i += 1;
358        }
359        let body_end = i.min(bytes.len());
360        collect_theme_declarations(
361            source,
362            &masked,
363            body_start,
364            body_end,
365            &mut out.tokens,
366            &mut seen,
367        );
368        if let Some(body) = masked.get(body_start..body_end) {
369            for cap in CSS_VAR_REF_RE.captures_iter(body) {
370                if let Some(name) = cap.get(1) {
371                    out.theme_var_reads.push(name.as_str().to_owned());
372                }
373            }
374        }
375    }
376    out
377}
378
379/// Walk a masked `@theme` body collecting top-level `--ident: value` declarations
380/// as tokens. Tracks brace depth so declarations inside a nested block (e.g. an
381/// `@keyframes` for `--animate-*`) are skipped, and statement position so only a
382/// `--ident` at a declaration start counts. The `*`-reset form (`--color-*`) is
383/// excluded because the `*` breaks the ident scan before the `:`.
384fn collect_theme_declarations(
385    source: &str,
386    masked: &str,
387    start: usize,
388    end: usize,
389    out: &mut Vec<ThemeTokenDef>,
390    seen: &mut FxHashSet<String>,
391) {
392    let bytes = masked.as_bytes();
393    let mut depth = 0usize;
394    let mut expect_decl = true;
395    let mut i = start;
396    while i < end {
397        let b = bytes[i];
398        match b {
399            b'{' => {
400                depth += 1;
401                expect_decl = false;
402                i += 1;
403            }
404            b'}' => {
405                depth = depth.saturating_sub(1);
406                if depth == 0 {
407                    expect_decl = true;
408                }
409                i += 1;
410            }
411            b';' => {
412                if depth == 0 {
413                    expect_decl = true;
414                }
415                i += 1;
416            }
417            _ if b.is_ascii_whitespace() => i += 1,
418            _ => {
419                if depth == 0 && expect_decl {
420                    expect_decl = false;
421                    if b == b'-' && bytes.get(i + 1) == Some(&b'-') {
422                        let id_start = i;
423                        let mut j = i;
424                        while j < end {
425                            let c = bytes[j];
426                            if c == b'-' || c == b'_' || c.is_ascii_alphanumeric() {
427                                j += 1;
428                            } else {
429                                break;
430                            }
431                        }
432                        let mut k = j;
433                        while k < end && bytes[k].is_ascii_whitespace() {
434                            k += 1;
435                        }
436                        // Only a `--ident:` (no `*` before the colon) is a token.
437                        if k < end && bytes[k] == b':' {
438                            let name = &masked[id_start + 2..j];
439                            if !name.is_empty() && seen.insert(name.to_owned()) {
440                                let line = 1 + source
441                                    .get(..id_start)
442                                    .map_or(0, |s| s.bytes().filter(|&x| x == b'\n').count());
443                                out.push(ThemeTokenDef {
444                                    name: name.to_owned(),
445                                    line: u32::try_from(line).unwrap_or(u32::MAX),
446                                });
447                            }
448                        }
449                        i = j;
450                    } else {
451                        i += 1;
452                    }
453                } else {
454                    i += 1;
455                }
456            }
457        }
458    }
459}
460
461/// Extract the utility tokens referenced in `@apply` directive bodies across a
462/// CSS source (comment / string masked). `@apply rounded-card font-bold;` yields
463/// `["rounded-card", "font-bold"]`. The leading-`!` and trailing-`!` important
464/// modifiers and a bare `!important` token are stripped, so a theme token whose
465/// utility is applied only via `@apply` is credited as used.
466#[must_use]
467pub fn extract_apply_tokens(source: &str) -> Vec<String> {
468    // Fast path: skip the masking allocation for the common no-`@apply` file.
469    if !source.contains("@apply") {
470        return Vec::new();
471    }
472    let masked = mask_with_whitespace(&mask_css_comments(source, false), &CSS_NON_SELECTOR_RE);
473    let mut out = Vec::new();
474    for m in CSS_APPLY_RE.find_iter(&masked) {
475        let body = m.as_str().trim_start_matches("@apply");
476        for token in body.split_whitespace() {
477            let token = token.trim_matches('!');
478            if token.is_empty() || token == "important" {
479                continue;
480            }
481            out.push(token.to_owned());
482        }
483    }
484    out
485}
486
487/// Mask every regex match in `src` with ASCII spaces (`0x20`) of equal byte
488/// length, so byte offsets in the returned string correspond 1:1 to byte
489/// offsets in the original.
490///
491/// Used to neutralise CSS comments, quoted strings, `url(...)`, and at-rule
492/// preludes before scanning for `.class` selectors, while preserving the
493/// original-source positions that callers need to populate `ExportInfo.span`
494/// (issue #549). The `regex` crate guarantees match boundaries respect UTF-8
495/// char boundaries, so the masked buffer is always valid UTF-8.
496fn mask_with_whitespace(src: &str, re: &regex::Regex) -> String {
497    let mut out = String::with_capacity(src.len());
498    let mut cursor = 0;
499    for m in re.find_iter(src) {
500        out.push_str(&src[cursor..m.start()]);
501        for _ in m.start()..m.end() {
502            out.push(' ');
503        }
504        cursor = m.end();
505    }
506    out.push_str(&src[cursor..]);
507    out
508}
509
510/// Collect the authoritative set of class-selector names from a CSS source by
511/// parsing it into a real AST (lightningcss). Returns `None` only on a
512/// catastrophic parse failure (Sass syntax that is not standard CSS), in which
513/// case the caller falls back to the regex scanner. With `error_recovery` on,
514/// individual malformed rules are recovered silently and contribute a partial
515/// set rather than triggering the fallback, so a broken rule drops only its own
516/// classes (a conservative miss) instead of returning `None`.
517///
518/// This is the source of truth for which `.token` occurrences are genuine class
519/// selectors. It natively excludes `@layer foo.bar` layer names, `@import ...
520/// layer(theme.button)` layer references, `@keyframes` step selectors, id and
521/// element selectors, and the contents of comments / strings / `url()`, which
522/// the older regex-only scanner had to approximate with a stack of masking
523/// passes. Classes nested inside `:is()` / `:where()` / `:not()` / `:has()` /
524/// `:any()` / `::slotted()` / `:host()` / `:nth-child(... of ...)` are
525/// collected too, matching the regex scanner's "every `.class` token" behavior.
526fn lightningcss_class_set(source: &str) -> Option<FxHashSet<String>> {
527    let options = ParserOptions {
528        // Recover from individual malformed rules so a single bad rule does not
529        // discard class names from the rest of the file.
530        error_recovery: true,
531        // These files are `.module.css` / `.module.scss`, so parse in CSS Modules
532        // mode. That makes the `:local()` / `:global()` pseudo-classes parse as
533        // real selectors rather than erroring, so classes wrapped in them are
534        // collected (matching the regex scanner). Renaming is a print-time
535        // concern, so the AST class names stay the original author-written names.
536        css_modules: Some(lightningcss::css_modules::Config::default()),
537        ..ParserOptions::default()
538    };
539    let stylesheet = StyleSheet::parse(source, options).ok()?;
540    let mut classes = FxHashSet::default();
541    collect_classes_from_rules(&stylesheet.rules.0, &mut classes);
542    Some(classes)
543}
544
545/// Recursively collect class-selector names from a list of CSS rules, descending
546/// into every grouping rule (`@media`, `@supports`, `@container`, `@layer {}`,
547/// `@document`, `@starting-style`, `@scope`, nested style rules) so a class
548/// declared anywhere contributes to the set.
549fn collect_classes_from_rules(rules: &[CssRule<'_>], classes: &mut FxHashSet<String>) {
550    for rule in rules {
551        match rule {
552            CssRule::Style(style) => {
553                collect_classes_from_selector_list(&style.selectors, classes);
554                collect_classes_from_rules(&style.rules.0, classes);
555            }
556            CssRule::Media(rule) => collect_classes_from_rules(&rule.rules.0, classes),
557            CssRule::Supports(rule) => collect_classes_from_rules(&rule.rules.0, classes),
558            CssRule::Container(rule) => collect_classes_from_rules(&rule.rules.0, classes),
559            CssRule::LayerBlock(rule) => collect_classes_from_rules(&rule.rules.0, classes),
560            CssRule::MozDocument(rule) => collect_classes_from_rules(&rule.rules.0, classes),
561            CssRule::StartingStyle(rule) => collect_classes_from_rules(&rule.rules.0, classes),
562            CssRule::Nesting(rule) => {
563                collect_classes_from_selector_list(&rule.style.selectors, classes);
564                collect_classes_from_rules(&rule.style.rules.0, classes);
565            }
566            CssRule::Scope(rule) => {
567                if let Some(scope_start) = &rule.scope_start {
568                    collect_classes_from_selector_list(scope_start, classes);
569                }
570                if let Some(scope_end) = &rule.scope_end {
571                    collect_classes_from_selector_list(scope_end, classes);
572                }
573                collect_classes_from_rules(&rule.rules.0, classes);
574            }
575            _ => {}
576        }
577    }
578}
579
580fn collect_classes_from_selector_list(list: &SelectorList<'_>, classes: &mut FxHashSet<String>) {
581    for selector in &list.0 {
582        collect_classes_from_selector(selector, classes);
583    }
584}
585
586fn collect_classes_from_selector(selector: &Selector<'_>, classes: &mut FxHashSet<String>) {
587    for component in selector.iter_raw_match_order() {
588        match component {
589            Component::Class(name) => {
590                classes.insert(name.0.to_string());
591            }
592            Component::Is(list)
593            | Component::Where(list)
594            | Component::Has(list)
595            | Component::Negation(list)
596            | Component::Any(_, list) => {
597                for nested in list.as_ref() {
598                    collect_classes_from_selector(nested, classes);
599                }
600            }
601            Component::Slotted(nested) | Component::Host(Some(nested)) => {
602                collect_classes_from_selector(nested, classes);
603            }
604            Component::NthOf(data) => {
605                for nested in data.selectors() {
606                    collect_classes_from_selector(nested, classes);
607                }
608            }
609            // CSS Modules `:local(.foo)` / `:global(.foo)` wrap a real selector.
610            Component::NonTSPseudoClass(
611                PseudoClass::Local { selector } | PseudoClass::Global { selector },
612            ) => collect_classes_from_selector(selector, classes),
613            _ => {}
614        }
615    }
616}
617
618/// Extract class names from a CSS module file as named exports.
619///
620/// For standard CSS, lightningcss parses the source into an AST and supplies the
621/// authoritative set of class-selector names; the byte-offset scanner then
622/// locates each name's [`Span`] in the ORIGINAL `source` (pointing at the bare
623/// class name, no leading dot) so downstream `compute_line_offsets` resolves the
624/// real declaration line and column instead of falling back to line:1 col:0
625/// (issue #549). For SCSS (Sass syntax lightningcss does not parse) and for any
626/// CSS that fails to parse outright, the regex-only scanner is used unchanged.
627pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
628    if !is_scss && let Some(class_set) = lightningcss_class_set(source) {
629        return scan_css_module_exports(source, is_scss, Some(&class_set));
630    }
631    scan_css_module_exports(source, is_scss, None)
632}
633
634/// Scan `source` for `.class` tokens and emit one [`ExportInfo`] per distinct
635/// class (first occurrence wins), with a [`Span`] pointing at the post-dot
636/// identifier in the original source.
637///
638/// When `class_filter` is `Some`, only tokens present in the AST-derived set are
639/// emitted, so the parser owns the membership decision and the scanner owns only
640/// span location. When `class_filter` is `None` (SCSS / parse-failure fallback),
641/// the at-rule prelude is masked to keep `@layer foo.bar` / `@import ...
642/// layer(...)` segments from being mistaken for classes.
643fn scan_css_module_exports(
644    source: &str,
645    is_scss: bool,
646    class_filter: Option<&FxHashSet<String>>,
647) -> Vec<ExportInfo> {
648    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
649    if is_scss {
650        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
651    }
652    masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
653    if class_filter.is_none() {
654        masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
655    }
656
657    let mut seen = FxHashSet::default();
658    let mut exports = Vec::new();
659    for cap in CSS_CLASS_RE.captures_iter(&masked) {
660        if let Some(m) = cap.get(1) {
661            let class_name = m.as_str().to_string();
662            if class_filter.is_some_and(|filter| !filter.contains(&class_name)) {
663                continue;
664            }
665            if seen.insert(class_name.clone()) {
666                #[expect(
667                    clippy::cast_possible_truncation,
668                    reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
669                )]
670                let span = Span::new(m.start() as u32, m.end() as u32);
671                exports.push(ExportInfo {
672                    name: ExportName::Named(class_name),
673                    local_name: None,
674                    is_type_only: false,
675                    visibility: VisibilityTag::None,
676                    span,
677                    members: Vec::new(),
678                    is_side_effect_used: false,
679                    super_class: None,
680                });
681            }
682        }
683    }
684    exports
685}
686
687/// Parse a CSS/SCSS file, extracting @import, @use, @forward, @plugin, @apply, and @tailwind directives.
688pub(crate) fn parse_css_to_module(
689    file_id: FileId,
690    path: &Path,
691    source: &str,
692    content_hash: u64,
693) -> ModuleInfo {
694    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
695    let is_scss = path
696        .extension()
697        .and_then(|e| e.to_str())
698        .is_some_and(|ext| matches!(ext, "scss" | "sass" | "less"));
699
700    let stripped = mask_css_comments(source, is_scss);
701
702    let mut imports = Vec::new();
703
704    for source in extract_css_import_sources(source, is_scss) {
705        imports.push(ImportInfo {
706            source: source.normalized,
707            imported_name: if source.is_plugin {
708                ImportedName::Default
709            } else {
710                ImportedName::SideEffect
711            },
712            local_name: String::new(),
713            is_type_only: false,
714            from_style: false,
715            span: source.span,
716            source_span: source.span,
717        });
718    }
719
720    let has_apply = CSS_APPLY_RE.is_match(&stripped);
721    let has_tailwind = CSS_TAILWIND_RE.is_match(&stripped);
722    if has_apply || has_tailwind {
723        imports.push(ImportInfo {
724            source: "tailwindcss".to_string(),
725            imported_name: ImportedName::SideEffect,
726            local_name: String::new(),
727            is_type_only: false,
728            from_style: false,
729            span: Span::default(),
730            source_span: Span::default(),
731        });
732    }
733
734    let exports = if is_css_module_file(path) {
735        extract_css_module_exports(source, is_scss)
736    } else {
737        Vec::new()
738    };
739
740    ModuleInfo {
741        file_id,
742        exports,
743        imports,
744        re_exports: Vec::new(),
745        dynamic_imports: Vec::new(),
746        dynamic_import_patterns: Vec::new(),
747        require_calls: Vec::new(),
748        package_path_references: Vec::new(),
749        member_accesses: Vec::new(),
750        whole_object_uses: Vec::new(),
751        has_cjs_exports: false,
752        has_angular_component_template_url: false,
753        content_hash,
754        suppressions: parsed_suppressions.suppressions,
755        unknown_suppression_kinds: parsed_suppressions.unknown_kinds,
756        unused_import_bindings: Vec::new(),
757        type_referenced_import_bindings: Vec::new(),
758        value_referenced_import_bindings: Vec::new(),
759        line_offsets: fallow_types::extract::compute_line_offsets(source),
760        complexity: Vec::new(),
761        flag_uses: Vec::new(),
762        class_heritage: vec![],
763        injection_tokens: vec![],
764        local_type_declarations: Vec::new(),
765        public_signature_type_references: Vec::new(),
766        namespace_object_aliases: Vec::new(),
767        iconify_prefixes: Vec::new(),
768        iconify_icon_names: Vec::new(),
769        auto_import_candidates: Vec::new(),
770        directives: Vec::new(),
771        client_only_dynamic_import_spans: Vec::new(),
772        security_sinks: Vec::new(),
773        security_sinks_skipped: 0,
774        security_unresolved_callee_sites: Vec::new(),
775        tainted_bindings: Vec::new(),
776        sanitized_sink_args: Vec::new(),
777        security_control_sites: Vec::new(),
778        callee_uses: Vec::new(),
779        misplaced_directives: Vec::new(),
780        di_key_sites: Vec::new(),
781        has_dynamic_provide: false,
782        referenced_import_bindings: Vec::new(),
783        component_props: Vec::new(),
784        has_props_attrs_fallthrough: false,
785        has_define_expose: false,
786        has_define_model: false,
787        has_unharvestable_props: false,
788        component_emits: Vec::new(),
789        has_unharvestable_emits: false,
790        has_dynamic_emit: false,
791        has_emit_whole_object_use: false,
792        load_return_keys: Vec::new(),
793        has_unharvestable_load: false,
794        has_load_data_whole_use: false,
795        has_page_data_store_whole_use: false,
796        component_functions: Vec::new(),
797        react_props: Vec::new(),
798        hook_uses: Vec::new(),
799        render_edges: Vec::new(),
800    }
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806
807    /// Helper to collect export names as strings from `extract_css_module_exports`.
808    fn export_names(source: &str) -> Vec<String> {
809        extract_css_module_exports(source, false)
810            .into_iter()
811            .filter_map(|e| match e.name {
812                ExportName::Named(n) => Some(n),
813                ExportName::Default => None,
814            })
815            .collect()
816    }
817
818    #[test]
819    fn is_css_file_css() {
820        assert!(is_css_file(Path::new("styles.css")));
821    }
822
823    #[test]
824    fn is_css_file_scss() {
825        assert!(is_css_file(Path::new("styles.scss")));
826    }
827
828    #[test]
829    fn is_css_file_sass() {
830        assert!(is_css_file(Path::new("styles.sass")));
831    }
832
833    #[test]
834    fn is_css_file_less() {
835        assert!(is_css_file(Path::new("styles.less")));
836    }
837
838    #[test]
839    fn is_css_file_rejects_js() {
840        assert!(!is_css_file(Path::new("app.js")));
841    }
842
843    #[test]
844    fn is_css_file_rejects_ts() {
845        assert!(!is_css_file(Path::new("app.ts")));
846    }
847
848    #[test]
849    fn is_css_file_rejects_no_extension() {
850        assert!(!is_css_file(Path::new("Makefile")));
851    }
852
853    #[test]
854    fn is_css_module_file_module_css() {
855        assert!(is_css_module_file(Path::new("Component.module.css")));
856    }
857
858    #[test]
859    fn is_css_module_file_module_scss() {
860        assert!(is_css_module_file(Path::new("Component.module.scss")));
861    }
862
863    #[test]
864    fn is_css_module_file_rejects_plain_css() {
865        assert!(!is_css_module_file(Path::new("styles.css")));
866    }
867
868    #[test]
869    fn is_css_module_file_rejects_plain_scss() {
870        assert!(!is_css_module_file(Path::new("styles.scss")));
871    }
872
873    #[test]
874    fn is_css_module_file_rejects_module_js() {
875        assert!(!is_css_module_file(Path::new("utils.module.js")));
876    }
877
878    #[test]
879    fn extracts_single_class() {
880        let names = export_names(".foo { color: red; }");
881        assert_eq!(names, vec!["foo"]);
882    }
883
884    #[test]
885    fn extracts_multiple_classes() {
886        let names = export_names(".foo { } .bar { }");
887        assert_eq!(names, vec!["foo", "bar"]);
888    }
889
890    #[test]
891    fn extracts_nested_classes() {
892        let names = export_names(".foo .bar { color: red; }");
893        assert!(names.contains(&"foo".to_string()));
894        assert!(names.contains(&"bar".to_string()));
895    }
896
897    #[test]
898    fn extracts_hyphenated_class() {
899        let names = export_names(".my-class { }");
900        assert_eq!(names, vec!["my-class"]);
901    }
902
903    #[test]
904    fn extracts_camel_case_class() {
905        let names = export_names(".myClass { }");
906        assert_eq!(names, vec!["myClass"]);
907    }
908
909    #[test]
910    fn extracts_class_inside_global_pseudo() {
911        // CSS Modules `:global(.foo)` must surface `foo`: the parser understands
912        // the wrapped selector, which the regex scanner could not on its own.
913        let names = export_names(":global(.globalClass) { color: red; }");
914        assert_eq!(names, vec!["globalClass"]);
915    }
916
917    #[test]
918    fn extracts_class_inside_local_pseudo() {
919        let names = export_names(":local(.localClass) { color: red; }");
920        assert_eq!(names, vec!["localClass"]);
921    }
922
923    #[test]
924    fn extracts_classes_inside_negation() {
925        let names = export_names(".btn:not(.disabled) { }");
926        assert!(names.contains(&"btn".to_string()), "got {names:?}");
927        assert!(names.contains(&"disabled".to_string()), "got {names:?}");
928    }
929
930    #[test]
931    fn extracts_classes_inside_is_and_where() {
932        let names = export_names(":is(.a, .b) :where(.c) { }");
933        for expected in ["a", "b", "c"] {
934            assert!(
935                names.contains(&expected.to_string()),
936                "missing {expected} in {names:?}"
937            );
938        }
939    }
940
941    #[test]
942    fn extracts_underscore_class() {
943        let names = export_names("._hidden { } .__wrapper { }");
944        assert!(names.contains(&"_hidden".to_string()));
945        assert!(names.contains(&"__wrapper".to_string()));
946    }
947
948    #[test]
949    fn pseudo_selector_hover() {
950        let names = export_names(".foo:hover { color: blue; }");
951        assert_eq!(names, vec!["foo"]);
952    }
953
954    #[test]
955    fn pseudo_selector_focus() {
956        let names = export_names(".input:focus { outline: none; }");
957        assert_eq!(names, vec!["input"]);
958    }
959
960    #[test]
961    fn pseudo_element_before() {
962        let names = export_names(".icon::before { content: ''; }");
963        assert_eq!(names, vec!["icon"]);
964    }
965
966    #[test]
967    fn combined_pseudo_selectors() {
968        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
969        assert_eq!(names, vec!["btn"]);
970    }
971
972    #[test]
973    fn classes_inside_media_query() {
974        let names = export_names(
975            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
976        );
977        assert!(names.contains(&"mobile-nav".to_string()));
978        assert!(names.contains(&"desktop-nav".to_string()));
979    }
980
981    #[test]
982    fn classes_inside_multi_line_media_query() {
983        let names =
984            export_names("@media\n  screen and (min-width: 600px)\n{\n  .real { color: red; }\n}");
985        assert_eq!(names, vec!["real"]);
986    }
987
988    #[test]
989    fn at_layer_statement_does_not_export() {
990        let names = export_names("@layer foo.bar;");
991        assert!(names.is_empty(), "got {names:?}");
992        let names = export_names("@layer foo.bar, foo.baz;");
993        assert!(names.is_empty(), "got {names:?}");
994    }
995
996    #[test]
997    fn at_layer_block_keeps_body_classes() {
998        let names = export_names("@layer foo.bar { .root { color: red; } }");
999        assert_eq!(names, vec!["root"]);
1000    }
1001
1002    #[test]
1003    fn at_layer_multiline_prelude_keeps_body_classes() {
1004        let names = export_names("@layer\n  foo.bar\n{ .root { color: red; } }");
1005        assert_eq!(names, vec!["root"]);
1006    }
1007
1008    #[test]
1009    fn at_layer_with_nested_media_keeps_body() {
1010        let names =
1011            export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
1012        assert_eq!(names, vec!["real"]);
1013    }
1014
1015    #[test]
1016    fn at_import_with_layer_attribute_does_not_export() {
1017        let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
1018        assert!(names.is_empty(), "got {names:?}");
1019    }
1020
1021    #[test]
1022    fn class_then_at_layer_does_not_leak_prelude() {
1023        let names =
1024            export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
1025        assert_eq!(names, vec!["outer", "inner"]);
1026    }
1027
1028    #[test]
1029    fn at_scope_keeps_selector_list_classes() {
1030        let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
1031        assert!(names.contains(&"parent".to_string()), "got {names:?}");
1032        assert!(names.contains(&"child".to_string()), "got {names:?}");
1033        assert!(names.contains(&"title".to_string()), "got {names:?}");
1034    }
1035
1036    #[test]
1037    fn at_keyframes_numeric_step_is_not_class() {
1038        let names = export_names(
1039            "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
1040        );
1041        assert!(names.is_empty(), "got {names:?}");
1042    }
1043
1044    #[test]
1045    fn at_webkit_keyframes_keeps_body_classes() {
1046        let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
1047        assert_eq!(names, vec!["real"]);
1048    }
1049
1050    #[test]
1051    fn deduplicates_repeated_class() {
1052        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
1053        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
1054    }
1055
1056    #[test]
1057    fn empty_source() {
1058        let names = export_names("");
1059        assert!(names.is_empty());
1060    }
1061
1062    #[test]
1063    fn no_classes() {
1064        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
1065        assert!(names.is_empty());
1066    }
1067
1068    #[test]
1069    fn ignores_classes_in_block_comments() {
1070        let names = export_names("/* .fake { } */ .real { }");
1071        assert!(!names.contains(&"fake".to_string()));
1072        assert!(names.contains(&"real".to_string()));
1073    }
1074
1075    #[test]
1076    fn ignores_classes_in_scss_line_comments() {
1077        let exports = extract_css_module_exports("// .fake\n.real { }", true);
1078        let names: Vec<_> = exports
1079            .iter()
1080            .filter_map(|e| match &e.name {
1081                ExportName::Named(n) => Some(n.as_str()),
1082                ExportName::Default => None,
1083            })
1084            .collect();
1085        assert_eq!(names, vec!["real"]);
1086    }
1087
1088    #[test]
1089    fn ignores_classes_in_strings() {
1090        let names = export_names(r#".real { content: ".fake"; }"#);
1091        assert!(names.contains(&"real".to_string()));
1092        assert!(!names.contains(&"fake".to_string()));
1093    }
1094
1095    #[test]
1096    fn ignores_classes_in_url() {
1097        let names = export_names(".real { background: url(./images/hero.png); }");
1098        assert!(names.contains(&"real".to_string()));
1099        assert!(!names.contains(&"png".to_string()));
1100    }
1101
1102    #[test]
1103    fn strip_css_block_comment() {
1104        let result = strip_css_comments("/* removed */ .kept { }", false);
1105        assert!(!result.contains("removed"));
1106        assert!(result.contains(".kept"));
1107    }
1108
1109    #[test]
1110    fn strip_scss_line_comment() {
1111        let result = strip_css_comments("// removed\n.kept { }", true);
1112        assert!(!result.contains("removed"));
1113        assert!(result.contains(".kept"));
1114    }
1115
1116    #[test]
1117    fn strip_scss_preserves_css_outside_comments() {
1118        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
1119        let result = strip_css_comments(source, true);
1120        assert!(result.contains(".visible"));
1121    }
1122
1123    #[test]
1124    fn url_import_http() {
1125        assert!(is_css_url_import("http://example.com/style.css"));
1126    }
1127
1128    #[test]
1129    fn url_import_https() {
1130        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
1131    }
1132
1133    #[test]
1134    fn url_import_data() {
1135        assert!(is_css_url_import("data:text/css;base64,abc"));
1136    }
1137
1138    #[test]
1139    fn url_import_local_not_skipped() {
1140        assert!(!is_css_url_import("./local.css"));
1141    }
1142
1143    #[test]
1144    fn url_import_bare_specifier_not_skipped() {
1145        assert!(!is_css_url_import("tailwindcss"));
1146    }
1147
1148    #[test]
1149    fn normalize_relative_dot_path_unchanged() {
1150        assert_eq!(
1151            normalize_css_import_path("./reset.css".to_string(), false),
1152            "./reset.css"
1153        );
1154    }
1155
1156    #[test]
1157    fn normalize_parent_relative_path_unchanged() {
1158        assert_eq!(
1159            normalize_css_import_path("../shared.scss".to_string(), false),
1160            "../shared.scss"
1161        );
1162    }
1163
1164    #[test]
1165    fn normalize_absolute_path_unchanged() {
1166        assert_eq!(
1167            normalize_css_import_path("/styles/main.css".to_string(), false),
1168            "/styles/main.css"
1169        );
1170    }
1171
1172    #[test]
1173    fn normalize_url_unchanged() {
1174        assert_eq!(
1175            normalize_css_import_path("https://example.com/style.css".to_string(), false),
1176            "https://example.com/style.css"
1177        );
1178    }
1179
1180    #[test]
1181    fn normalize_bare_css_gets_dot_slash() {
1182        assert_eq!(
1183            normalize_css_import_path("app.css".to_string(), false),
1184            "./app.css"
1185        );
1186    }
1187
1188    #[test]
1189    fn normalize_css_package_subpath_stays_bare() {
1190        assert_eq!(
1191            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
1192            "tailwindcss/theme.css"
1193        );
1194    }
1195
1196    #[test]
1197    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
1198        assert_eq!(
1199            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
1200            "highlight.js/styles/github.css"
1201        );
1202    }
1203
1204    #[test]
1205    fn normalize_bare_scss_gets_dot_slash() {
1206        assert_eq!(
1207            normalize_css_import_path("vars.scss".to_string(), false),
1208            "./vars.scss"
1209        );
1210    }
1211
1212    #[test]
1213    fn normalize_bare_sass_gets_dot_slash() {
1214        assert_eq!(
1215            normalize_css_import_path("main.sass".to_string(), false),
1216            "./main.sass"
1217        );
1218    }
1219
1220    #[test]
1221    fn normalize_bare_less_gets_dot_slash() {
1222        assert_eq!(
1223            normalize_css_import_path("theme.less".to_string(), false),
1224            "./theme.less"
1225        );
1226    }
1227
1228    #[test]
1229    fn normalize_bare_js_extension_stays_bare() {
1230        assert_eq!(
1231            normalize_css_import_path("module.js".to_string(), false),
1232            "module.js"
1233        );
1234    }
1235
1236    #[test]
1237    fn normalize_scss_bare_partial_gets_dot_slash() {
1238        assert_eq!(
1239            normalize_css_import_path("variables".to_string(), true),
1240            "./variables"
1241        );
1242    }
1243
1244    #[test]
1245    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
1246        assert_eq!(
1247            normalize_css_import_path("base/reset".to_string(), true),
1248            "./base/reset"
1249        );
1250    }
1251
1252    #[test]
1253    fn normalize_scss_builtin_stays_bare() {
1254        assert_eq!(
1255            normalize_css_import_path("sass:math".to_string(), true),
1256            "sass:math"
1257        );
1258    }
1259
1260    #[test]
1261    fn normalize_scss_relative_path_unchanged() {
1262        assert_eq!(
1263            normalize_css_import_path("../styles/variables".to_string(), true),
1264            "../styles/variables"
1265        );
1266    }
1267
1268    #[test]
1269    fn normalize_css_bare_extensionless_stays_bare() {
1270        assert_eq!(
1271            normalize_css_import_path("tailwindcss".to_string(), false),
1272            "tailwindcss"
1273        );
1274    }
1275
1276    #[test]
1277    fn normalize_scoped_package_with_css_extension_stays_bare() {
1278        assert_eq!(
1279            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
1280            "@fontsource/monaspace-neon/400.css"
1281        );
1282    }
1283
1284    #[test]
1285    fn normalize_scoped_package_with_scss_extension_stays_bare() {
1286        assert_eq!(
1287            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
1288            "@company/design-system/tokens.scss"
1289        );
1290    }
1291
1292    #[test]
1293    fn normalize_scoped_package_without_extension_stays_bare() {
1294        assert_eq!(
1295            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
1296            "@fallow/design-system/styles"
1297        );
1298    }
1299
1300    #[test]
1301    fn normalize_scoped_package_extensionless_scss_stays_bare() {
1302        assert_eq!(
1303            normalize_css_import_path("@company/tokens".to_string(), true),
1304            "@company/tokens"
1305        );
1306    }
1307
1308    #[test]
1309    fn normalize_path_alias_with_css_extension_stays_bare() {
1310        assert_eq!(
1311            normalize_css_import_path("@/components/Button.css".to_string(), false),
1312            "@/components/Button.css"
1313        );
1314    }
1315
1316    #[test]
1317    fn normalize_path_alias_extensionless_stays_bare() {
1318        assert_eq!(
1319            normalize_css_import_path("@/styles/variables".to_string(), false),
1320            "@/styles/variables"
1321        );
1322    }
1323
1324    #[test]
1325    fn strip_css_no_comments() {
1326        let source = ".foo { color: red; }";
1327        assert_eq!(strip_css_comments(source, false), source);
1328    }
1329
1330    #[test]
1331    fn strip_css_multiple_block_comments() {
1332        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1333        let result = strip_css_comments(source, false);
1334        assert!(!result.contains("comment-one"));
1335        assert!(!result.contains("comment-two"));
1336        assert!(result.contains(".foo"));
1337        assert!(result.contains(".bar"));
1338    }
1339
1340    #[test]
1341    fn strip_scss_does_not_affect_non_scss() {
1342        let source = "// this stays\n.foo { }";
1343        let result = strip_css_comments(source, false);
1344        assert!(result.contains("// this stays"));
1345    }
1346
1347    #[test]
1348    fn css_module_parses_suppressions() {
1349        let info = parse_css_to_module(
1350            fallow_types::discover::FileId(0),
1351            Path::new("Component.module.css"),
1352            "/* fallow-ignore-file */\n.btn { color: red; }",
1353            0,
1354        );
1355        assert!(!info.suppressions.is_empty());
1356        assert_eq!(info.suppressions[0].line, 0);
1357    }
1358
1359    #[test]
1360    fn extracts_class_starting_with_underscore() {
1361        let names = export_names("._private { } .__dunder { }");
1362        assert!(names.contains(&"_private".to_string()));
1363        assert!(names.contains(&"__dunder".to_string()));
1364    }
1365
1366    #[test]
1367    fn ignores_id_selectors() {
1368        let names = export_names("#myId { color: red; }");
1369        assert!(!names.contains(&"myId".to_string()));
1370    }
1371
1372    #[test]
1373    fn ignores_element_selectors() {
1374        let names = export_names("div { color: red; } span { }");
1375        assert!(names.is_empty());
1376    }
1377
1378    #[test]
1379    fn extract_css_imports_at_import_quoted() {
1380        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1381        assert_eq!(imports, vec!["./reset.css"]);
1382    }
1383
1384    #[test]
1385    fn extract_css_imports_package_subpath_stays_bare() {
1386        let imports =
1387            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1388        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1389    }
1390
1391    #[test]
1392    fn extract_css_imports_at_import_url() {
1393        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1394        assert_eq!(imports, vec!["./reset.css"]);
1395    }
1396
1397    #[test]
1398    fn extract_css_imports_skips_remote_urls() {
1399        let imports =
1400            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1401        assert!(imports.is_empty());
1402    }
1403
1404    #[test]
1405    fn extract_css_imports_scss_use_normalizes_partial() {
1406        let imports = extract_css_imports(r#"@use "variables";"#, true);
1407        assert_eq!(imports, vec!["./variables"]);
1408    }
1409
1410    #[test]
1411    fn extract_css_imports_scss_forward_normalizes_partial() {
1412        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1413        assert_eq!(imports, vec!["./tokens"]);
1414    }
1415
1416    #[test]
1417    fn extract_css_imports_skips_comments() {
1418        let imports = extract_css_imports(
1419            r#"/* @import "./hidden.scss"; */
1420@use "real";"#,
1421            true,
1422        );
1423        assert_eq!(imports, vec!["./real"]);
1424    }
1425
1426    #[test]
1427    fn extract_css_imports_at_plugin_keeps_package_bare() {
1428        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1429        assert_eq!(imports, vec!["daisyui"]);
1430    }
1431
1432    #[test]
1433    fn extract_css_imports_at_plugin_tracks_relative_file() {
1434        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1435        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1436    }
1437
1438    #[test]
1439    fn extract_css_imports_scss_at_import_kept_relative() {
1440        let imports = extract_css_imports(r"@import 'Foo';", true);
1441        assert_eq!(imports, vec!["./Foo"]);
1442    }
1443
1444    #[test]
1445    fn extract_css_imports_additional_data_string_body() {
1446        let body = r#"@use "./src/styles/global.scss";"#;
1447        let imports = extract_css_imports(body, true);
1448        assert_eq!(imports, vec!["./src/styles/global.scss"]);
1449    }
1450
1451    #[test]
1452    fn mask_with_whitespace_preserves_byte_length() {
1453        let src = "/* hello */ .foo { }";
1454        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1455        assert_eq!(masked.len(), src.len());
1456        assert!(masked.is_char_boundary(src.len()));
1457    }
1458
1459    #[test]
1460    fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1461        let src = "/* \u{2713} */ .foo { }";
1462        let foo_offset = src.find(".foo").expect("`.foo` present");
1463        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1464        assert_eq!(masked.len(), src.len());
1465        assert_eq!(masked.find(".foo"), Some(foo_offset));
1466    }
1467
1468    /// Resolve a span's start to (line, col) using the same primitives the
1469    /// downstream pipeline uses in `crates/core/src/analyze/unused_exports.rs`.
1470    fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1471        let offsets = fallow_types::extract::compute_line_offsets(source);
1472        fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1473    }
1474
1475    #[test]
1476    fn span_points_at_real_class_declaration_line() {
1477        let source = "\n\n\n\n.foo { color: red; }\n";
1478        let exports = extract_css_module_exports(source, false);
1479        assert_eq!(exports.len(), 1);
1480        let span = exports[0].span;
1481        let (line, col) = span_line_col(source, span.start);
1482        assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1483        assert_eq!(
1484            col, 1,
1485            "column points at `f` in `.foo` (post-dot identifier)"
1486        );
1487        assert_eq!(
1488            &source[span.start as usize..span.end as usize],
1489            "foo",
1490            "span range must slice to the class identifier in the original source"
1491        );
1492    }
1493
1494    #[test]
1495    fn span_survives_multibyte_comment_prefix() {
1496        let source = "/* \u{2713} */\n.foo { }";
1497        let exports = extract_css_module_exports(source, false);
1498        assert_eq!(exports.len(), 1);
1499        let span = exports[0].span;
1500        assert!(
1501            source.is_char_boundary(span.start as usize),
1502            "span.start must lie on a UTF-8 char boundary"
1503        );
1504        assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1505    }
1506
1507    #[test]
1508    fn span_skips_at_layer_prelude_dot_segments() {
1509        let source = "@layer foo.bar { }\n.root { }\n";
1510        let exports = extract_css_module_exports(source, false);
1511        let names: Vec<_> = exports
1512            .iter()
1513            .filter_map(|e| match &e.name {
1514                ExportName::Named(n) => Some(n.as_str()),
1515                ExportName::Default => None,
1516            })
1517            .collect();
1518        assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1519        let span = exports[0].span;
1520        let (line, _col) = span_line_col(source, span.start);
1521        assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1522        assert_eq!(&source[span.start as usize..span.end as usize], "root");
1523    }
1524
1525    #[test]
1526    fn span_skips_classes_in_strings() {
1527        let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1528        let exports = extract_css_module_exports(source, false);
1529        let names: Vec<_> = exports
1530            .iter()
1531            .filter_map(|e| match &e.name {
1532                ExportName::Named(n) => Some(n.as_str()),
1533                ExportName::Default => None,
1534            })
1535            .collect();
1536        assert_eq!(names, vec!["real", "also-real"]);
1537        for export in &exports {
1538            let span = export.span;
1539            let slice = &source[span.start as usize..span.end as usize];
1540            match &export.name {
1541                ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1542                ExportName::Default => unreachable!("CSS modules emit only named exports"),
1543            }
1544        }
1545    }
1546
1547    #[test]
1548    fn span_deduplicates_to_first_occurrence() {
1549        let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1550        let exports = extract_css_module_exports(source, false);
1551        assert_eq!(exports.len(), 1);
1552        let (line, _col) = span_line_col(source, exports[0].span.start);
1553        assert_eq!(
1554            line, 1,
1555            "first occurrence wins for deduplicated class names"
1556        );
1557    }
1558
1559    #[test]
1560    fn span_inside_media_query() {
1561        let source =
1562            "@media (max-width: 768px) {\n  .mobile { display: block; }\n  .desktop { }\n}\n";
1563        let exports = extract_css_module_exports(source, false);
1564        let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1565            .iter()
1566            .filter_map(|e| match &e.name {
1567                ExportName::Named(n) => Some((n.as_str(), e.span)),
1568                ExportName::Default => None,
1569            })
1570            .collect();
1571        let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1572        let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1573        assert_eq!(mobile_line, 2);
1574        assert_eq!(desktop_line, 3);
1575    }
1576
1577    #[test]
1578    fn at_layer_only_module_emits_no_exports() {
1579        let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1580        assert!(exports.is_empty());
1581    }
1582
1583    #[test]
1584    fn parse_css_to_module_resolves_real_line_offsets() {
1585        let source = "\n\n\n\n.foo { color: red; }\n";
1586        let info = parse_css_to_module(
1587            fallow_types::discover::FileId(0),
1588            Path::new("Component.module.css"),
1589            source,
1590            0,
1591        );
1592        assert_eq!(info.exports.len(), 1);
1593        let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1594            &info.line_offsets,
1595            info.exports[0].span.start,
1596        );
1597        assert_eq!(line, 5, "downstream line must equal the source line");
1598    }
1599
1600    fn theme_token_names(source: &str) -> Vec<String> {
1601        scan_theme_blocks(source)
1602            .tokens
1603            .into_iter()
1604            .map(|t| t.name)
1605            .collect()
1606    }
1607
1608    #[test]
1609    fn theme_single_block_collects_tokens() {
1610        let names = theme_token_names("@theme { --color-brand: #f00; --radius-card: 8px; }");
1611        assert_eq!(names, vec!["color-brand", "radius-card"]);
1612    }
1613
1614    #[test]
1615    fn theme_dashed_multi_segment_names() {
1616        let names = theme_token_names(
1617            "@theme {\n  --font-weight-heavy: 900;\n  --inset-shadow-glow: 0 0 4px red;\n}",
1618        );
1619        assert_eq!(names, vec!["font-weight-heavy", "inset-shadow-glow"]);
1620    }
1621
1622    #[test]
1623    fn theme_inline_and_static_modifiers() {
1624        assert_eq!(
1625            theme_token_names("@theme inline { --color-a: red; }"),
1626            vec!["color-a"]
1627        );
1628        assert_eq!(
1629            theme_token_names("@theme static { --color-b: red; }"),
1630            vec!["color-b"]
1631        );
1632    }
1633
1634    #[test]
1635    fn theme_multiple_blocks_union() {
1636        let names = theme_token_names(
1637            "@theme { --color-a: red; }\n.x { color: blue; }\n@theme { --spacing-gutter: 1rem; }",
1638        );
1639        assert_eq!(names, vec!["color-a", "spacing-gutter"]);
1640    }
1641
1642    #[test]
1643    fn theme_reset_form_excluded() {
1644        // `--color-*: initial` is a namespace reset directive, not a token.
1645        let names = theme_token_names("@theme { --color-*: initial; --color-brand: red; }");
1646        assert_eq!(names, vec!["color-brand"]);
1647    }
1648
1649    #[test]
1650    fn theme_no_block_yields_nothing() {
1651        assert!(theme_token_names(".x { --color-brand: red; }").is_empty());
1652    }
1653
1654    #[test]
1655    fn theme_line_numbers() {
1656        let scan = scan_theme_blocks("@theme {\n  --color-a: red;\n  --radius-b: 4px;\n}");
1657        assert_eq!(scan.tokens[0].line, 2);
1658        assert_eq!(scan.tokens[1].line, 3);
1659    }
1660
1661    #[test]
1662    fn theme_token_backs_token_via_var() {
1663        let scan = scan_theme_blocks(
1664            "@theme {\n  --color-brand: #f00;\n  --color-button: var(--color-brand);\n}",
1665        );
1666        assert!(scan.theme_var_reads.contains(&"color-brand".to_string()));
1667    }
1668
1669    #[test]
1670    fn theme_nested_keyframes_body_not_collected() {
1671        // `@keyframes` inside `@theme` (for `--animate-*`) must not surface its
1672        // step selectors or interior as theme tokens.
1673        let names = theme_token_names(
1674            "@theme {\n  --animate-spin: spin 1s linear infinite;\n  @keyframes spin { from { --x: 0; } to { --y: 1; } }\n}",
1675        );
1676        assert_eq!(names, vec!["animate-spin"]);
1677    }
1678
1679    #[test]
1680    fn theme_comment_block_ignored() {
1681        let names = theme_token_names("/* @theme { --color-fake: red; } */ .x { color: blue; }");
1682        assert!(names.is_empty(), "got {names:?}");
1683    }
1684
1685    #[test]
1686    fn theme_deduplicates_repeated_token() {
1687        let names = theme_token_names("@theme { --color-a: red; --color-a: blue; }");
1688        assert_eq!(names, vec!["color-a"]);
1689    }
1690
1691    #[test]
1692    fn apply_tokens_basic() {
1693        let tokens = extract_apply_tokens(".panel { @apply rounded-card font-bold; }");
1694        assert_eq!(tokens, vec!["rounded-card", "font-bold"]);
1695    }
1696
1697    #[test]
1698    fn apply_tokens_strips_important() {
1699        let tokens = extract_apply_tokens(".x { @apply text-brand! font-bold !important; }");
1700        assert_eq!(tokens, vec!["text-brand", "font-bold"]);
1701    }
1702
1703    #[test]
1704    fn apply_tokens_ignored_in_comments() {
1705        let tokens = extract_apply_tokens("/* @apply hidden-token; */ .x { color: red; }");
1706        assert!(tokens.is_empty(), "got {tokens:?}");
1707    }
1708}