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    regex::Regex::new(r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#)
18        .expect("valid regex")
19});
20
21/// Regex to extract SCSS @use and @forward sources.
22/// Matches: @use "path"; @use 'path'; @forward "path"; @forward 'path';
23static SCSS_USE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
24    regex::Regex::new(r#"@(?:use|forward)\s+["']([^"']+)["']"#).expect("valid regex")
25});
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(|| regex::Regex::new(r#"@plugin\s+["']([^"']+)["']"#).expect("valid regex"));
31
32/// Regex to extract @apply class references.
33/// Matches: @apply class1 class2 class3;
34static CSS_APPLY_RE: LazyLock<regex::Regex> =
35    LazyLock::new(|| regex::Regex::new(r"@apply\s+[^;}\n]+").expect("valid regex"));
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(|| regex::Regex::new(r"@tailwind\s+\w+").expect("valid regex"));
41
42/// Regex to match CSS block comments (`/* ... */`) for stripping before extraction.
43static CSS_COMMENT_RE: LazyLock<regex::Regex> =
44    LazyLock::new(|| regex::Regex::new(r"(?s)/\*.*?\*/").expect("valid regex"));
45
46/// Regex to match SCSS single-line comments (`// ...`) for stripping before extraction.
47static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
48    LazyLock::new(|| regex::Regex::new(r"//[^\n]*").expect("valid regex"));
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(|| regex::Regex::new(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)").expect("valid regex"));
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> = LazyLock::new(|| {
58    regex::Regex::new(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#).expect("valid regex")
59});
60
61pub(crate) fn is_css_file(path: &Path) -> bool {
62    path.extension()
63        .and_then(|e| e.to_str())
64        .is_some_and(|ext| ext == "css" || ext == "scss")
65}
66
67/// A CSS import source with both the literal source and fallow's resolver-normalized form.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct CssImportSource {
70    /// The import source exactly as it appeared in `@import` / `@use` / `@forward` / `@plugin`.
71    pub raw: String,
72    /// The source normalized for fallow's resolver (`variables` -> `./variables` in SCSS).
73    pub normalized: String,
74    /// Whether this source came from Tailwind CSS `@plugin`.
75    pub is_plugin: bool,
76}
77
78fn is_css_module_file(path: &Path) -> bool {
79    is_css_file(path)
80        && path
81            .file_stem()
82            .and_then(|s| s.to_str())
83            .is_some_and(|stem| stem.ends_with(".module"))
84}
85
86/// Returns true if a CSS import source is a remote URL or data URI that should be skipped.
87fn is_css_url_import(source: &str) -> bool {
88    source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
89}
90
91/// Normalize a CSS/SCSS import path to use `./` prefix for relative paths.
92/// Bare file names such as `reset.css` stay relative for CSS ergonomics, while
93/// package subpaths such as `tailwindcss/theme.css` stay bare so bundler-style
94/// package CSS imports resolve through `node_modules`.
95///
96/// When `is_scss` is true, extensionless specifiers that are not SCSS built-in
97/// modules (`sass:*`) are treated as relative imports (SCSS partial convention).
98/// This handles `@use 'variables'` resolving to `./_variables.scss`.
99///
100/// Scoped npm packages (`@scope/pkg`) are always kept bare, even when they have
101/// CSS extensions (e.g., `@fontsource/monaspace-neon/400.css`). Bundlers like
102/// Vite resolve these from node_modules, not as relative paths.
103fn normalize_css_import_path(path: String, is_scss: bool) -> String {
104    if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
105        return path;
106    }
107    // Scoped npm packages (`@scope/...`) are always bare specifiers resolved
108    // from node_modules, regardless of file extension.
109    if path.starts_with('@') && path.contains('/') {
110        return path;
111    }
112    let path_ref = std::path::Path::new(&path);
113    if !is_scss
114        && path.contains('/')
115        && path_ref
116            .extension()
117            .and_then(|e| e.to_str())
118            .is_some_and(is_style_extension)
119    {
120        return path;
121    }
122    // Bare filenames with CSS/SCSS extensions are relative file imports.
123    let ext = std::path::Path::new(&path)
124        .extension()
125        .and_then(|e| e.to_str());
126    match ext {
127        Some(e) if is_style_extension(e) => format!("./{path}"),
128        _ => {
129            // In SCSS, extensionless bare specifiers like `@use 'variables'` are
130            // local partials, not npm packages. SCSS built-in modules (`sass:math`,
131            // `sass:color`) use a colon prefix and should stay bare.
132            if is_scss && !path.contains(':') {
133                format!("./{path}")
134            } else {
135                path
136            }
137        }
138    }
139}
140
141fn is_style_extension(ext: &str) -> bool {
142    ext.eq_ignore_ascii_case("css")
143        || ext.eq_ignore_ascii_case("scss")
144        || ext.eq_ignore_ascii_case("sass")
145        || ext.eq_ignore_ascii_case("less")
146}
147
148/// Strip comments from CSS/SCSS source to avoid matching directives inside comments.
149fn strip_css_comments(source: &str, is_scss: bool) -> String {
150    let stripped = CSS_COMMENT_RE.replace_all(source, "");
151    if is_scss {
152        SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
153    } else {
154        stripped.into_owned()
155    }
156}
157
158/// Normalize a Tailwind CSS `@plugin` target.
159///
160/// Unlike SCSS `@use`, extensionless targets such as `daisyui` are package
161/// specifiers, not local partials. Keep bare specifiers bare and only preserve
162/// explicit relative/root-relative paths.
163fn normalize_css_plugin_path(path: String) -> String {
164    path
165}
166
167/// Extract `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
168///
169/// Returns both the raw source and the normalized source. URL imports
170/// (`http://`, `https://`, `data:`) are skipped. Use [`extract_css_imports`]
171/// when only the normalized form is needed.
172#[must_use]
173pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
174    let stripped = strip_css_comments(source, is_scss);
175    let mut out = Vec::new();
176
177    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
178        let raw = cap
179            .get(1)
180            .or_else(|| cap.get(2))
181            .or_else(|| cap.get(3))
182            .map(|m| m.as_str().trim().to_string());
183        if let Some(src) = raw
184            && !src.is_empty()
185            && !is_css_url_import(&src)
186        {
187            out.push(CssImportSource {
188                normalized: normalize_css_import_path(src.clone(), is_scss),
189                raw: src,
190                is_plugin: false,
191            });
192        }
193    }
194
195    if is_scss {
196        for cap in SCSS_USE_RE.captures_iter(&stripped) {
197            if let Some(m) = cap.get(1) {
198                let raw = m.as_str().to_string();
199                out.push(CssImportSource {
200                    normalized: normalize_css_import_path(raw.clone(), true),
201                    raw,
202                    is_plugin: false,
203                });
204            }
205        }
206    }
207
208    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
209        if let Some(m) = cap.get(1) {
210            let raw = m.as_str().trim().to_string();
211            if !raw.is_empty() && !is_css_url_import(&raw) {
212                out.push(CssImportSource {
213                    normalized: normalize_css_plugin_path(raw.clone()),
214                    raw,
215                    is_plugin: true,
216                });
217            }
218        }
219    }
220
221    out
222}
223
224/// Extract normalized `@import` / `@use` / `@forward` / `@plugin` source paths from a CSS/SCSS string.
225///
226/// Returns specifiers normalized via `normalize_css_import_path`. URL imports
227/// (`http://`, `https://`, `data:`) are skipped. Used by callers that only need
228/// entry/dependency source paths; callers that need import kind information
229/// should use [`extract_css_import_sources`].
230#[must_use]
231pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
232    extract_css_import_sources(source, is_scss)
233        .into_iter()
234        .map(|source| source.normalized)
235        .collect()
236}
237
238/// Extract class names from a CSS module file as named exports.
239pub fn extract_css_module_exports(source: &str) -> Vec<ExportInfo> {
240    let cleaned = CSS_NON_SELECTOR_RE.replace_all(source, "");
241    let mut seen = rustc_hash::FxHashSet::default();
242    let mut exports = Vec::new();
243    for cap in CSS_CLASS_RE.captures_iter(&cleaned) {
244        if let Some(m) = cap.get(1) {
245            let class_name = m.as_str().to_string();
246            if seen.insert(class_name.clone()) {
247                exports.push(ExportInfo {
248                    name: ExportName::Named(class_name),
249                    local_name: None,
250                    is_type_only: false,
251                    visibility: VisibilityTag::None,
252                    span: Span::default(),
253                    members: Vec::new(),
254                    is_side_effect_used: false,
255                    super_class: None,
256                });
257            }
258        }
259    }
260    exports
261}
262
263/// Parse a CSS/SCSS file, extracting @import, @use, @forward, @plugin, @apply, and @tailwind directives.
264pub(crate) fn parse_css_to_module(
265    file_id: FileId,
266    path: &Path,
267    source: &str,
268    content_hash: u64,
269) -> ModuleInfo {
270    let suppressions = crate::suppress::parse_suppressions_from_source(source);
271    let is_scss = path
272        .extension()
273        .and_then(|e| e.to_str())
274        .is_some_and(|ext| ext == "scss");
275
276    // Strip comments before matching to avoid false positives from commented-out code.
277    let stripped = strip_css_comments(source, is_scss);
278
279    let mut imports = Vec::new();
280
281    // Extract @import statements
282    for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
283        let source_path = cap
284            .get(1)
285            .or_else(|| cap.get(2))
286            .or_else(|| cap.get(3))
287            .map(|m| m.as_str().trim().to_string());
288        if let Some(src) = source_path
289            && !src.is_empty()
290            && !is_css_url_import(&src)
291        {
292            // CSS/SCSS @import resolves relative paths without ./ prefix,
293            // so normalize to ./ to avoid bare-specifier misclassification
294            let src = normalize_css_import_path(src, is_scss);
295            imports.push(ImportInfo {
296                source: src,
297                imported_name: ImportedName::SideEffect,
298                local_name: String::new(),
299                is_type_only: false,
300                from_style: false,
301                span: Span::default(),
302                source_span: Span::default(),
303            });
304        }
305    }
306
307    // Extract SCSS @use/@forward statements
308    if is_scss {
309        for cap in SCSS_USE_RE.captures_iter(&stripped) {
310            if let Some(m) = cap.get(1) {
311                imports.push(ImportInfo {
312                    source: normalize_css_import_path(m.as_str().to_string(), true),
313                    imported_name: ImportedName::SideEffect,
314                    local_name: String::new(),
315                    is_type_only: false,
316                    from_style: false,
317                    span: Span::default(),
318                    source_span: Span::default(),
319                });
320            }
321        }
322    }
323
324    // Extract Tailwind CSS @plugin directives. These can reference npm packages
325    // (e.g. `@plugin "daisyui"`) or explicit local plugin files.
326    for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
327        if let Some(m) = cap.get(1) {
328            let source = m.as_str().trim().to_string();
329            if !source.is_empty() && !is_css_url_import(&source) {
330                imports.push(ImportInfo {
331                    source: normalize_css_plugin_path(source),
332                    imported_name: ImportedName::Default,
333                    local_name: String::new(),
334                    is_type_only: false,
335                    from_style: false,
336                    span: Span::default(),
337                    source_span: Span::default(),
338                });
339            }
340        }
341    }
342
343    // If @apply or @tailwind directives exist, create a synthetic import to tailwindcss
344    // to mark the dependency as used
345    let has_apply = CSS_APPLY_RE.is_match(&stripped);
346    let has_tailwind = CSS_TAILWIND_RE.is_match(&stripped);
347    if has_apply || has_tailwind {
348        imports.push(ImportInfo {
349            source: "tailwindcss".to_string(),
350            imported_name: ImportedName::SideEffect,
351            local_name: String::new(),
352            is_type_only: false,
353            from_style: false,
354            span: Span::default(),
355            source_span: Span::default(),
356        });
357    }
358
359    // For CSS module files, extract class names as named exports
360    let exports = if is_css_module_file(path) {
361        extract_css_module_exports(&stripped)
362    } else {
363        Vec::new()
364    };
365
366    ModuleInfo {
367        file_id,
368        exports,
369        imports,
370        re_exports: Vec::new(),
371        dynamic_imports: Vec::new(),
372        dynamic_import_patterns: Vec::new(),
373        require_calls: Vec::new(),
374        member_accesses: Vec::new(),
375        whole_object_uses: Vec::new(),
376        has_cjs_exports: false,
377        content_hash,
378        suppressions,
379        unused_import_bindings: Vec::new(),
380        type_referenced_import_bindings: Vec::new(),
381        value_referenced_import_bindings: Vec::new(),
382        line_offsets: fallow_types::extract::compute_line_offsets(source),
383        complexity: Vec::new(),
384        flag_uses: Vec::new(),
385        class_heritage: vec![],
386        local_type_declarations: Vec::new(),
387        public_signature_type_references: Vec::new(),
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    /// Helper to collect export names as strings from `extract_css_module_exports`.
396    fn export_names(source: &str) -> Vec<String> {
397        extract_css_module_exports(source)
398            .into_iter()
399            .filter_map(|e| match e.name {
400                ExportName::Named(n) => Some(n),
401                ExportName::Default => None,
402            })
403            .collect()
404    }
405
406    // ── is_css_file ──────────────────────────────────────────────
407
408    #[test]
409    fn is_css_file_css() {
410        assert!(is_css_file(Path::new("styles.css")));
411    }
412
413    #[test]
414    fn is_css_file_scss() {
415        assert!(is_css_file(Path::new("styles.scss")));
416    }
417
418    #[test]
419    fn is_css_file_rejects_js() {
420        assert!(!is_css_file(Path::new("app.js")));
421    }
422
423    #[test]
424    fn is_css_file_rejects_ts() {
425        assert!(!is_css_file(Path::new("app.ts")));
426    }
427
428    #[test]
429    fn is_css_file_rejects_less() {
430        assert!(!is_css_file(Path::new("styles.less")));
431    }
432
433    #[test]
434    fn is_css_file_rejects_no_extension() {
435        assert!(!is_css_file(Path::new("Makefile")));
436    }
437
438    // ── is_css_module_file ───────────────────────────────────────
439
440    #[test]
441    fn is_css_module_file_module_css() {
442        assert!(is_css_module_file(Path::new("Component.module.css")));
443    }
444
445    #[test]
446    fn is_css_module_file_module_scss() {
447        assert!(is_css_module_file(Path::new("Component.module.scss")));
448    }
449
450    #[test]
451    fn is_css_module_file_rejects_plain_css() {
452        assert!(!is_css_module_file(Path::new("styles.css")));
453    }
454
455    #[test]
456    fn is_css_module_file_rejects_plain_scss() {
457        assert!(!is_css_module_file(Path::new("styles.scss")));
458    }
459
460    #[test]
461    fn is_css_module_file_rejects_module_js() {
462        assert!(!is_css_module_file(Path::new("utils.module.js")));
463    }
464
465    // ── extract_css_module_exports: basic class extraction ───────
466
467    #[test]
468    fn extracts_single_class() {
469        let names = export_names(".foo { color: red; }");
470        assert_eq!(names, vec!["foo"]);
471    }
472
473    #[test]
474    fn extracts_multiple_classes() {
475        let names = export_names(".foo { } .bar { }");
476        assert_eq!(names, vec!["foo", "bar"]);
477    }
478
479    #[test]
480    fn extracts_nested_classes() {
481        let names = export_names(".foo .bar { color: red; }");
482        assert!(names.contains(&"foo".to_string()));
483        assert!(names.contains(&"bar".to_string()));
484    }
485
486    #[test]
487    fn extracts_hyphenated_class() {
488        let names = export_names(".my-class { }");
489        assert_eq!(names, vec!["my-class"]);
490    }
491
492    #[test]
493    fn extracts_camel_case_class() {
494        let names = export_names(".myClass { }");
495        assert_eq!(names, vec!["myClass"]);
496    }
497
498    #[test]
499    fn extracts_underscore_class() {
500        let names = export_names("._hidden { } .__wrapper { }");
501        assert!(names.contains(&"_hidden".to_string()));
502        assert!(names.contains(&"__wrapper".to_string()));
503    }
504
505    // ── Pseudo-selectors ─────────────────────────────────────────
506
507    #[test]
508    fn pseudo_selector_hover() {
509        let names = export_names(".foo:hover { color: blue; }");
510        assert_eq!(names, vec!["foo"]);
511    }
512
513    #[test]
514    fn pseudo_selector_focus() {
515        let names = export_names(".input:focus { outline: none; }");
516        assert_eq!(names, vec!["input"]);
517    }
518
519    #[test]
520    fn pseudo_element_before() {
521        let names = export_names(".icon::before { content: ''; }");
522        assert_eq!(names, vec!["icon"]);
523    }
524
525    #[test]
526    fn combined_pseudo_selectors() {
527        let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
528        // "btn" should be deduplicated
529        assert_eq!(names, vec!["btn"]);
530    }
531
532    // ── Media queries ────────────────────────────────────────────
533
534    #[test]
535    fn classes_inside_media_query() {
536        let names = export_names(
537            "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
538        );
539        assert!(names.contains(&"mobile-nav".to_string()));
540        assert!(names.contains(&"desktop-nav".to_string()));
541    }
542
543    // ── Deduplication ────────────────────────────────────────────
544
545    #[test]
546    fn deduplicates_repeated_class() {
547        let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
548        assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
549    }
550
551    // ── Edge cases ───────────────────────────────────────────────
552
553    #[test]
554    fn empty_source() {
555        let names = export_names("");
556        assert!(names.is_empty());
557    }
558
559    #[test]
560    fn no_classes() {
561        let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
562        assert!(names.is_empty());
563    }
564
565    #[test]
566    fn ignores_classes_in_block_comments() {
567        // Note: extract_css_module_exports itself does NOT strip comments;
568        // comments are stripped in parse_css_to_module before calling it.
569        // But CSS_NON_SELECTOR_RE strips quoted strings. Testing the
570        // strip_css_comments + extract pipeline via the stripped source:
571        let stripped = strip_css_comments("/* .fake { } */ .real { }", false);
572        let names = export_names(&stripped);
573        assert!(!names.contains(&"fake".to_string()));
574        assert!(names.contains(&"real".to_string()));
575    }
576
577    #[test]
578    fn ignores_classes_in_strings() {
579        let names = export_names(r#".real { content: ".fake"; }"#);
580        assert!(names.contains(&"real".to_string()));
581        assert!(!names.contains(&"fake".to_string()));
582    }
583
584    #[test]
585    fn ignores_classes_in_url() {
586        let names = export_names(".real { background: url(./images/hero.png); }");
587        assert!(names.contains(&"real".to_string()));
588        // "png" from "hero.png" should not be extracted
589        assert!(!names.contains(&"png".to_string()));
590    }
591
592    // ── strip_css_comments ───────────────────────────────────────
593
594    #[test]
595    fn strip_css_block_comment() {
596        let result = strip_css_comments("/* removed */ .kept { }", false);
597        assert!(!result.contains("removed"));
598        assert!(result.contains(".kept"));
599    }
600
601    #[test]
602    fn strip_scss_line_comment() {
603        let result = strip_css_comments("// removed\n.kept { }", true);
604        assert!(!result.contains("removed"));
605        assert!(result.contains(".kept"));
606    }
607
608    #[test]
609    fn strip_scss_preserves_css_outside_comments() {
610        let source = "// line comment\n/* block comment */\n.visible { color: red; }";
611        let result = strip_css_comments(source, true);
612        assert!(result.contains(".visible"));
613    }
614
615    // ── is_css_url_import ────────────────────────────────────────
616
617    #[test]
618    fn url_import_http() {
619        assert!(is_css_url_import("http://example.com/style.css"));
620    }
621
622    #[test]
623    fn url_import_https() {
624        assert!(is_css_url_import("https://fonts.googleapis.com/css"));
625    }
626
627    #[test]
628    fn url_import_data() {
629        assert!(is_css_url_import("data:text/css;base64,abc"));
630    }
631
632    #[test]
633    fn url_import_local_not_skipped() {
634        assert!(!is_css_url_import("./local.css"));
635    }
636
637    #[test]
638    fn url_import_bare_specifier_not_skipped() {
639        assert!(!is_css_url_import("tailwindcss"));
640    }
641
642    // ── normalize_css_import_path ─────────────────────────────────
643
644    #[test]
645    fn normalize_relative_dot_path_unchanged() {
646        assert_eq!(
647            normalize_css_import_path("./reset.css".to_string(), false),
648            "./reset.css"
649        );
650    }
651
652    #[test]
653    fn normalize_parent_relative_path_unchanged() {
654        assert_eq!(
655            normalize_css_import_path("../shared.scss".to_string(), false),
656            "../shared.scss"
657        );
658    }
659
660    #[test]
661    fn normalize_absolute_path_unchanged() {
662        assert_eq!(
663            normalize_css_import_path("/styles/main.css".to_string(), false),
664            "/styles/main.css"
665        );
666    }
667
668    #[test]
669    fn normalize_url_unchanged() {
670        assert_eq!(
671            normalize_css_import_path("https://example.com/style.css".to_string(), false),
672            "https://example.com/style.css"
673        );
674    }
675
676    #[test]
677    fn normalize_bare_css_gets_dot_slash() {
678        assert_eq!(
679            normalize_css_import_path("app.css".to_string(), false),
680            "./app.css"
681        );
682    }
683
684    #[test]
685    fn normalize_css_package_subpath_stays_bare() {
686        assert_eq!(
687            normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
688            "tailwindcss/theme.css"
689        );
690    }
691
692    #[test]
693    fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
694        assert_eq!(
695            normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
696            "highlight.js/styles/github.css"
697        );
698    }
699
700    #[test]
701    fn normalize_bare_scss_gets_dot_slash() {
702        assert_eq!(
703            normalize_css_import_path("vars.scss".to_string(), false),
704            "./vars.scss"
705        );
706    }
707
708    #[test]
709    fn normalize_bare_sass_gets_dot_slash() {
710        assert_eq!(
711            normalize_css_import_path("main.sass".to_string(), false),
712            "./main.sass"
713        );
714    }
715
716    #[test]
717    fn normalize_bare_less_gets_dot_slash() {
718        assert_eq!(
719            normalize_css_import_path("theme.less".to_string(), false),
720            "./theme.less"
721        );
722    }
723
724    #[test]
725    fn normalize_bare_js_extension_stays_bare() {
726        assert_eq!(
727            normalize_css_import_path("module.js".to_string(), false),
728            "module.js"
729        );
730    }
731
732    // ── SCSS partial normalization ───────────────────────────────
733
734    #[test]
735    fn normalize_scss_bare_partial_gets_dot_slash() {
736        assert_eq!(
737            normalize_css_import_path("variables".to_string(), true),
738            "./variables"
739        );
740    }
741
742    #[test]
743    fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
744        assert_eq!(
745            normalize_css_import_path("base/reset".to_string(), true),
746            "./base/reset"
747        );
748    }
749
750    #[test]
751    fn normalize_scss_builtin_stays_bare() {
752        assert_eq!(
753            normalize_css_import_path("sass:math".to_string(), true),
754            "sass:math"
755        );
756    }
757
758    #[test]
759    fn normalize_scss_relative_path_unchanged() {
760        assert_eq!(
761            normalize_css_import_path("../styles/variables".to_string(), true),
762            "../styles/variables"
763        );
764    }
765
766    #[test]
767    fn normalize_css_bare_extensionless_stays_bare() {
768        // In CSS context (not SCSS), extensionless imports are npm packages
769        assert_eq!(
770            normalize_css_import_path("tailwindcss".to_string(), false),
771            "tailwindcss"
772        );
773    }
774
775    // ── Scoped npm packages stay bare ───────────────────────────
776
777    #[test]
778    fn normalize_scoped_package_with_css_extension_stays_bare() {
779        assert_eq!(
780            normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
781            "@fontsource/monaspace-neon/400.css"
782        );
783    }
784
785    #[test]
786    fn normalize_scoped_package_with_scss_extension_stays_bare() {
787        assert_eq!(
788            normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
789            "@company/design-system/tokens.scss"
790        );
791    }
792
793    #[test]
794    fn normalize_scoped_package_without_extension_stays_bare() {
795        assert_eq!(
796            normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
797            "@fallow/design-system/styles"
798        );
799    }
800
801    #[test]
802    fn normalize_scoped_package_extensionless_scss_stays_bare() {
803        assert_eq!(
804            normalize_css_import_path("@company/tokens".to_string(), true),
805            "@company/tokens"
806        );
807    }
808
809    #[test]
810    fn normalize_path_alias_with_css_extension_stays_bare() {
811        // Path aliases like `@/components/Button.css` (configured via tsconfig paths
812        // or Vite alias) share the `@` prefix with scoped packages. They must stay
813        // bare so the resolver's path-alias path can handle them; prepending `./`
814        // would break resolution.
815        assert_eq!(
816            normalize_css_import_path("@/components/Button.css".to_string(), false),
817            "@/components/Button.css"
818        );
819    }
820
821    #[test]
822    fn normalize_path_alias_extensionless_stays_bare() {
823        assert_eq!(
824            normalize_css_import_path("@/styles/variables".to_string(), false),
825            "@/styles/variables"
826        );
827    }
828
829    // ── strip_css_comments edge cases ─────────────────────────────
830
831    #[test]
832    fn strip_css_no_comments() {
833        let source = ".foo { color: red; }";
834        assert_eq!(strip_css_comments(source, false), source);
835    }
836
837    #[test]
838    fn strip_css_multiple_block_comments() {
839        let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
840        let result = strip_css_comments(source, false);
841        assert!(!result.contains("comment-one"));
842        assert!(!result.contains("comment-two"));
843        assert!(result.contains(".foo"));
844        assert!(result.contains(".bar"));
845    }
846
847    #[test]
848    fn strip_scss_does_not_affect_non_scss() {
849        // When is_scss=false, line comments should NOT be stripped
850        let source = "// this stays\n.foo { }";
851        let result = strip_css_comments(source, false);
852        assert!(result.contains("// this stays"));
853    }
854
855    // ── parse_css_to_module: suppression integration ──────────────
856
857    #[test]
858    fn css_module_parses_suppressions() {
859        let info = parse_css_to_module(
860            fallow_types::discover::FileId(0),
861            Path::new("Component.module.css"),
862            "/* fallow-ignore-file */\n.btn { color: red; }",
863            0,
864        );
865        assert!(!info.suppressions.is_empty());
866        assert_eq!(info.suppressions[0].line, 0);
867    }
868
869    // ── CSS class name edge cases ─────────────────────────────────
870
871    #[test]
872    fn extracts_class_starting_with_underscore() {
873        let names = export_names("._private { } .__dunder { }");
874        assert!(names.contains(&"_private".to_string()));
875        assert!(names.contains(&"__dunder".to_string()));
876    }
877
878    #[test]
879    fn ignores_id_selectors() {
880        let names = export_names("#myId { color: red; }");
881        assert!(!names.contains(&"myId".to_string()));
882    }
883
884    #[test]
885    fn ignores_element_selectors() {
886        let names = export_names("div { color: red; } span { }");
887        assert!(names.is_empty());
888    }
889
890    // ── extract_css_imports (issue #195: vite additionalData / SFC styles) ──
891
892    #[test]
893    fn extract_css_imports_at_import_quoted() {
894        let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
895        assert_eq!(imports, vec!["./reset.css"]);
896    }
897
898    #[test]
899    fn extract_css_imports_package_subpath_stays_bare() {
900        let imports =
901            extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
902        assert_eq!(imports, vec!["tailwindcss/theme.css"]);
903    }
904
905    #[test]
906    fn extract_css_imports_at_import_url() {
907        let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
908        assert_eq!(imports, vec!["./reset.css"]);
909    }
910
911    #[test]
912    fn extract_css_imports_skips_remote_urls() {
913        let imports =
914            extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
915        assert!(imports.is_empty());
916    }
917
918    #[test]
919    fn extract_css_imports_scss_use_normalizes_partial() {
920        let imports = extract_css_imports(r#"@use "variables";"#, true);
921        assert_eq!(imports, vec!["./variables"]);
922    }
923
924    #[test]
925    fn extract_css_imports_scss_forward_normalizes_partial() {
926        let imports = extract_css_imports(r#"@forward "tokens";"#, true);
927        assert_eq!(imports, vec!["./tokens"]);
928    }
929
930    #[test]
931    fn extract_css_imports_skips_comments() {
932        let imports = extract_css_imports(
933            r#"/* @import "./hidden.scss"; */
934@use "real";"#,
935            true,
936        );
937        assert_eq!(imports, vec!["./real"]);
938    }
939
940    #[test]
941    fn extract_css_imports_at_plugin_keeps_package_bare() {
942        let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
943        assert_eq!(imports, vec!["daisyui"]);
944    }
945
946    #[test]
947    fn extract_css_imports_at_plugin_tracks_relative_file() {
948        let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
949        assert_eq!(imports, vec!["./tailwind-plugin.js"]);
950    }
951
952    #[test]
953    fn extract_css_imports_scss_at_import_kept_relative() {
954        let imports = extract_css_imports(r"@import 'Foo';", true);
955        // Bare specifier in SCSS context is normalized to ./
956        assert_eq!(imports, vec!["./Foo"]);
957    }
958
959    #[test]
960    fn extract_css_imports_additional_data_string_body() {
961        // Mimics what Vite's css.preprocessorOptions.scss.additionalData ships
962        let body = r#"@use "./src/styles/global.scss";"#;
963        let imports = extract_css_imports(body, true);
964        assert_eq!(imports, vec!["./src/styles/global.scss"]);
965    }
966}