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 crate::static_regex(
18 r#"@import\s+(?:url\(\s*(?:["']([^"']+)["']|([^)]+))\s*\)|["']([^"']+)["'])"#,
19 )
20});
21
22static SCSS_USE_RE: LazyLock<regex::Regex> =
25 LazyLock::new(|| crate::static_regex(r#"@(?:use|forward)\s+["']([^"']+)["']"#));
26
27static CSS_PLUGIN_RE: LazyLock<regex::Regex> =
30 LazyLock::new(|| crate::static_regex(r#"@plugin\s+["']([^"']+)["']"#));
31
32static CSS_APPLY_RE: LazyLock<regex::Regex> =
35 LazyLock::new(|| crate::static_regex(r"@apply\s+[^;}\n]+"));
36
37static CSS_TAILWIND_RE: LazyLock<regex::Regex> =
40 LazyLock::new(|| crate::static_regex(r"@tailwind\s+\w+"));
41
42static CSS_COMMENT_RE: LazyLock<regex::Regex> =
44 LazyLock::new(|| crate::static_regex(r"(?s)/\*.*?\*/"));
45
46static SCSS_LINE_COMMENT_RE: LazyLock<regex::Regex> =
48 LazyLock::new(|| crate::static_regex(r"//[^\n]*"));
49
50static CSS_CLASS_RE: LazyLock<regex::Regex> =
53 LazyLock::new(|| crate::static_regex(r"\.([a-zA-Z_][a-zA-Z0-9_-]*)"));
54
55static CSS_NON_SELECTOR_RE: LazyLock<regex::Regex> =
58 LazyLock::new(|| crate::static_regex(r#"(?s)"[^"]*"|'[^']*'|url\([^)]*\)"#));
59
60static 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#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct CssImportSource {
83 pub raw: String,
85 pub normalized: String,
87 pub is_plugin: bool,
89 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
101fn is_css_url_import(source: &str) -> bool {
103 source.starts_with("http://") || source.starts_with("https://") || source.starts_with("data:")
104}
105
106fn 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#[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
176fn normalize_css_plugin_path(path: String) -> String {
182 path
183}
184
185#[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#[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
264fn mask_with_whitespace(src: &str, re: ®ex::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
287pub 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
328pub(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 member_accesses: Vec::new(),
390 whole_object_uses: Vec::new(),
391 has_cjs_exports: false,
392 has_angular_component_template_url: false,
393 content_hash,
394 suppressions: parsed_suppressions.suppressions,
395 unknown_suppression_kinds: parsed_suppressions.unknown_kinds,
396 unused_import_bindings: Vec::new(),
397 type_referenced_import_bindings: Vec::new(),
398 value_referenced_import_bindings: Vec::new(),
399 line_offsets: fallow_types::extract::compute_line_offsets(source),
400 complexity: Vec::new(),
401 flag_uses: Vec::new(),
402 class_heritage: vec![],
403 injection_tokens: vec![],
404 local_type_declarations: Vec::new(),
405 public_signature_type_references: Vec::new(),
406 namespace_object_aliases: Vec::new(),
407 iconify_prefixes: Vec::new(),
408 auto_import_candidates: Vec::new(),
409 directives: Vec::new(),
410 security_sinks: Vec::new(),
411 security_sinks_skipped: 0,
412 tainted_bindings: Vec::new(),
413 sanitized_sink_args: Vec::new(),
414 }
415}
416
417#[cfg(test)]
418mod tests {
419 use super::*;
420
421 fn export_names(source: &str) -> Vec<String> {
423 extract_css_module_exports(source, false)
424 .into_iter()
425 .filter_map(|e| match e.name {
426 ExportName::Named(n) => Some(n),
427 ExportName::Default => None,
428 })
429 .collect()
430 }
431
432 #[test]
433 fn is_css_file_css() {
434 assert!(is_css_file(Path::new("styles.css")));
435 }
436
437 #[test]
438 fn is_css_file_scss() {
439 assert!(is_css_file(Path::new("styles.scss")));
440 }
441
442 #[test]
443 fn is_css_file_rejects_js() {
444 assert!(!is_css_file(Path::new("app.js")));
445 }
446
447 #[test]
448 fn is_css_file_rejects_ts() {
449 assert!(!is_css_file(Path::new("app.ts")));
450 }
451
452 #[test]
453 fn is_css_file_rejects_less() {
454 assert!(!is_css_file(Path::new("styles.less")));
455 }
456
457 #[test]
458 fn is_css_file_rejects_no_extension() {
459 assert!(!is_css_file(Path::new("Makefile")));
460 }
461
462 #[test]
463 fn is_css_module_file_module_css() {
464 assert!(is_css_module_file(Path::new("Component.module.css")));
465 }
466
467 #[test]
468 fn is_css_module_file_module_scss() {
469 assert!(is_css_module_file(Path::new("Component.module.scss")));
470 }
471
472 #[test]
473 fn is_css_module_file_rejects_plain_css() {
474 assert!(!is_css_module_file(Path::new("styles.css")));
475 }
476
477 #[test]
478 fn is_css_module_file_rejects_plain_scss() {
479 assert!(!is_css_module_file(Path::new("styles.scss")));
480 }
481
482 #[test]
483 fn is_css_module_file_rejects_module_js() {
484 assert!(!is_css_module_file(Path::new("utils.module.js")));
485 }
486
487 #[test]
488 fn extracts_single_class() {
489 let names = export_names(".foo { color: red; }");
490 assert_eq!(names, vec!["foo"]);
491 }
492
493 #[test]
494 fn extracts_multiple_classes() {
495 let names = export_names(".foo { } .bar { }");
496 assert_eq!(names, vec!["foo", "bar"]);
497 }
498
499 #[test]
500 fn extracts_nested_classes() {
501 let names = export_names(".foo .bar { color: red; }");
502 assert!(names.contains(&"foo".to_string()));
503 assert!(names.contains(&"bar".to_string()));
504 }
505
506 #[test]
507 fn extracts_hyphenated_class() {
508 let names = export_names(".my-class { }");
509 assert_eq!(names, vec!["my-class"]);
510 }
511
512 #[test]
513 fn extracts_camel_case_class() {
514 let names = export_names(".myClass { }");
515 assert_eq!(names, vec!["myClass"]);
516 }
517
518 #[test]
519 fn extracts_underscore_class() {
520 let names = export_names("._hidden { } .__wrapper { }");
521 assert!(names.contains(&"_hidden".to_string()));
522 assert!(names.contains(&"__wrapper".to_string()));
523 }
524
525 #[test]
526 fn pseudo_selector_hover() {
527 let names = export_names(".foo:hover { color: blue; }");
528 assert_eq!(names, vec!["foo"]);
529 }
530
531 #[test]
532 fn pseudo_selector_focus() {
533 let names = export_names(".input:focus { outline: none; }");
534 assert_eq!(names, vec!["input"]);
535 }
536
537 #[test]
538 fn pseudo_element_before() {
539 let names = export_names(".icon::before { content: ''; }");
540 assert_eq!(names, vec!["icon"]);
541 }
542
543 #[test]
544 fn combined_pseudo_selectors() {
545 let names = export_names(".btn:hover, .btn:active, .btn:focus { }");
546 assert_eq!(names, vec!["btn"]);
547 }
548
549 #[test]
550 fn classes_inside_media_query() {
551 let names = export_names(
552 "@media (max-width: 768px) { .mobile-nav { display: block; } .desktop-nav { display: none; } }",
553 );
554 assert!(names.contains(&"mobile-nav".to_string()));
555 assert!(names.contains(&"desktop-nav".to_string()));
556 }
557
558 #[test]
559 fn classes_inside_multi_line_media_query() {
560 let names =
561 export_names("@media\n screen and (min-width: 600px)\n{\n .real { color: red; }\n}");
562 assert_eq!(names, vec!["real"]);
563 }
564
565 #[test]
566 fn at_layer_statement_does_not_export() {
567 let names = export_names("@layer foo.bar;");
568 assert!(names.is_empty(), "got {names:?}");
569 let names = export_names("@layer foo.bar, foo.baz;");
570 assert!(names.is_empty(), "got {names:?}");
571 }
572
573 #[test]
574 fn at_layer_block_keeps_body_classes() {
575 let names = export_names("@layer foo.bar { .root { color: red; } }");
576 assert_eq!(names, vec!["root"]);
577 }
578
579 #[test]
580 fn at_layer_multiline_prelude_keeps_body_classes() {
581 let names = export_names("@layer\n foo.bar\n{ .root { color: red; } }");
582 assert_eq!(names, vec!["root"]);
583 }
584
585 #[test]
586 fn at_layer_with_nested_media_keeps_body() {
587 let names =
588 export_names("@layer foo.bar { @media (max-width: 768px) { .real { color: red; } } }");
589 assert_eq!(names, vec!["real"]);
590 }
591
592 #[test]
593 fn at_import_with_layer_attribute_does_not_export() {
594 let names = export_names(r#"@import url("x.css") layer(theme.button);"#);
595 assert!(names.is_empty(), "got {names:?}");
596 }
597
598 #[test]
599 fn class_then_at_layer_does_not_leak_prelude() {
600 let names =
601 export_names(".outer { color: blue; } @layer foo.bar { .inner { color: red; } }");
602 assert_eq!(names, vec!["outer", "inner"]);
603 }
604
605 #[test]
606 fn at_scope_keeps_selector_list_classes() {
607 let names = export_names("@scope (.parent) to (.child) { .title { color: red; } }");
608 assert!(names.contains(&"parent".to_string()), "got {names:?}");
609 assert!(names.contains(&"child".to_string()), "got {names:?}");
610 assert!(names.contains(&"title".to_string()), "got {names:?}");
611 }
612
613 #[test]
614 fn at_keyframes_numeric_step_is_not_class() {
615 let names = export_names(
616 "@keyframes slide { 0% { transform: scale(.5); } 100% { transform: scale(1); } }",
617 );
618 assert!(names.is_empty(), "got {names:?}");
619 }
620
621 #[test]
622 fn at_webkit_keyframes_keeps_body_classes() {
623 let names = export_names("@-webkit-keyframes slide { 0% { } 100% { } } .real { }");
624 assert_eq!(names, vec!["real"]);
625 }
626
627 #[test]
628 fn deduplicates_repeated_class() {
629 let names = export_names(".btn { color: red; } .btn { font-size: 14px; }");
630 assert_eq!(names.iter().filter(|n| *n == "btn").count(), 1);
631 }
632
633 #[test]
634 fn empty_source() {
635 let names = export_names("");
636 assert!(names.is_empty());
637 }
638
639 #[test]
640 fn no_classes() {
641 let names = export_names("body { margin: 0; } * { box-sizing: border-box; }");
642 assert!(names.is_empty());
643 }
644
645 #[test]
646 fn ignores_classes_in_block_comments() {
647 let names = export_names("/* .fake { } */ .real { }");
648 assert!(!names.contains(&"fake".to_string()));
649 assert!(names.contains(&"real".to_string()));
650 }
651
652 #[test]
653 fn ignores_classes_in_scss_line_comments() {
654 let exports = extract_css_module_exports("// .fake\n.real { }", true);
655 let names: Vec<_> = exports
656 .iter()
657 .filter_map(|e| match &e.name {
658 ExportName::Named(n) => Some(n.as_str()),
659 ExportName::Default => None,
660 })
661 .collect();
662 assert_eq!(names, vec!["real"]);
663 }
664
665 #[test]
666 fn ignores_classes_in_strings() {
667 let names = export_names(r#".real { content: ".fake"; }"#);
668 assert!(names.contains(&"real".to_string()));
669 assert!(!names.contains(&"fake".to_string()));
670 }
671
672 #[test]
673 fn ignores_classes_in_url() {
674 let names = export_names(".real { background: url(./images/hero.png); }");
675 assert!(names.contains(&"real".to_string()));
676 assert!(!names.contains(&"png".to_string()));
677 }
678
679 #[test]
680 fn strip_css_block_comment() {
681 let result = strip_css_comments("/* removed */ .kept { }", false);
682 assert!(!result.contains("removed"));
683 assert!(result.contains(".kept"));
684 }
685
686 #[test]
687 fn strip_scss_line_comment() {
688 let result = strip_css_comments("// removed\n.kept { }", true);
689 assert!(!result.contains("removed"));
690 assert!(result.contains(".kept"));
691 }
692
693 #[test]
694 fn strip_scss_preserves_css_outside_comments() {
695 let source = "// line comment\n/* block comment */\n.visible { color: red; }";
696 let result = strip_css_comments(source, true);
697 assert!(result.contains(".visible"));
698 }
699
700 #[test]
701 fn url_import_http() {
702 assert!(is_css_url_import("http://example.com/style.css"));
703 }
704
705 #[test]
706 fn url_import_https() {
707 assert!(is_css_url_import("https://fonts.googleapis.com/css"));
708 }
709
710 #[test]
711 fn url_import_data() {
712 assert!(is_css_url_import("data:text/css;base64,abc"));
713 }
714
715 #[test]
716 fn url_import_local_not_skipped() {
717 assert!(!is_css_url_import("./local.css"));
718 }
719
720 #[test]
721 fn url_import_bare_specifier_not_skipped() {
722 assert!(!is_css_url_import("tailwindcss"));
723 }
724
725 #[test]
726 fn normalize_relative_dot_path_unchanged() {
727 assert_eq!(
728 normalize_css_import_path("./reset.css".to_string(), false),
729 "./reset.css"
730 );
731 }
732
733 #[test]
734 fn normalize_parent_relative_path_unchanged() {
735 assert_eq!(
736 normalize_css_import_path("../shared.scss".to_string(), false),
737 "../shared.scss"
738 );
739 }
740
741 #[test]
742 fn normalize_absolute_path_unchanged() {
743 assert_eq!(
744 normalize_css_import_path("/styles/main.css".to_string(), false),
745 "/styles/main.css"
746 );
747 }
748
749 #[test]
750 fn normalize_url_unchanged() {
751 assert_eq!(
752 normalize_css_import_path("https://example.com/style.css".to_string(), false),
753 "https://example.com/style.css"
754 );
755 }
756
757 #[test]
758 fn normalize_bare_css_gets_dot_slash() {
759 assert_eq!(
760 normalize_css_import_path("app.css".to_string(), false),
761 "./app.css"
762 );
763 }
764
765 #[test]
766 fn normalize_css_package_subpath_stays_bare() {
767 assert_eq!(
768 normalize_css_import_path("tailwindcss/theme.css".to_string(), false),
769 "tailwindcss/theme.css"
770 );
771 }
772
773 #[test]
774 fn normalize_css_package_subpath_with_dotted_name_stays_bare() {
775 assert_eq!(
776 normalize_css_import_path("highlight.js/styles/github.css".to_string(), false),
777 "highlight.js/styles/github.css"
778 );
779 }
780
781 #[test]
782 fn normalize_bare_scss_gets_dot_slash() {
783 assert_eq!(
784 normalize_css_import_path("vars.scss".to_string(), false),
785 "./vars.scss"
786 );
787 }
788
789 #[test]
790 fn normalize_bare_sass_gets_dot_slash() {
791 assert_eq!(
792 normalize_css_import_path("main.sass".to_string(), false),
793 "./main.sass"
794 );
795 }
796
797 #[test]
798 fn normalize_bare_less_gets_dot_slash() {
799 assert_eq!(
800 normalize_css_import_path("theme.less".to_string(), false),
801 "./theme.less"
802 );
803 }
804
805 #[test]
806 fn normalize_bare_js_extension_stays_bare() {
807 assert_eq!(
808 normalize_css_import_path("module.js".to_string(), false),
809 "module.js"
810 );
811 }
812
813 #[test]
814 fn normalize_scss_bare_partial_gets_dot_slash() {
815 assert_eq!(
816 normalize_css_import_path("variables".to_string(), true),
817 "./variables"
818 );
819 }
820
821 #[test]
822 fn normalize_scss_bare_partial_with_subdir_gets_dot_slash() {
823 assert_eq!(
824 normalize_css_import_path("base/reset".to_string(), true),
825 "./base/reset"
826 );
827 }
828
829 #[test]
830 fn normalize_scss_builtin_stays_bare() {
831 assert_eq!(
832 normalize_css_import_path("sass:math".to_string(), true),
833 "sass:math"
834 );
835 }
836
837 #[test]
838 fn normalize_scss_relative_path_unchanged() {
839 assert_eq!(
840 normalize_css_import_path("../styles/variables".to_string(), true),
841 "../styles/variables"
842 );
843 }
844
845 #[test]
846 fn normalize_css_bare_extensionless_stays_bare() {
847 assert_eq!(
848 normalize_css_import_path("tailwindcss".to_string(), false),
849 "tailwindcss"
850 );
851 }
852
853 #[test]
854 fn normalize_scoped_package_with_css_extension_stays_bare() {
855 assert_eq!(
856 normalize_css_import_path("@fontsource/monaspace-neon/400.css".to_string(), false),
857 "@fontsource/monaspace-neon/400.css"
858 );
859 }
860
861 #[test]
862 fn normalize_scoped_package_with_scss_extension_stays_bare() {
863 assert_eq!(
864 normalize_css_import_path("@company/design-system/tokens.scss".to_string(), true),
865 "@company/design-system/tokens.scss"
866 );
867 }
868
869 #[test]
870 fn normalize_scoped_package_without_extension_stays_bare() {
871 assert_eq!(
872 normalize_css_import_path("@fallow/design-system/styles".to_string(), false),
873 "@fallow/design-system/styles"
874 );
875 }
876
877 #[test]
878 fn normalize_scoped_package_extensionless_scss_stays_bare() {
879 assert_eq!(
880 normalize_css_import_path("@company/tokens".to_string(), true),
881 "@company/tokens"
882 );
883 }
884
885 #[test]
886 fn normalize_path_alias_with_css_extension_stays_bare() {
887 assert_eq!(
888 normalize_css_import_path("@/components/Button.css".to_string(), false),
889 "@/components/Button.css"
890 );
891 }
892
893 #[test]
894 fn normalize_path_alias_extensionless_stays_bare() {
895 assert_eq!(
896 normalize_css_import_path("@/styles/variables".to_string(), false),
897 "@/styles/variables"
898 );
899 }
900
901 #[test]
902 fn strip_css_no_comments() {
903 let source = ".foo { color: red; }";
904 assert_eq!(strip_css_comments(source, false), source);
905 }
906
907 #[test]
908 fn strip_css_multiple_block_comments() {
909 let source = "/* comment-one */ .foo { } /* comment-two */ .bar { }";
910 let result = strip_css_comments(source, false);
911 assert!(!result.contains("comment-one"));
912 assert!(!result.contains("comment-two"));
913 assert!(result.contains(".foo"));
914 assert!(result.contains(".bar"));
915 }
916
917 #[test]
918 fn strip_scss_does_not_affect_non_scss() {
919 let source = "// this stays\n.foo { }";
920 let result = strip_css_comments(source, false);
921 assert!(result.contains("// this stays"));
922 }
923
924 #[test]
925 fn css_module_parses_suppressions() {
926 let info = parse_css_to_module(
927 fallow_types::discover::FileId(0),
928 Path::new("Component.module.css"),
929 "/* fallow-ignore-file */\n.btn { color: red; }",
930 0,
931 );
932 assert!(!info.suppressions.is_empty());
933 assert_eq!(info.suppressions[0].line, 0);
934 }
935
936 #[test]
937 fn extracts_class_starting_with_underscore() {
938 let names = export_names("._private { } .__dunder { }");
939 assert!(names.contains(&"_private".to_string()));
940 assert!(names.contains(&"__dunder".to_string()));
941 }
942
943 #[test]
944 fn ignores_id_selectors() {
945 let names = export_names("#myId { color: red; }");
946 assert!(!names.contains(&"myId".to_string()));
947 }
948
949 #[test]
950 fn ignores_element_selectors() {
951 let names = export_names("div { color: red; } span { }");
952 assert!(names.is_empty());
953 }
954
955 #[test]
956 fn extract_css_imports_at_import_quoted() {
957 let imports = extract_css_imports(r#"@import "./reset.css";"#, false);
958 assert_eq!(imports, vec!["./reset.css"]);
959 }
960
961 #[test]
962 fn extract_css_imports_package_subpath_stays_bare() {
963 let imports =
964 extract_css_imports(r#"@import "tailwindcss/theme.css" layer(theme);"#, false);
965 assert_eq!(imports, vec!["tailwindcss/theme.css"]);
966 }
967
968 #[test]
969 fn extract_css_imports_at_import_url() {
970 let imports = extract_css_imports(r#"@import url("./reset.css");"#, false);
971 assert_eq!(imports, vec!["./reset.css"]);
972 }
973
974 #[test]
975 fn extract_css_imports_skips_remote_urls() {
976 let imports =
977 extract_css_imports(r#"@import "https://fonts.example.com/font.css";"#, false);
978 assert!(imports.is_empty());
979 }
980
981 #[test]
982 fn extract_css_imports_scss_use_normalizes_partial() {
983 let imports = extract_css_imports(r#"@use "variables";"#, true);
984 assert_eq!(imports, vec!["./variables"]);
985 }
986
987 #[test]
988 fn extract_css_imports_scss_forward_normalizes_partial() {
989 let imports = extract_css_imports(r#"@forward "tokens";"#, true);
990 assert_eq!(imports, vec!["./tokens"]);
991 }
992
993 #[test]
994 fn extract_css_imports_skips_comments() {
995 let imports = extract_css_imports(
996 r#"/* @import "./hidden.scss"; */
997@use "real";"#,
998 true,
999 );
1000 assert_eq!(imports, vec!["./real"]);
1001 }
1002
1003 #[test]
1004 fn extract_css_imports_at_plugin_keeps_package_bare() {
1005 let imports = extract_css_imports(r#"@plugin "daisyui";"#, true);
1006 assert_eq!(imports, vec!["daisyui"]);
1007 }
1008
1009 #[test]
1010 fn extract_css_imports_at_plugin_tracks_relative_file() {
1011 let imports = extract_css_imports(r#"@plugin "./tailwind-plugin.js";"#, false);
1012 assert_eq!(imports, vec!["./tailwind-plugin.js"]);
1013 }
1014
1015 #[test]
1016 fn extract_css_imports_scss_at_import_kept_relative() {
1017 let imports = extract_css_imports(r"@import 'Foo';", true);
1018 assert_eq!(imports, vec!["./Foo"]);
1019 }
1020
1021 #[test]
1022 fn extract_css_imports_additional_data_string_body() {
1023 let body = r#"@use "./src/styles/global.scss";"#;
1024 let imports = extract_css_imports(body, true);
1025 assert_eq!(imports, vec!["./src/styles/global.scss"]);
1026 }
1027
1028 #[test]
1029 fn mask_with_whitespace_preserves_byte_length() {
1030 let src = "/* hello */ .foo { }";
1031 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1032 assert_eq!(masked.len(), src.len());
1033 assert!(masked.is_char_boundary(src.len()));
1034 }
1035
1036 #[test]
1037 fn mask_with_whitespace_preserves_offsets_around_multibyte() {
1038 let src = "/* \u{2713} */ .foo { }";
1039 let foo_offset = src.find(".foo").expect("`.foo` present");
1040 let masked = mask_with_whitespace(src, &CSS_COMMENT_RE);
1041 assert_eq!(masked.len(), src.len());
1042 assert_eq!(masked.find(".foo"), Some(foo_offset));
1043 }
1044
1045 fn span_line_col(source: &str, start: u32) -> (u32, u32) {
1048 let offsets = fallow_types::extract::compute_line_offsets(source);
1049 fallow_types::extract::byte_offset_to_line_col(&offsets, start)
1050 }
1051
1052 #[test]
1053 fn span_points_at_real_class_declaration_line() {
1054 let source = "\n\n\n\n.foo { color: red; }\n";
1055 let exports = extract_css_module_exports(source, false);
1056 assert_eq!(exports.len(), 1);
1057 let span = exports[0].span;
1058 let (line, col) = span_line_col(source, span.start);
1059 assert_eq!(line, 5, "`.foo` on line 5 must produce line 5, not line 1");
1060 assert_eq!(
1061 col, 1,
1062 "column points at `f` in `.foo` (post-dot identifier)"
1063 );
1064 assert_eq!(
1065 &source[span.start as usize..span.end as usize],
1066 "foo",
1067 "span range must slice to the class identifier in the original source"
1068 );
1069 }
1070
1071 #[test]
1072 fn span_survives_multibyte_comment_prefix() {
1073 let source = "/* \u{2713} */\n.foo { }";
1074 let exports = extract_css_module_exports(source, false);
1075 assert_eq!(exports.len(), 1);
1076 let span = exports[0].span;
1077 assert!(
1078 source.is_char_boundary(span.start as usize),
1079 "span.start must lie on a UTF-8 char boundary"
1080 );
1081 assert_eq!(&source[span.start as usize..span.end as usize], "foo");
1082 }
1083
1084 #[test]
1085 fn span_skips_at_layer_prelude_dot_segments() {
1086 let source = "@layer foo.bar { }\n.root { }\n";
1087 let exports = extract_css_module_exports(source, false);
1088 let names: Vec<_> = exports
1089 .iter()
1090 .filter_map(|e| match &e.name {
1091 ExportName::Named(n) => Some(n.as_str()),
1092 ExportName::Default => None,
1093 })
1094 .collect();
1095 assert_eq!(names, vec!["root"], "@layer sub-segments must not export");
1096 let span = exports[0].span;
1097 let (line, _col) = span_line_col(source, span.start);
1098 assert_eq!(line, 2, "`.root` lives on line 2 of the original source");
1099 assert_eq!(&source[span.start as usize..span.end as usize], "root");
1100 }
1101
1102 #[test]
1103 fn span_skips_classes_in_strings() {
1104 let source = ".real { content: \".fake\"; }\n.also-real { }\n";
1105 let exports = extract_css_module_exports(source, false);
1106 let names: Vec<_> = exports
1107 .iter()
1108 .filter_map(|e| match &e.name {
1109 ExportName::Named(n) => Some(n.as_str()),
1110 ExportName::Default => None,
1111 })
1112 .collect();
1113 assert_eq!(names, vec!["real", "also-real"]);
1114 for export in &exports {
1115 let span = export.span;
1116 let slice = &source[span.start as usize..span.end as usize];
1117 match &export.name {
1118 ExportName::Named(n) => assert_eq!(slice, n.as_str()),
1119 ExportName::Default => unreachable!("CSS modules emit only named exports"),
1120 }
1121 }
1122 }
1123
1124 #[test]
1125 fn span_deduplicates_to_first_occurrence() {
1126 let source = ".btn { color: red; }\n.btn { color: blue; }\n";
1127 let exports = extract_css_module_exports(source, false);
1128 assert_eq!(exports.len(), 1);
1129 let (line, _col) = span_line_col(source, exports[0].span.start);
1130 assert_eq!(
1131 line, 1,
1132 "first occurrence wins for deduplicated class names"
1133 );
1134 }
1135
1136 #[test]
1137 fn span_inside_media_query() {
1138 let source =
1139 "@media (max-width: 768px) {\n .mobile { display: block; }\n .desktop { }\n}\n";
1140 let exports = extract_css_module_exports(source, false);
1141 let by_name: rustc_hash::FxHashMap<&str, oxc_span::Span> = exports
1142 .iter()
1143 .filter_map(|e| match &e.name {
1144 ExportName::Named(n) => Some((n.as_str(), e.span)),
1145 ExportName::Default => None,
1146 })
1147 .collect();
1148 let mobile_line = span_line_col(source, by_name["mobile"].start).0;
1149 let desktop_line = span_line_col(source, by_name["desktop"].start).0;
1150 assert_eq!(mobile_line, 2);
1151 assert_eq!(desktop_line, 3);
1152 }
1153
1154 #[test]
1155 fn at_layer_only_module_emits_no_exports() {
1156 let exports = extract_css_module_exports("@layer foo.bar, foo.baz;\n", false);
1157 assert!(exports.is_empty());
1158 }
1159
1160 #[test]
1161 fn parse_css_to_module_resolves_real_line_offsets() {
1162 let source = "\n\n\n\n.foo { color: red; }\n";
1163 let info = parse_css_to_module(
1164 fallow_types::discover::FileId(0),
1165 Path::new("Component.module.css"),
1166 source,
1167 0,
1168 );
1169 assert_eq!(info.exports.len(), 1);
1170 let (line, _col) = fallow_types::extract::byte_offset_to_line_col(
1171 &info.line_offsets,
1172 info.exports[0].span.start,
1173 );
1174 assert_eq!(line, 5, "downstream line must equal the source line");
1175 }
1176}