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
6use std::path::Path;
7use std::sync::LazyLock;
8
9use oxc_span::Span;
10
11use crate::{ExportInfo, ExportName, ImportInfo, ImportedName, ModuleInfo, VisibilityTag};
12use fallow_types::discover::FileId;
13
14/// Regex to extract CSS @import sources.
15/// Matches: @import "path"; @import 'path'; @import url("path"); @import url('path'); @import url(path);
16static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
17    crate::static_regex(
18        r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
19    )
20});
21
22/// Regex to extract SCSS @use and @forward sources.
23/// Matches: @use "path"; @use 'path'; @forward "path"; @forward 'path';
24static SCSS_USE_RE: LazyLock<regex::Regex> =
25    LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
26
27/// Regex to extract Tailwind CSS @plugin sources.
28/// Matches: @plugin "package"; @plugin 'package'; @plugin "./local-plugin.js";
29static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
30    LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
31
32/// Regex to extract @apply class references.
33/// Matches: @apply class1 class2 class3;
34static CSS_APPLY_RE: LazyLock<regex::Regex> =
35    LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
36
37/// Regex to extract @tailwind directives.
38/// Matches: @tailwind base; @tailwind components; @tailwind utilities;
39static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
40    LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
41
42/// Regex to match CSS block comments (`/* ... */`) for stripping before extraction.
43static CSS_COMMENT_RE: LazyLock<regex::Regex> =
44    LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
45
46/// Regex to match SCSS single-line comments (`// ...`) for stripping before extraction.
47static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
48    LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
49
50/// Regex to extract CSS class names from selectors.
51/// Matches `.className` in selectors. Applied after stripping comments, strings, and URLs.
52static CSS_CLASS_RE: LazyLock<regex::Regex> =
53    LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
54
55/// Regex to strip quoted strings and `url(...)` content from CSS before class extraction.
56/// Prevents false positives from `content: ".foo"` and `url(./path/file.ext)`.
57static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
58    LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
59
60/// Regex to strip the prelude of `@layer` and `@import` at-rules before
61/// CSS-Modules class extraction. Matches the `@keyword` plus everything up to
62/// (but not including) the next `;` or `{`, so block bodies are preserved.
63///
64/// Narrow allowlist by design (issue #540): only at-rules whose preludes
65/// legitimately carry dot-separated identifiers without selector semantics are
66/// stripped. `@layer foo.bar` (CSS Cascading & Inheritance L5) lists layer
67/// names; `@import url("x.css") layer(theme.button)` carries a parenthesised
68/// layer reference. `@scope (.foo) to (.bar)` keeps its existing behavior
69/// because the prelude IS a selector list and `.foo` / `.bar` are real class
70/// references that the user may want to surface as exports.
71static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
72    LazyLock::new(|| crate::static_regex(r"@(?:layer|import)\b[^;{]*"));
73
74pub(crate) fn is_css_file(path: &Path) -> bool {
75    path.extension()
76        .and_then(|e| e.to_str())
77        .is_some_and(|ext| ext == "css" || ext == "scss")
78}
79
80/// A CSS import source with both the literal source and fallow's resolver-normalized form.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct CssImportSource {
83    /// The import source exactly as it appeared in `@import` / `@use` / `@forward` / `@plugin`.
84    pub raw: String,
85    /// The source normalized for fallow's resolver (`variables` -> `./variables` in SCSS).
86    pub normalized: String,
87    /// Whether this source came from Tailwind CSS `@plugin`.
88    pub is_plugin: bool,
89    /// Span of the source specifier in the original CSS/SCSS input.
90    pub span: Span,
91}
92
93fn is_css_module_file(path: &Path) -> bool {
94    is_css_file(path)
95        && path
96            .file_stem()
97            .and_then(|s| s.to_str())
98            .is_some_and(|stem| stem.ends_with(".module"))
99}
100
101/// Returns true if a CSS import source is a remote URL or data URI that should be skipped.
102fn is_css_url_import(source: &str) -> bool {
103    source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
104}
105
106/// Normalize a CSS/SCSS import path to use `./` prefix for relative paths.
107/// Bare file names such as `reset.css` stay relative for CSS ergonomics, while
108/// package subpaths such as `tailwindcss/theme.css` stay bare so bundler-style
109/// package CSS imports resolve through `node_modules`.
110///
111/// When `is_scss` is true, extensionless specifiers that are not SCSS built-in
112/// modules (`sass:*`) are treated as relative imports (SCSS partial convention).
113/// This handles `@use 'variables'` resolving to `./_variables.scss`.
114///
115/// Scoped npm packages (`@scope/pkg`) are always kept bare, even when they have
116/// CSS extensions (e.g., `@fontsource/monaspace-neon/400.css`). Bundlers like
117/// Vite resolve these from node_modules, not as relative paths.
118fn normalize_css_import_path(path: String, is_scss: bool) -> String {
119    if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
120        return path;
121    }
122    if path.starts_with('@') && path.contains('/') {
123        return path;
124    }
125    let path_ref = std::path::Path::new(&path);
126    if !is_scss
127        && path.contains('/')
128        && path_ref
129            .extension()
130            .and_then(|e| e.to_str())
131            .is_some_and(is_style_extension)
132    {
133        return path;
134    }
135    let ext = std::path::Path::new(&path)
136        .extension()
137        .and_then(|e| e.to_str());
138    match ext {
139        Some(e) if is_style_extension(e) => format!("./{path}"),
140        _ => {
141            if is_scss && !path.contains(':') {
142                format!("./{path}")
143            } else {
144                path
145            }
146        }
147    }
148}
149
150fn is_style_extension(ext: &str) -> bool {
151    ext.eq_ignore_ascii_case("css")
152        || ext.eq_ignore_ascii_case("scss")
153        || ext.eq_ignore_ascii_case("sass")
154        || ext.eq_ignore_ascii_case("less")
155}
156
157/// Strip comments from CSS/SCSS source to avoid matching directives inside comments.
158#[cfg(test)]
159fn strip_css_comments(source: &str, is_scss: bool) -> String {
160    let stripped = CSS_COMMENT_RE.replace_all(source, "");
161    if is_scss {
162        SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
163    } else {
164        stripped.into_owned()
165    }
166}
167
168fn mask_css_comments(source: &str, is_scss: bool) -> String {
169    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
170    if is_scss {
171        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
172    }
173    masked
174}
175
176/// Normalize a Tailwind CSS `@plugin` target.
177///
178/// Unlike SCSS `@use`, extensionless targets such as `daisyui` are package
179/// specifiers, not local partials. Keep bare specifiers bare and only preserve
180/// explicit relative/root-relative paths.
181fn normalize_css_plugin_path(path: String) -> String {
182    path
183}
184
185/// Extract `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
186///
187/// Returns both the raw source and the normalized source. URL imports
188/// (`http://`, `https://`, `data:`) are skipped. Use [`extract_css_imports`]
189/// when only the normalized form is needed.
190#[must_use]
191pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
192    let stripped = mask_css_comments(source, is_scss);
193    let mut out = Vec::new();
194
195    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
196        let raw = cap.get(1).or_else(|| cap.get(2)).or_else(|| cap.get(3));
197        if let Some(m) = raw {
198            let (src, span) = trimmed_match_with_span(m);
199            if !src.is_empty() && !is_css_url_import(&src) {
200                out.push(CssImportSource {
201                    normalized: normalize_css_import_path(src.clone(), is_scss),
202                    raw: src,
203                    is_plugin: false,
204                    span,
205                });
206            }
207        }
208    }
209
210    if is_scss {
211        for cap in SCSS_USE_RE.captures_iter(&stripped) {
212            if let Some(m) = cap.get(1) {
213                let (raw, span) = trimmed_match_with_span(m);
214                out.push(CssImportSource {
215                    normalized: normalize_css_import_path(raw.clone(), true),
216                    raw,
217                    is_plugin: false,
218                    span,
219                });
220            }
221        }
222    }
223
224    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
225        if let Some(m) = cap.get(1) {
226            let (raw, span) = trimmed_match_with_span(m);
227            if !raw.is_empty() && !is_css_url_import(&raw) {
228                out.push(CssImportSource {
229                    normalized: normalize_css_plugin_path(raw.clone()),
230                    raw,
231                    is_plugin: true,
232                    span,
233                });
234            }
235        }
236    }
237
238    out
239}
240
241fn trimmed_match_with_span(m: regex::Match<'_>) -> (String, Span) {
242    let raw = m.as_str();
243    let trimmed_start = raw.len() - raw.trim_start().len();
244    let trimmed_end = raw.trim_end().len();
245    let start = m.start() + trimmed_start;
246    let end = m.start() + trimmed_end;
247    (raw.trim().to_string(), Span::new(start as u32, end as u32))
248}
249
250/// Extract normalized `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
251///
252/// Returns specifiers normalized via `normalize_css_import_path`. URL imports
253/// (`http://`, `https://`, `data:`) are skipped. Used by callers that only need
254/// entry/dependency source paths; callers that need import kind information
255/// should use [`extract_css_import_sources`].
256#[must_use]
257pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
258    extract_css_import_sources(source, is_scss)
259        .into_iter()
260        .map(|source| source.normalized)
261        .collect()
262}
263
264/// Mask every regex match in `src` with ASCII spaces (`0x20`) of equal byte
265/// length, so byte offsets in the returned string correspond 1:1 to byte
266/// offsets in the original.
267///
268/// Used to neutralise CSS comments, quoted strings, `url(...)`, and at-rule
269/// preludes before scanning for `.class` selectors, while preserving the
270/// original-source positions that callers need to populate `ExportInfo.span`
271/// (issue #549). The `regex` crate guarantees match boundaries respect UTF-8
272/// char boundaries, so the masked buffer is always valid UTF-8.
273fn mask_with_whitespace(src: &str, re: &regex::Regex) -> String {
274    let mut out = String::with_capacity(src.len());
275    let mut cursor = 0;
276    for m in re.find_iter(src) {
277        out.push_str(&src[cursor..m.start()]);
278        for _ in m.start()..m.end() {
279            out.push(' ');
280        }
281        cursor = m.end();
282    }
283    out.push_str(&src[cursor..]);
284    out
285}
286
287/// Extract class names from a CSS module file as named exports.
288///
289/// Each emitted [`ExportInfo`] carries a [`Span`] pointing at the bare class
290/// name in the ORIGINAL `source` (no leading dot), so downstream
291/// `compute_line_offsets` resolves the real declaration line and column
292/// instead of falling back to line:1 col:0 (issue #549).
293pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
294    let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
295    if is_scss {
296        masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
297    }
298    masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
299    masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
300
301    let mut seen = rustc_hash::FxHashSet::default();
302    let mut exports = Vec::new();
303    for cap in CSS_CLASS_RE.captures_iter(&masked) {
304        if let Some(m) = cap.get(1) {
305            let class_name = m.as_str().to_string();
306            if seen.insert(class_name.clone()) {
307                #[expect(
308                    clippy::cast_possible_truncation,
309                    reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
310                )]
311                let span = Span::new(m.start() as u32, m.end() as u32);
312                exports.push(ExportInfo {
313                    name: ExportName::Named(class_name),
314                    local_name: None,
315                    is_type_only: false,
316                    visibility: VisibilityTag::None,
317                    span,
318                    members: Vec::new(),
319                    is_side_effect_used: false,
320                    super_class: None,
321                });
322            }
323        }
324    }
325    exports
326}
327
328/// Parse a CSS/SCSS file, extracting @import, @use, @forward, @plugin, @apply, and @tailwind directives.
329pub(crate) fn parse_css_to_module(
330    file_id: FileId,
331    path: &Path,
332    source: &str,
333    content_hash: u64,
334) -> ModuleInfo {
335    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
336    let is_scss = path
337        .extension()
338        .and_then(|e| e.to_str())
339        .is_some_and(|ext| ext == "scss");
340
341    let stripped = mask_css_comments(source, is_scss);
342
343    let mut imports = Vec::new();
344
345    for source in extract_css_import_sources(source, is_scss) {
346        imports.push(ImportInfo {
347            source: source.normalized,
348            imported_name: if source.is_plugin {
349                ImportedName::Default
350            } else {
351                ImportedName::SideEffect
352            },
353            local_name: String::new(),
354            is_type_only: false,
355            from_style: false,
356            span: source.span,
357            source_span: source.span,
358        });
359    }
360
361    let has_apply = CSS_APPLY_RE.is_match(&stripped);
362    let has_tailwind = CSS_TAILWIND_RE.is_match(&stripped);
363    if has_apply || has_tailwind {
364        imports.push(ImportInfo {
365            source: "tailwindcss".to_string(),
366            imported_name: ImportedName::SideEffect,
367            local_name: String::new(),
368            is_type_only: false,
369            from_style: false,
370            span: Span::default(),
371            source_span: Span::default(),
372        });
373    }
374
375    let exports = if is_css_module_file(path) {
376        extract_css_module_exports(source, is_scss)
377    } else {
378        Vec::new()
379    };
380
381    ModuleInfo {
382        file_id,
383        exports,
384        imports,
385        re_exports: Vec::new(),
386        dynamic_imports: Vec::new(),
387        dynamic_import_patterns: Vec::new(),
388        require_calls: Vec::new(),
389        package_path_references: Vec::new(),
390        member_accesses: Vec::new(),
391        whole_object_uses: Vec::new(),
392        has_cjs_exports: false,
393        has_angular_component_template_url: false,
394        content_hash,
395        suppressions: parsed_suppressions.suppressions,
396        unknown_suppression_kinds: parsed_suppressions.unknown_kinds,
397        unused_import_bindings: Vec::new(),
398        type_referenced_import_bindings: Vec::new(),
399        value_referenced_import_bindings: Vec::new(),
400        line_offsets: fallow_types::extract::compute_line_offsets(source),
401        complexity: Vec::new(),
402        flag_uses: Vec::new(),
403        class_heritage: vec![],
404        injection_tokens: vec![],
405        local_type_declarations: Vec::new(),
406        public_signature_type_references: Vec::new(),
407        namespace_object_aliases: Vec::new(),
408        iconify_prefixes: Vec::new(),
409        iconify_icon_names: Vec::new(),
410        auto_import_candidates: Vec::new(),
411        directives: Vec::new(),
412        security_sinks: Vec::new(),
413        security_sinks_skipped: 0,
414        tainted_bindings: Vec::new(),
415        sanitized_sink_args: Vec::new(),
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422
423    /// Helper to collect export names as strings from `extract_css_module_exports`.
424    fn export_names(source: &str) -> Vec<String> {
425        extract_css_module_exports(source, false)
426            .into_iter()
427            .filter_map(|e| match e.name {
428                ExportName::Named(n) => Some(n),
429                ExportName::Default => None,
430            })
431            .collect()
432    }
433
434    #[test]
435    fn is_css_file_css() {
436        assert!(is_css_file(Path::new("styles.css")));
437    }
438
439    #[test]
440    fn is_css_file_scss() {
441        assert!(is_css_file(Path::new("styles.scss")));
442    }
443
444    #[test]
445    fn is_css_file_rejects_js() {
446        assert!(!is_css_file(Path::new("app.js")));
447    }
448
449    #[test]
450    fn is_css_file_rejects_ts() {
451        assert!(!is_css_file(Path::new("app.ts")));
452    }
453
454    #[test]
455    fn is_css_file_rejects_less() {
456        assert!(!is_css_file(Path::new("styles.less")));
457    }
458
459    #[test]
460    fn is_css_file_rejects_no_extension() {
461        assert!(!is_css_file(Path::new("Makefile")));
462    }
463
464    #[test]
465    fn is_css_module_file_module_css() {
466        assert!(is_css_module_file(Path::new("Component.module.css")));
467    }
468
469    #[test]
470    fn is_css_module_file_module_scss() {
471        assert!(is_css_module_file(Path::new("Component.module.scss")));
472    }
473
474    #[test]
475    fn is_css_module_file_rejects_plain_css() {
476        assert!(!is_css_module_file(Path::new("styles.css")));
477    }
478
479    #[test]
480    fn is_css_module_file_rejects_plain_scss() {
481        assert!(!is_css_module_file(Path::new("styles.scss")));
482    }
483
484    #[test]
485    fn is_css_module_file_rejects_module_js() {
486        assert!(!is_css_module_file(Path::new("utils.module.js")));
487    }
488
489    #[test]
490    fn extracts_single_class() {
491        let names = export_names(".foo { color: red; }");
492        assert_eq!(names, vec!["foo"]);
493    }
494
495    #[test]
496    fn extracts_multiple_classes() {
497        let names = export_names(".foo { } .bar { }");
498        assert_eq!(names, vec!["foo", "bar"]);
499    }
500
501    #[test]
502    fn extracts_nested_classes() {
503        let names = export_names(".foo .bar { color: red; }");
504        assert!(names.contains(&"foo".to_string()));
505        assert!(names.contains(&"bar".to_string()));
506    }
507
508    #[test]
509    fn extracts_hyphenated_class() {
510        let names = export_names(".my-class { }");
511        assert_eq!(names, vec!["my-class"]);
512    }
513
514    #[test]
515    fn extracts_camel_case_class() {
516        let names = export_names(".myClass { }");
517        assert_eq!(names, vec!["myClass"]);
518    }
519
520    #[test]
521    fn extracts_underscore_class() {
522        let names = export_names("._hidden { } .__wrapper { }");
523        assert!(names.contains(&"_hidden".to_string()));
524        assert!(names.contains(&"__wrapper".to_string()));
525    }
526
527    #[test]
528    fn pseudo_selector_hover() {
529        let names = export_names(".foo:hover { color: blue; }");
530        assert_eq!(names, vec!["foo"]);
531    }
532
533    #[test]
534    fn pseudo_selector_focus() {
535        let names = export_names(".input:focus { outline: none; }");
536        assert_eq!(names, vec!["input"]);
537    }
538
539    #[test]
540    fn pseudo_element_before() {
541        let names = export_names(".icon::before { content: ''; }");
542        assert_eq!(names, vec!["icon"]);
543    }
544
545    #[test]
546    fn combined_pseudo_selectors() {
547        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
548        assert_eq!(names, vec!["btn"]);
549    }
550
551    #[test]
552    fn classes_inside_media_query() {
553        let names = export_names(
554            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
555        );
556        assert!(names.contains(&"mobile-nav".to_string()));
557        assert!(names.contains(&"desktop-nav".to_string()));
558    }
559
560    #[test]
561    fn classes_inside_multi_line_media_query() {
562        let names =
563            export_names("@media\n  screen and (min-width: 600px)\n{\n  .real { color: red; }\n}");
564        assert_eq!(names, vec!["real"]);
565    }
566
567    #[test]
568    fn at_layer_statement_does_not_export() {
569        let names = export_names("@layer foo.bar;");
570        assert!(names.is_empty(), "got {names:?}");
571        let names = export_names("@layer foo.bar, foo.baz;");
572        assert!(names.is_empty(), "got {names:?}");
573    }
574
575    #[test]
576    fn at_layer_block_keeps_body_classes() {
577        let names = export_names("@layer foo.bar { .root { color: red; } }");
578        assert_eq!(names, vec!["root"]);
579    }
580
581    #[test]
582    fn at_layer_multiline_prelude_keeps_body_classes() {
583        let names = export_names("@layer\n  foo.bar\n{ .root { color: red; } }");
584        assert_eq!(names, vec!["root"]);
585    }
586
587    #[test]
588    fn at_layer_with_nested_media_keeps_body() {
589        let names =
590            export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
591        assert_eq!(names, vec!["real"]);
592    }
593
594    #[test]
595    fn at_import_with_layer_attribute_does_not_export() {
596        let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
597        assert!(names.is_empty(), "got {names:?}");
598    }
599
600    #[test]
601    fn class_then_at_layer_does_not_leak_prelude() {
602        let names =
603            export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
604        assert_eq!(names, vec!["outer", "inner"]);
605    }
606
607    #[test]
608    fn at_scope_keeps_selector_list_classes() {
609        let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
610        assert!(names.contains(&"parent".to_string()), "got {names:?}");
611        assert!(names.contains(&"child".to_string()), "got {names:?}");
612        assert!(names.contains(&"title".to_string()), "got {names:?}");
613    }
614
615    #[test]
616    fn at_keyframes_numeric_step_is_not_class() {
617        let names = export_names(
618            "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
619        );
620        assert!(names.is_empty(), "got {names:?}");
621    }
622
623    #[test]
624    fn at_webkit_keyframes_keeps_body_classes() {
625        let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
626        assert_eq!(names, vec!["real"]);
627    }
628
629    #[test]
630    fn deduplicates_repeated_class() {
631        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
632        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
633    }
634
635    #[test]
636    fn empty_source() {
637        let names = export_names("");
638        assert!(names.is_empty());
639    }
640
641    #[test]
642    fn no_classes() {
643        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
644        assert!(names.is_empty());
645    }
646
647    #[test]
648    fn ignores_classes_in_block_comments() {
649        let names = export_names("/* .fake { } */ .real { }");
650        assert!(!names.contains(&"fake".to_string()));
651        assert!(names.contains(&"real".to_string()));
652    }
653
654    #[test]
655    fn ignores_classes_in_scss_line_comments() {
656        let exports = extract_css_module_exports("// .fake\n.real { }", true);
657        let names: Vec<_> = exports
658            .iter()
659            .filter_map(|e| match &e.name {
660                ExportName::Named(n) => Some(n.as_str()),
661                ExportName::Default => None,
662            })
663            .collect();
664        assert_eq!(names, vec!["real"]);
665    }
666
667    #[test]
668    fn ignores_classes_in_strings() {
669        let names = export_names(r#".real { content: ".fake"; }"#);
670        assert!(names.contains(&"real".to_string()));
671        assert!(!names.contains(&"fake".to_string()));
672    }
673
674    #[test]
675    fn ignores_classes_in_url() {
676        let names = export_names(".real { background: url(./images/hero.png); }");
677        assert!(names.contains(&"real".to_string()));
678        assert!(!names.contains(&"png".to_string()));
679    }
680
681    #[test]
682    fn strip_css_block_comment() {
683        let result = strip_css_comments("/* removed */ .kept { }", false);
684        assert!(!result.contains("removed"));
685        assert!(result.contains(".kept"));
686    }
687
688    #[test]
689    fn strip_scss_line_comment() {
690        let result = strip_css_comments("// removed\n.kept { }", true);
691        assert!(!result.contains("removed"));
692        assert!(result.contains(".kept"));
693    }
694
695    #[test]
696    fn strip_scss_preserves_css_outside_comments() {
697        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
698        let result = strip_css_comments(source, true);
699        assert!(result.contains(".visible"));
700    }
701
702    #[test]
703    fn url_import_http() {
704        assert!(is_css_url_import("http://example.com/style.css"));
705    }
706
707    #[test]
708    fn url_import_https() {
709        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
710    }
711
712    #[test]
713    fn url_import_data() {
714        assert!(is_css_url_import("data:text/css;base64,abc"));
715    }
716
717    #[test]
718    fn url_import_local_not_skipped() {
719        assert!(!is_css_url_import("./local.css"));
720    }
721
722    #[test]
723    fn url_import_bare_specifier_not_skipped() {
724        assert!(!is_css_url_import("tailwindcss"));
725    }
726
727    #[test]
728    fn normalize_relative_dot_path_unchanged() {
729        assert_eq!(
730            normalize_css_import_path("./reset.css".to_string(), false),
731            "./reset.css"
732        );
733    }
734
735    #[test]
736    fn normalize_parent_relative_path_unchanged() {
737        assert_eq!(
738            normalize_css_import_path("../shared.scss".to_string(), false),
739            "../shared.scss"
740        );
741    }
742
743    #[test]
744    fn normalize_absolute_path_unchanged() {
745        assert_eq!(
746            normalize_css_import_path("/styles/main.css".to_string(), false),
747            "/styles/main.css"
748        );
749    }
750
751    #[test]
752    fn normalize_url_unchanged() {
753        assert_eq!(
754            normalize_css_import_path("https://example.com/style.css".to_string(), false),
755            "https://example.com/style.css"
756        );
757    }
758
759    #[test]
760    fn normalize_bare_css_gets_dot_slash() {
761        assert_eq!(
762            normalize_css_import_path("app.css".to_string(), false),
763            "./app.css"
764        );
765    }
766
767    #[test]
768    fn normalize_css_package_subpath_stays_bare() {
769        assert_eq!(
770            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
771            "tailwindcss/theme.css"
772        );
773    }
774
775    #[test]
776    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
777        assert_eq!(
778            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
779            "highlight.js/styles/github.css"
780        );
781    }
782
783    #[test]
784    fn normalize_bare_scss_gets_dot_slash() {
785        assert_eq!(
786            normalize_css_import_path("vars.scss".to_string(), false),
787            "./vars.scss"
788        );
789    }
790
791    #[test]
792    fn normalize_bare_sass_gets_dot_slash() {
793        assert_eq!(
794            normalize_css_import_path("main.sass".to_string(), false),
795            "./main.sass"
796        );
797    }
798
799    #[test]
800    fn normalize_bare_less_gets_dot_slash() {
801        assert_eq!(
802            normalize_css_import_path("theme.less".to_string(), false),
803            "./theme.less"
804        );
805    }
806
807    #[test]
808    fn normalize_bare_js_extension_stays_bare() {
809        assert_eq!(
810            normalize_css_import_path("module.js".to_string(), false),
811            "module.js"
812        );
813    }
814
815    #[test]
816    fn normalize_scss_bare_partial_gets_dot_slash() {
817        assert_eq!(
818            normalize_css_import_path("variables".to_string(), true),
819            "./variables"
820        );
821    }
822
823    #[test]
824    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
825        assert_eq!(
826            normalize_css_import_path("base/reset".to_string(), true),
827            "./base/reset"
828        );
829    }
830
831    #[test]
832    fn normalize_scss_builtin_stays_bare() {
833        assert_eq!(
834            normalize_css_import_path("sass:math".to_string(), true),
835            "sass:math"
836        );
837    }
838
839    #[test]
840    fn normalize_scss_relative_path_unchanged() {
841        assert_eq!(
842            normalize_css_import_path("../styles/variables".to_string(), true),
843            "../styles/variables"
844        );
845    }
846
847    #[test]
848    fn normalize_css_bare_extensionless_stays_bare() {
849        assert_eq!(
850            normalize_css_import_path("tailwindcss".to_string(), false),
851            "tailwindcss"
852        );
853    }
854
855    #[test]
856    fn normalize_scoped_package_with_css_extension_stays_bare() {
857        assert_eq!(
858            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
859            "@fontsource/monaspace-neon/400.css"
860        );
861    }
862
863    #[test]
864    fn normalize_scoped_package_with_scss_extension_stays_bare() {
865        assert_eq!(
866            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
867            "@company/design-system/tokens.scss"
868        );
869    }
870
871    #[test]
872    fn normalize_scoped_package_without_extension_stays_bare() {
873        assert_eq!(
874            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
875            "@fallow/design-system/styles"
876        );
877    }
878
879    #[test]
880    fn normalize_scoped_package_extensionless_scss_stays_bare() {
881        assert_eq!(
882            normalize_css_import_path("@company/tokens".to_string(), true),
883            "@company/tokens"
884        );
885    }
886
887    #[test]
888    fn normalize_path_alias_with_css_extension_stays_bare() {
889        assert_eq!(
890            normalize_css_import_path("@/components/Button.css".to_string(), false),
891            "@/components/Button.css"
892        );
893    }
894
895    #[test]
896    fn normalize_path_alias_extensionless_stays_bare() {
897        assert_eq!(
898            normalize_css_import_path("@/styles/variables".to_string(), false),
899            "@/styles/variables"
900        );
901    }
902
903    #[test]
904    fn strip_css_no_comments() {
905        let source = ".foo { color: red; }";
906        assert_eq!(strip_css_comments(source, false), source);
907    }
908
909    #[test]
910    fn strip_css_multiple_block_comments() {
911        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
912        let result = strip_css_comments(source, false);
913        assert!(!result.contains("comment-one"));
914        assert!(!result.contains("comment-two"));
915        assert!(result.contains(".foo"));
916        assert!(result.contains(".bar"));
917    }
918
919    #[test]
920    fn strip_scss_does_not_affect_non_scss() {
921        let source = "// this stays\n.foo { }";
922        let result = strip_css_comments(source, false);
923        assert!(result.contains("// this stays"));
924    }
925
926    #[test]
927    fn css_module_parses_suppressions() {
928        let info = parse_css_to_module(
929            fallow_types::discover::FileId(0),
930            Path::new("Component.module.css"),
931            "/* fallow-ignore-file */\n.btn { color: red; }",
932            0,
933        );
934        assert!(!info.suppressions.is_empty());
935        assert_eq!(info.suppressions[0].line, 0);
936    }
937
938    #[test]
939    fn extracts_class_starting_with_underscore() {
940        let names = export_names("._private { } .__dunder { }");
941        assert!(names.contains(&"_private".to_string()));
942        assert!(names.contains(&"__dunder".to_string()));
943    }
944
945    #[test]
946    fn ignores_id_selectors() {
947        let names = export_names("#myId { color: red; }");
948        assert!(!names.contains(&"myId".to_string()));
949    }
950
951    #[test]
952    fn ignores_element_selectors() {
953        let names = export_names("div { color: red; } span { }");
954        assert!(names.is_empty());
955    }
956
957    #[test]
958    fn extract_css_imports_at_import_quoted() {
959        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
960        assert_eq!(imports, vec!["./reset.css"]);
961    }
962
963    #[test]
964    fn extract_css_imports_package_subpath_stays_bare() {
965        let imports =
966            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
967        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
968    }
969
970    #[test]
971    fn extract_css_imports_at_import_url() {
972        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
973        assert_eq!(imports, vec!["./reset.css"]);
974    }
975
976    #[test]
977    fn extract_css_imports_skips_remote_urls() {
978        let imports =
979            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
980        assert!(imports.is_empty());
981    }
982
983    #[test]
984    fn extract_css_imports_scss_use_normalizes_partial() {
985        let imports = extract_css_imports(r#"@use "variables";"#, true);
986        assert_eq!(imports, vec!["./variables"]);
987    }
988
989    #[test]
990    fn extract_css_imports_scss_forward_normalizes_partial() {
991        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
992        assert_eq!(imports, vec!["./tokens"]);
993    }
994
995    #[test]
996    fn extract_css_imports_skips_comments() {
997        let imports = extract_css_imports(
998            r#"/* @import "./hidden.scss"; */
999@use "real";"#,
1000            true,
1001        );
1002        assert_eq!(imports, vec!["./real"]);
1003    }
1004
1005    #[test]
1006    fn extract_css_imports_at_plugin_keeps_package_bare() {
1007        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1008        assert_eq!(imports, vec!["daisyui"]);
1009    }
1010
1011    #[test]
1012    fn extract_css_imports_at_plugin_tracks_relative_file() {
1013        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1014        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1015    }
1016
1017    #[test]
1018    fn extract_css_imports_scss_at_import_kept_relative() {
1019        let imports = extract_css_imports(r"@import 'Foo';", true);
1020        assert_eq!(imports, vec!["./Foo"]);
1021    }
1022
1023    #[test]
1024    fn extract_css_imports_additional_data_string_body() {
1025        let body = r#"@use "./src/styles/global.scss";"#;
1026        let imports = extract_css_imports(body, true);
1027        assert_eq!(imports, vec!["./src/styles/global.scss"]);
1028    }
1029
1030    #[test]
1031    fn mask_with_whitespace_preserves_byte_length() {
1032        let src = "/* hello */ .foo { }";
1033        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1034        assert_eq!(masked.len(), src.len());
1035        assert!(masked.is_char_boundary(src.len()));
1036    }
1037
1038    #[test]
1039    fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1040        let src = "/* \u{2713} */ .foo { }";
1041        let foo_offset = src.find(".foo").expect("`.foo` present");
1042        let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1043        assert_eq!(masked.len(), src.len());
1044        assert_eq!(masked.find(".foo"), Some(foo_offset));
1045    }
1046
1047    /// Resolve a span's start to (line, col) using the same primitives the
1048    /// downstream pipeline uses in `crates/core/src/analyze/unused_exports.rs`.
1049    fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1050        let offsets = fallow_types::extract::compute_line_offsets(source);
1051        fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1052    }
1053
1054    #[test]
1055    fn span_points_at_real_class_declaration_line() {
1056        let source = "\n\n\n\n.foo { color: red; }\n";
1057        let exports = extract_css_module_exports(source, false);
1058        assert_eq!(exports.len(), 1);
1059        let span = exports[0].span;
1060        let (line, col) = span_line_col(source, span.start);
1061        assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1062        assert_eq!(
1063            col, 1,
1064            "column points at `f` in `.foo` (post-dot identifier)"
1065        );
1066        assert_eq!(
1067            &source[span.start as usize..span.end as usize],
1068            "foo",
1069            "span range must slice to the class identifier in the original source"
1070        );
1071    }
1072
1073    #[test]
1074    fn span_survives_multibyte_comment_prefix() {
1075        let source = "/* \u{2713} */\n.foo { }";
1076        let exports = extract_css_module_exports(source, false);
1077        assert_eq!(exports.len(), 1);
1078        let span = exports[0].span;
1079        assert!(
1080            source.is_char_boundary(span.start as usize),
1081            "span.start must lie on a UTF-8 char boundary"
1082        );
1083        assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1084    }
1085
1086    #[test]
1087    fn span_skips_at_layer_prelude_dot_segments() {
1088        let source = "@layer foo.bar { }\n.root { }\n";
1089        let exports = extract_css_module_exports(source, false);
1090        let names: Vec<_> = exports
1091            .iter()
1092            .filter_map(|e| match &e.name {
1093                ExportName::Named(n) => Some(n.as_str()),
1094                ExportName::Default => None,
1095            })
1096            .collect();
1097        assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1098        let span = exports[0].span;
1099        let (line, _col) = span_line_col(source, span.start);
1100        assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1101        assert_eq!(&source[span.start as usize..span.end as usize], "root");
1102    }
1103
1104    #[test]
1105    fn span_skips_classes_in_strings() {
1106        let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1107        let exports = extract_css_module_exports(source, false);
1108        let names: Vec<_> = exports
1109            .iter()
1110            .filter_map(|e| match &e.name {
1111                ExportName::Named(n) => Some(n.as_str()),
1112                ExportName::Default => None,
1113            })
1114            .collect();
1115        assert_eq!(names, vec!["real", "also-real"]);
1116        for export in &exports {
1117            let span = export.span;
1118            let slice = &source[span.start as usize..span.end as usize];
1119            match &export.name {
1120                ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1121                ExportName::Default => unreachable!("CSS modules emit only named exports"),
1122            }
1123        }
1124    }
1125
1126    #[test]
1127    fn span_deduplicates_to_first_occurrence() {
1128        let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1129        let exports = extract_css_module_exports(source, false);
1130        assert_eq!(exports.len(), 1);
1131        let (line, _col) = span_line_col(source, exports[0].span.start);
1132        assert_eq!(
1133            line, 1,
1134            "first occurrence wins for deduplicated class names"
1135        );
1136    }
1137
1138    #[test]
1139    fn span_inside_media_query() {
1140        let source =
1141            "@media (max-width: 768px) {\n  .mobile { display: block; }\n  .desktop { }\n}\n";
1142        let exports = extract_css_module_exports(source, false);
1143        let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1144            .iter()
1145            .filter_map(|e| match &e.name {
1146                ExportName::Named(n) => Some((n.as_str(), e.span)),
1147                ExportName::Default => None,
1148            })
1149            .collect();
1150        let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1151        let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1152        assert_eq!(mobile_line, 2);
1153        assert_eq!(desktop_line, 3);
1154    }
1155
1156    #[test]
1157    fn at_layer_only_module_emits_no_exports() {
1158        let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1159        assert!(exports.is_empty());
1160    }
1161
1162    #[test]
1163    fn parse_css_to_module_resolves_real_line_offsets() {
1164        let source = "\n\n\n\n.foo { color: red; }\n";
1165        let info = parse_css_to_module(
1166            fallow_types::discover::FileId(0),
1167            Path::new("Component.module.css"),
1168            source,
1169            0,
1170        );
1171        assert_eq!(info.exports.len(), 1);
1172        let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1173            &info.line_offsets,
1174            info.exports[0].span.start,
1175        );
1176        assert_eq!(line, 5, "downstream line must equal the source line");
1177    }
1178}