1use 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
14static CSS_IMPORT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
17 regex::Regex::new(r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#)
18 .expect("valid regex")
19});
20
21static SCSS_USE_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
24 regex::Regex::new(r#"@(?:use|forward)\s+["']([^"']+)["']"#).expect("valid regex")
25});
26
27static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
30 LazyLock::new(|| regex::Regex::new(r#"@plugin\s+["']([^"']+)["']"#).expect("valid regex"));
31
32static CSS_APPLY_RE: LazyLock<regex::Regex> =
35 LazyLock::new(|| regex::Regex::new(r"@apply\s+[^;}\n]+").expect("valid regex"));
36
37static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
40 LazyLock::new(|| regex::Regex::new(r"@tailwind\s+\w+").expect("valid regex"));
41
42static CSS_COMMENT_RE: LazyLock<regex::Regex> =
44 LazyLock::new(|| regex::Regex::new(r"(?s)/\*.*?\*/").expect("valid regex"));
45
46static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
48 LazyLock::new(|| regex::Regex::new(r"//[^\n]*").expect("valid regex"));
49
50static CSS_CLASS_RE: LazyLock<regex::Regex> =
53 LazyLock::new(|| regex::Regex::new(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)").expect("valid regex"));
54
55static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
58 regex::Regex::new(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#).expect("valid regex")
59});
60
61static CSS_AT_RULE_PRELUDE_RE: LazyLock<regex::Regex> =
73 LazyLock::new(|| regex::Regex::new(r"@(?:layer|import)\b[^;{]*").expect("valid regex"));
74
75pub(crate) fn is_css_file(path: &Path) -> bool {
76 path.extension()
77 .and_then(|e| e.to_str())
78 .is_some_and(|ext| ext == "css" || ext == "scss")
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct CssImportSource {
84 pub raw: String,
86 pub normalized: String,
88 pub is_plugin: bool,
90}
91
92fn is_css_module_file(path: &Path) -> bool {
93 is_css_file(path)
94 && path
95 .file_stem()
96 .and_then(|s| s.to_str())
97 .is_some_and(|stem| stem.ends_with(".module"))
98}
99
100fn is_css_url_import(source: &str) -> bool {
102 source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
103}
104
105fn normalize_css_import_path(path: String, is_scss: bool) -> String {
118 if path.starts_with('.') || path.starts_with('/') || path.contains("://") {
119 return path;
120 }
121 if path.starts_with('@') && path.contains('/') {
124 return path;
125 }
126 let path_ref = std::path::Path::new(&path);
127 if !is_scss
128 && path.contains('/')
129 && path_ref
130 .extension()
131 .and_then(|e| e.to_str())
132 .is_some_and(is_style_extension)
133 {
134 return path;
135 }
136 let ext = std::path::Path::new(&path)
138 .extension()
139 .and_then(|e| e.to_str());
140 match ext {
141 Some(e) if is_style_extension(e) => format!("./{path}"),
142 _ => {
143 if is_scss && !path.contains(':') {
147 format!("./{path}")
148 } else {
149 path
150 }
151 }
152 }
153}
154
155fn is_style_extension(ext: &str) -> bool {
156 ext.eq_ignore_ascii_case("css")
157 || ext.eq_ignore_ascii_case("scss")
158 || ext.eq_ignore_ascii_case("sass")
159 || ext.eq_ignore_ascii_case("less")
160}
161
162fn strip_css_comments(source: &str, is_scss: bool) -> String {
164 let stripped = CSS_COMMENT_RE.replace_all(source, "");
165 if is_scss {
166 SCSS_LINE_COMMENT_RE.replace_all(&stripped, "").into_owned()
167 } else {
168 stripped.into_owned()
169 }
170}
171
172fn normalize_css_plugin_path(path: String) -> String {
178 path
179}
180
181#[must_use]
187pub fn extract_css_import_sources(source: &str, is_scss: bool) -> Vec<CssImportSource> {
188 let stripped = strip_css_comments(source, is_scss);
189 let mut out = Vec::new();
190
191 for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
192 let raw = cap
193 .get(1)
194 .or_else(|| cap.get(2))
195 .or_else(|| cap.get(3))
196 .map(|m| m.as_str().trim().to_string());
197 if let Some(src) = raw
198 && !src.is_empty()
199 && !is_css_url_import(&src)
200 {
201 out.push(CssImportSource {
202 normalized: normalize_css_import_path(src.clone(), is_scss),
203 raw: src,
204 is_plugin: false,
205 });
206 }
207 }
208
209 if is_scss {
210 for cap in SCSS_USE_RE.captures_iter(&stripped) {
211 if let Some(m) = cap.get(1) {
212 let raw = m.as_str().to_string();
213 out.push(CssImportSource {
214 normalized: normalize_css_import_path(raw.clone(), true),
215 raw,
216 is_plugin: false,
217 });
218 }
219 }
220 }
221
222 for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
223 if let Some(m) = cap.get(1) {
224 let raw = m.as_str().trim().to_string();
225 if !raw.is_empty() && !is_css_url_import(&raw) {
226 out.push(CssImportSource {
227 normalized: normalize_css_plugin_path(raw.clone()),
228 raw,
229 is_plugin: true,
230 });
231 }
232 }
233 }
234
235 out
236}
237
238#[must_use]
245pub fn extract_css_imports(source: &str, is_scss: bool) -> Vec<String> {
246 extract_css_import_sources(source, is_scss)
247 .into_iter()
248 .map(|source| source.normalized)
249 .collect()
250}
251
252fn mask_with_whitespace(src: &str, re: ®ex::Regex) -> String {
262 let mut out = String::with_capacity(src.len());
263 let mut cursor = 0;
264 for m in re.find_iter(src) {
265 out.push_str(&src[cursor..m.start()]);
266 for _ in m.start()..m.end() {
267 out.push(' ');
268 }
269 cursor = m.end();
270 }
271 out.push_str(&src[cursor..]);
272 out
273}
274
275pub fn extract_css_module_exports(source: &str, is_scss: bool) -> Vec<ExportInfo> {
282 let mut masked = mask_with_whitespace(source, &CSS_COMMENT_RE);
287 if is_scss {
288 masked = mask_with_whitespace(&masked, &SCSS_LINE_COMMENT_RE);
289 }
290 masked = mask_with_whitespace(&masked, &CSS_NON_SELECTOR_RE);
291 masked = mask_with_whitespace(&masked, &CSS_AT_RULE_PRELUDE_RE);
296
297 let mut seen = rustc_hash::FxHashSet::default();
298 let mut exports = Vec::new();
299 for cap in CSS_CLASS_RE.captures_iter(&masked) {
300 if let Some(m) = cap.get(1) {
301 let class_name = m.as_str().to_string();
302 if seen.insert(class_name.clone()) {
303 #[expect(
304 clippy::cast_possible_truncation,
305 reason = "CSS files exceeding u32::MAX bytes are not a realistic input"
306 )]
307 let span = Span::new(m.start() as u32, m.end() as u32);
308 exports.push(ExportInfo {
309 name: ExportName::Named(class_name),
310 local_name: None,
311 is_type_only: false,
312 visibility: VisibilityTag::None,
313 span,
314 members: Vec::new(),
315 is_side_effect_used: false,
316 super_class: None,
317 });
318 }
319 }
320 }
321 exports
322}
323
324pub(crate) fn parse_css_to_module(
326 file_id: FileId,
327 path: &Path,
328 source: &str,
329 content_hash: u64,
330) -> ModuleInfo {
331 let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
332 let is_scss = path
333 .extension()
334 .and_then(|e| e.to_str())
335 .is_some_and(|ext| ext == "scss");
336
337 let stripped = strip_css_comments(source, is_scss);
339
340 let mut imports = Vec::new();
341
342 for cap in CSS_IMPORT_RE.captures_iter(&stripped) {
344 let source_path = cap
345 .get(1)
346 .or_else(|| cap.get(2))
347 .or_else(|| cap.get(3))
348 .map(|m| m.as_str().trim().to_string());
349 if let Some(src) = source_path
350 && !src.is_empty()
351 && !is_css_url_import(&src)
352 {
353 let src = normalize_css_import_path(src, is_scss);
356 imports.push(ImportInfo {
357 source: src,
358 imported_name: ImportedName::SideEffect,
359 local_name: String::new(),
360 is_type_only: false,
361 from_style: false,
362 span: Span::default(),
363 source_span: Span::default(),
364 });
365 }
366 }
367
368 if is_scss {
370 for cap in SCSS_USE_RE.captures_iter(&stripped) {
371 if let Some(m) = cap.get(1) {
372 imports.push(ImportInfo {
373 source: normalize_css_import_path(m.as_str().to_string(), true),
374 imported_name: ImportedName::SideEffect,
375 local_name: String::new(),
376 is_type_only: false,
377 from_style: false,
378 span: Span::default(),
379 source_span: Span::default(),
380 });
381 }
382 }
383 }
384
385 for cap in CSS_PLUGIN_RE.captures_iter(&stripped) {
388 if let Some(m) = cap.get(1) {
389 let source = m.as_str().trim().to_string();
390 if !source.is_empty() && !is_css_url_import(&source) {
391 imports.push(ImportInfo {
392 source: normalize_css_plugin_path(source),
393 imported_name: ImportedName::Default,
394 local_name: String::new(),
395 is_type_only: false,
396 from_style: false,
397 span: Span::default(),
398 source_span: Span::default(),
399 });
400 }
401 }
402 }
403
404 let has_apply = CSS_APPLY_RE.is_match(&stripped);
407 let has_tailwind = CSS_TAILWIND_RE.is_match(&stripped);
408 if has_apply || has_tailwind {
409 imports.push(ImportInfo {
410 source: "tailwindcss".to_string(),
411 imported_name: ImportedName::SideEffect,
412 local_name: String::new(),
413 is_type_only: false,
414 from_style: false,
415 span: Span::default(),
416 source_span: Span::default(),
417 });
418 }
419
420 let exports = if is_css_module_file(path) {
425 extract_css_module_exports(source, is_scss)
426 } else {
427 Vec::new()
428 };
429
430 ModuleInfo {
431 file_id,
432 exports,
433 imports,
434 re_exports: Vec::new(),
435 dynamic_imports: Vec::new(),
436 dynamic_import_patterns: Vec::new(),
437 require_calls: Vec::new(),
438 member_accesses: Vec::new(),
439 whole_object_uses: Vec::new(),
440 has_cjs_exports: false,
441 has_angular_component_template_url: false,
442 content_hash,
443 suppressions: parsed_suppressions.suppressions,
444 unknown_suppression_kinds: parsed_suppressions.unknown_kinds,
445 unused_import_bindings: Vec::new(),
446 type_referenced_import_bindings: Vec::new(),
447 value_referenced_import_bindings: Vec::new(),
448 line_offsets: fallow_types::extract::compute_line_offsets(source),
449 complexity: Vec::new(),
450 flag_uses: Vec::new(),
451 class_heritage: vec![],
452 local_type_declarations: Vec::new(),
453 public_signature_type_references: Vec::new(),
454 namespace_object_aliases: Vec::new(),
455 iconify_prefixes: Vec::new(),
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 use super::*;
462
463 fn export_names(source: &str) -> Vec<String> {
465 extract_css_module_exports(source, false)
466 .into_iter()
467 .filter_map(|e| match e.name {
468 ExportName::Named(n) => Some(n),
469 ExportName::Default => None,
470 })
471 .collect()
472 }
473
474 #[test]
477 fn is_css_file_css() {
478 assert!(is_css_file(Path::new("styles.css")));
479 }
480
481 #[test]
482 fn is_css_file_scss() {
483 assert!(is_css_file(Path::new("styles.scss")));
484 }
485
486 #[test]
487 fn is_css_file_rejects_js() {
488 assert!(!is_css_file(Path::new("app.js")));
489 }
490
491 #[test]
492 fn is_css_file_rejects_ts() {
493 assert!(!is_css_file(Path::new("app.ts")));
494 }
495
496 #[test]
497 fn is_css_file_rejects_less() {
498 assert!(!is_css_file(Path::new("styles.less")));
499 }
500
501 #[test]
502 fn is_css_file_rejects_no_extension() {
503 assert!(!is_css_file(Path::new("Makefile")));
504 }
505
506 #[test]
509 fn is_css_module_file_module_css() {
510 assert!(is_css_module_file(Path::new("Component.module.css")));
511 }
512
513 #[test]
514 fn is_css_module_file_module_scss() {
515 assert!(is_css_module_file(Path::new("Component.module.scss")));
516 }
517
518 #[test]
519 fn is_css_module_file_rejects_plain_css() {
520 assert!(!is_css_module_file(Path::new("styles.css")));
521 }
522
523 #[test]
524 fn is_css_module_file_rejects_plain_scss() {
525 assert!(!is_css_module_file(Path::new("styles.scss")));
526 }
527
528 #[test]
529 fn is_css_module_file_rejects_module_js() {
530 assert!(!is_css_module_file(Path::new("utils.module.js")));
531 }
532
533 #[test]
536 fn extracts_single_class() {
537 let names = export_names(".foo { color: red; }");
538 assert_eq!(names, vec!["foo"]);
539 }
540
541 #[test]
542 fn extracts_multiple_classes() {
543 let names = export_names(".foo { } .bar { }");
544 assert_eq!(names, vec!["foo", "bar"]);
545 }
546
547 #[test]
548 fn extracts_nested_classes() {
549 let names = export_names(".foo .bar { color: red; }");
550 assert!(names.contains(&"foo".to_string()));
551 assert!(names.contains(&"bar".to_string()));
552 }
553
554 #[test]
555 fn extracts_hyphenated_class() {
556 let names = export_names(".my-class { }");
557 assert_eq!(names, vec!["my-class"]);
558 }
559
560 #[test]
561 fn extracts_camel_case_class() {
562 let names = export_names(".myClass { }");
563 assert_eq!(names, vec!["myClass"]);
564 }
565
566 #[test]
567 fn extracts_underscore_class() {
568 let names = export_names("._hidden { } .__wrapper { }");
569 assert!(names.contains(&"_hidden".to_string()));
570 assert!(names.contains(&"__wrapper".to_string()));
571 }
572
573 #[test]
576 fn pseudo_selector_hover() {
577 let names = export_names(".foo:hover { color: blue; }");
578 assert_eq!(names, vec!["foo"]);
579 }
580
581 #[test]
582 fn pseudo_selector_focus() {
583 let names = export_names(".input:focus { outline: none; }");
584 assert_eq!(names, vec!["input"]);
585 }
586
587 #[test]
588 fn pseudo_element_before() {
589 let names = export_names(".icon::before { content: ''; }");
590 assert_eq!(names, vec!["icon"]);
591 }
592
593 #[test]
594 fn combined_pseudo_selectors() {
595 let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
596 assert_eq!(names, vec!["btn"]);
598 }
599
600 #[test]
603 fn classes_inside_media_query() {
604 let names = export_names(
605 "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
606 );
607 assert!(names.contains(&"mobile-nav".to_string()));
608 assert!(names.contains(&"desktop-nav".to_string()));
609 }
610
611 #[test]
612 fn classes_inside_multi_line_media_query() {
613 let names =
618 export_names("@media\n screen and (min-width: 600px)\n{\n .real { color: red; }\n}");
619 assert_eq!(names, vec!["real"]);
620 }
621
622 #[test]
625 fn at_layer_statement_does_not_export() {
626 let names = export_names("@layer foo.bar;");
629 assert!(names.is_empty(), "got {names:?}");
630 let names = export_names("@layer foo.bar, foo.baz;");
631 assert!(names.is_empty(), "got {names:?}");
632 }
633
634 #[test]
635 fn at_layer_block_keeps_body_classes() {
636 let names = export_names("@layer foo.bar { .root { color: red; } }");
639 assert_eq!(names, vec!["root"]);
640 }
641
642 #[test]
643 fn at_layer_multiline_prelude_keeps_body_classes() {
644 let names = export_names("@layer\n foo.bar\n{ .root { color: red; } }");
647 assert_eq!(names, vec!["root"]);
648 }
649
650 #[test]
651 fn at_layer_with_nested_media_keeps_body() {
652 let names =
656 export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
657 assert_eq!(names, vec!["real"]);
658 }
659
660 #[test]
661 fn at_import_with_layer_attribute_does_not_export() {
662 let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
667 assert!(names.is_empty(), "got {names:?}");
668 }
669
670 #[test]
671 fn class_then_at_layer_does_not_leak_prelude() {
672 let names =
675 export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
676 assert_eq!(names, vec!["outer", "inner"]);
677 }
678
679 #[test]
682 fn at_scope_keeps_selector_list_classes() {
683 let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
688 assert!(names.contains(&"parent".to_string()), "got {names:?}");
689 assert!(names.contains(&"child".to_string()), "got {names:?}");
690 assert!(names.contains(&"title".to_string()), "got {names:?}");
691 }
692
693 #[test]
694 fn at_keyframes_numeric_step_is_not_class() {
695 let names = export_names(
701 "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
702 );
703 assert!(names.is_empty(), "got {names:?}");
704 }
705
706 #[test]
707 fn at_webkit_keyframes_keeps_body_classes() {
708 let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
712 assert_eq!(names, vec!["real"]);
713 }
714
715 #[test]
718 fn deduplicates_repeated_class() {
719 let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
720 assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
721 }
722
723 #[test]
726 fn empty_source() {
727 let names = export_names("");
728 assert!(names.is_empty());
729 }
730
731 #[test]
732 fn no_classes() {
733 let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
734 assert!(names.is_empty());
735 }
736
737 #[test]
738 fn ignores_classes_in_block_comments() {
739 let names = export_names("/* .fake { } */ .real { }");
742 assert!(!names.contains(&"fake".to_string()));
743 assert!(names.contains(&"real".to_string()));
744 }
745
746 #[test]
747 fn ignores_classes_in_scss_line_comments() {
748 let exports = extract_css_module_exports("// .fake\n.real { }", true);
749 let names: Vec<_> = exports
750 .iter()
751 .filter_map(|e| match &e.name {
752 ExportName::Named(n) => Some(n.as_str()),
753 ExportName::Default => None,
754 })
755 .collect();
756 assert_eq!(names, vec!["real"]);
757 }
758
759 #[test]
760 fn ignores_classes_in_strings() {
761 let names = export_names(r#".real { content: ".fake"; }"#);
762 assert!(names.contains(&"real".to_string()));
763 assert!(!names.contains(&"fake".to_string()));
764 }
765
766 #[test]
767 fn ignores_classes_in_url() {
768 let names = export_names(".real { background: url(./images/hero.png); }");
769 assert!(names.contains(&"real".to_string()));
770 assert!(!names.contains(&"png".to_string()));
772 }
773
774 #[test]
777 fn strip_css_block_comment() {
778 let result = strip_css_comments("/* removed */ .kept { }", false);
779 assert!(!result.contains("removed"));
780 assert!(result.contains(".kept"));
781 }
782
783 #[test]
784 fn strip_scss_line_comment() {
785 let result = strip_css_comments("// removed\n.kept { }", true);
786 assert!(!result.contains("removed"));
787 assert!(result.contains(".kept"));
788 }
789
790 #[test]
791 fn strip_scss_preserves_css_outside_comments() {
792 let source = "// line comment\n/* block comment */\n.visible { color: red; }";
793 let result = strip_css_comments(source, true);
794 assert!(result.contains(".visible"));
795 }
796
797 #[test]
800 fn url_import_http() {
801 assert!(is_css_url_import("http://example.com/style.css"));
802 }
803
804 #[test]
805 fn url_import_https() {
806 assert!(is_css_url_import("https://fonts.googleapis.com/css"));
807 }
808
809 #[test]
810 fn url_import_data() {
811 assert!(is_css_url_import("data:text/css;base64,abc"));
812 }
813
814 #[test]
815 fn url_import_local_not_skipped() {
816 assert!(!is_css_url_import("./local.css"));
817 }
818
819 #[test]
820 fn url_import_bare_specifier_not_skipped() {
821 assert!(!is_css_url_import("tailwindcss"));
822 }
823
824 #[test]
827 fn normalize_relative_dot_path_unchanged() {
828 assert_eq!(
829 normalize_css_import_path("./reset.css".to_string(), false),
830 "./reset.css"
831 );
832 }
833
834 #[test]
835 fn normalize_parent_relative_path_unchanged() {
836 assert_eq!(
837 normalize_css_import_path("../shared.scss".to_string(), false),
838 "../shared.scss"
839 );
840 }
841
842 #[test]
843 fn normalize_absolute_path_unchanged() {
844 assert_eq!(
845 normalize_css_import_path("/styles/main.css".to_string(), false),
846 "/styles/main.css"
847 );
848 }
849
850 #[test]
851 fn normalize_url_unchanged() {
852 assert_eq!(
853 normalize_css_import_path("https://example.com/style.css".to_string(), false),
854 "https://example.com/style.css"
855 );
856 }
857
858 #[test]
859 fn normalize_bare_css_gets_dot_slash() {
860 assert_eq!(
861 normalize_css_import_path("app.css".to_string(), false),
862 "./app.css"
863 );
864 }
865
866 #[test]
867 fn normalize_css_package_subpath_stays_bare() {
868 assert_eq!(
869 normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
870 "tailwindcss/theme.css"
871 );
872 }
873
874 #[test]
875 fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
876 assert_eq!(
877 normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
878 "highlight.js/styles/github.css"
879 );
880 }
881
882 #[test]
883 fn normalize_bare_scss_gets_dot_slash() {
884 assert_eq!(
885 normalize_css_import_path("vars.scss".to_string(), false),
886 "./vars.scss"
887 );
888 }
889
890 #[test]
891 fn normalize_bare_sass_gets_dot_slash() {
892 assert_eq!(
893 normalize_css_import_path("main.sass".to_string(), false),
894 "./main.sass"
895 );
896 }
897
898 #[test]
899 fn normalize_bare_less_gets_dot_slash() {
900 assert_eq!(
901 normalize_css_import_path("theme.less".to_string(), false),
902 "./theme.less"
903 );
904 }
905
906 #[test]
907 fn normalize_bare_js_extension_stays_bare() {
908 assert_eq!(
909 normalize_css_import_path("module.js".to_string(), false),
910 "module.js"
911 );
912 }
913
914 #[test]
917 fn normalize_scss_bare_partial_gets_dot_slash() {
918 assert_eq!(
919 normalize_css_import_path("variables".to_string(), true),
920 "./variables"
921 );
922 }
923
924 #[test]
925 fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
926 assert_eq!(
927 normalize_css_import_path("base/reset".to_string(), true),
928 "./base/reset"
929 );
930 }
931
932 #[test]
933 fn normalize_scss_builtin_stays_bare() {
934 assert_eq!(
935 normalize_css_import_path("sass:math".to_string(), true),
936 "sass:math"
937 );
938 }
939
940 #[test]
941 fn normalize_scss_relative_path_unchanged() {
942 assert_eq!(
943 normalize_css_import_path("../styles/variables".to_string(), true),
944 "../styles/variables"
945 );
946 }
947
948 #[test]
949 fn normalize_css_bare_extensionless_stays_bare() {
950 assert_eq!(
952 normalize_css_import_path("tailwindcss".to_string(), false),
953 "tailwindcss"
954 );
955 }
956
957 #[test]
960 fn normalize_scoped_package_with_css_extension_stays_bare() {
961 assert_eq!(
962 normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
963 "@fontsource/monaspace-neon/400.css"
964 );
965 }
966
967 #[test]
968 fn normalize_scoped_package_with_scss_extension_stays_bare() {
969 assert_eq!(
970 normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
971 "@company/design-system/tokens.scss"
972 );
973 }
974
975 #[test]
976 fn normalize_scoped_package_without_extension_stays_bare() {
977 assert_eq!(
978 normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
979 "@fallow/design-system/styles"
980 );
981 }
982
983 #[test]
984 fn normalize_scoped_package_extensionless_scss_stays_bare() {
985 assert_eq!(
986 normalize_css_import_path("@company/tokens".to_string(), true),
987 "@company/tokens"
988 );
989 }
990
991 #[test]
992 fn normalize_path_alias_with_css_extension_stays_bare() {
993 assert_eq!(
998 normalize_css_import_path("@/components/Button.css".to_string(), false),
999 "@/components/Button.css"
1000 );
1001 }
1002
1003 #[test]
1004 fn normalize_path_alias_extensionless_stays_bare() {
1005 assert_eq!(
1006 normalize_css_import_path("@/styles/variables".to_string(), false),
1007 "@/styles/variables"
1008 );
1009 }
1010
1011 #[test]
1014 fn strip_css_no_comments() {
1015 let source = ".foo { color: red; }";
1016 assert_eq!(strip_css_comments(source, false), source);
1017 }
1018
1019 #[test]
1020 fn strip_css_multiple_block_comments() {
1021 let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
1022 let result = strip_css_comments(source, false);
1023 assert!(!result.contains("comment-one"));
1024 assert!(!result.contains("comment-two"));
1025 assert!(result.contains(".foo"));
1026 assert!(result.contains(".bar"));
1027 }
1028
1029 #[test]
1030 fn strip_scss_does_not_affect_non_scss() {
1031 let source = "// this stays\n.foo { }";
1033 let result = strip_css_comments(source, false);
1034 assert!(result.contains("// this stays"));
1035 }
1036
1037 #[test]
1040 fn css_module_parses_suppressions() {
1041 let info = parse_css_to_module(
1042 fallow_types::discover::FileId(0),
1043 Path::new("Component.module.css"),
1044 "/* fallow-ignore-file */\n.btn { color: red; }",
1045 0,
1046 );
1047 assert!(!info.suppressions.is_empty());
1048 assert_eq!(info.suppressions[0].line, 0);
1049 }
1050
1051 #[test]
1054 fn extracts_class_starting_with_underscore() {
1055 let names = export_names("._private { } .__dunder { }");
1056 assert!(names.contains(&"_private".to_string()));
1057 assert!(names.contains(&"__dunder".to_string()));
1058 }
1059
1060 #[test]
1061 fn ignores_id_selectors() {
1062 let names = export_names("#myId { color: red; }");
1063 assert!(!names.contains(&"myId".to_string()));
1064 }
1065
1066 #[test]
1067 fn ignores_element_selectors() {
1068 let names = export_names("div { color: red; } span { }");
1069 assert!(names.is_empty());
1070 }
1071
1072 #[test]
1075 fn extract_css_imports_at_import_quoted() {
1076 let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
1077 assert_eq!(imports, vec!["./reset.css"]);
1078 }
1079
1080 #[test]
1081 fn extract_css_imports_package_subpath_stays_bare() {
1082 let imports =
1083 extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
1084 assert_eq!(imports, vec!["tailwindcss/theme.css"]);
1085 }
1086
1087 #[test]
1088 fn extract_css_imports_at_import_url() {
1089 let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
1090 assert_eq!(imports, vec!["./reset.css"]);
1091 }
1092
1093 #[test]
1094 fn extract_css_imports_skips_remote_urls() {
1095 let imports =
1096 extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
1097 assert!(imports.is_empty());
1098 }
1099
1100 #[test]
1101 fn extract_css_imports_scss_use_normalizes_partial() {
1102 let imports = extract_css_imports(r#"@use "variables";"#, true);
1103 assert_eq!(imports, vec!["./variables"]);
1104 }
1105
1106 #[test]
1107 fn extract_css_imports_scss_forward_normalizes_partial() {
1108 let imports = extract_css_imports(r#"@forward "tokens";"#, true);
1109 assert_eq!(imports, vec!["./tokens"]);
1110 }
1111
1112 #[test]
1113 fn extract_css_imports_skips_comments() {
1114 let imports = extract_css_imports(
1115 r#"/* @import "./hidden.scss"; */
1116@use "real";"#,
1117 true,
1118 );
1119 assert_eq!(imports, vec!["./real"]);
1120 }
1121
1122 #[test]
1123 fn extract_css_imports_at_plugin_keeps_package_bare() {
1124 let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1125 assert_eq!(imports, vec!["daisyui"]);
1126 }
1127
1128 #[test]
1129 fn extract_css_imports_at_plugin_tracks_relative_file() {
1130 let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1131 assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1132 }
1133
1134 #[test]
1135 fn extract_css_imports_scss_at_import_kept_relative() {
1136 let imports = extract_css_imports(r"@import 'Foo';", true);
1137 assert_eq!(imports, vec!["./Foo"]);
1139 }
1140
1141 #[test]
1142 fn extract_css_imports_additional_data_string_body() {
1143 let body = r#"@use "./src/styles/global.scss";"#;
1145 let imports = extract_css_imports(body, true);
1146 assert_eq!(imports, vec!["./src/styles/global.scss"]);
1147 }
1148
1149 #[test]
1152 fn mask_with_whitespace_preserves_byte_length() {
1153 let src = "/* hello */ .foo { }";
1154 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1155 assert_eq!(masked.len(), src.len());
1156 assert!(masked.is_char_boundary(src.len()));
1157 }
1158
1159 #[test]
1160 fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1161 let src = "/* \u{2713} */ .foo { }";
1165 let foo_offset = src.find(".foo").expect("`.foo` present");
1166 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1167 assert_eq!(masked.len(), src.len());
1168 assert_eq!(masked.find(".foo"), Some(foo_offset));
1169 }
1170
1171 fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1176 let offsets = fallow_types::extract::compute_line_offsets(source);
1177 fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1178 }
1179
1180 #[test]
1181 fn span_points_at_real_class_declaration_line() {
1182 let source = "\n\n\n\n.foo { color: red; }\n";
1183 let exports = extract_css_module_exports(source, false);
1184 assert_eq!(exports.len(), 1);
1185 let span = exports[0].span;
1186 let (line, col) = span_line_col(source, span.start);
1187 assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1188 assert_eq!(
1191 col, 1,
1192 "column points at `f` in `.foo` (post-dot identifier)"
1193 );
1194 assert_eq!(
1197 &source[span.start as usize..span.end as usize],
1198 "foo",
1199 "span range must slice to the class identifier in the original source"
1200 );
1201 }
1202
1203 #[test]
1204 fn span_survives_multibyte_comment_prefix() {
1205 let source = "/* \u{2713} */\n.foo { }";
1209 let exports = extract_css_module_exports(source, false);
1210 assert_eq!(exports.len(), 1);
1211 let span = exports[0].span;
1212 assert!(
1213 source.is_char_boundary(span.start as usize),
1214 "span.start must lie on a UTF-8 char boundary"
1215 );
1216 assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1217 }
1218
1219 #[test]
1220 fn span_skips_at_layer_prelude_dot_segments() {
1221 let source = "@layer foo.bar { }\n.root { }\n";
1225 let exports = extract_css_module_exports(source, false);
1226 let names: Vec<_> = exports
1227 .iter()
1228 .filter_map(|e| match &e.name {
1229 ExportName::Named(n) => Some(n.as_str()),
1230 ExportName::Default => None,
1231 })
1232 .collect();
1233 assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1234 let span = exports[0].span;
1235 let (line, _col) = span_line_col(source, span.start);
1236 assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1237 assert_eq!(&source[span.start as usize..span.end as usize], "root");
1238 }
1239
1240 #[test]
1241 fn span_skips_classes_in_strings() {
1242 let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1243 let exports = extract_css_module_exports(source, false);
1244 let names: Vec<_> = exports
1245 .iter()
1246 .filter_map(|e| match &e.name {
1247 ExportName::Named(n) => Some(n.as_str()),
1248 ExportName::Default => None,
1249 })
1250 .collect();
1251 assert_eq!(names, vec!["real", "also-real"]);
1252 for export in &exports {
1254 let span = export.span;
1255 let slice = &source[span.start as usize..span.end as usize];
1256 match &export.name {
1257 ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1258 ExportName::Default => unreachable!("CSS modules emit only named exports"),
1259 }
1260 }
1261 }
1262
1263 #[test]
1264 fn span_deduplicates_to_first_occurrence() {
1265 let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1266 let exports = extract_css_module_exports(source, false);
1267 assert_eq!(exports.len(), 1);
1268 let (line, _col) = span_line_col(source, exports[0].span.start);
1269 assert_eq!(
1270 line, 1,
1271 "first occurrence wins for deduplicated class names"
1272 );
1273 }
1274
1275 #[test]
1276 fn span_inside_media_query() {
1277 let source =
1278 "@media (max-width: 768px) {\n .mobile { display: block; }\n .desktop { }\n}\n";
1279 let exports = extract_css_module_exports(source, false);
1280 let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1281 .iter()
1282 .filter_map(|e| match &e.name {
1283 ExportName::Named(n) => Some((n.as_str(), e.span)),
1284 ExportName::Default => None,
1285 })
1286 .collect();
1287 let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1288 let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1289 assert_eq!(mobile_line, 2);
1290 assert_eq!(desktop_line, 3);
1291 }
1292
1293 #[test]
1294 fn at_layer_only_module_emits_no_exports() {
1295 let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1298 assert!(exports.is_empty());
1299 }
1300
1301 #[test]
1302 fn parse_css_to_module_resolves_real_line_offsets() {
1303 let source = "\n\n\n\n.foo { color: red; }\n";
1307 let info = parse_css_to_module(
1308 fallow_types::discover::FileId(0),
1309 Path::new("Component.module.css"),
1310 source,
1311 0,
1312 );
1313 assert_eq!(info.exports.len(), 1);
1314 let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1315 &info.line_offsets,
1316 info.exports[0].span.start,
1317 );
1318 assert_eq!(line, 5, "downstream line must equal the source line");
1319 }
1320}