Skip to main content

rspack_lightningcss/
bundler.rs

1//! CSS bundling.
2//!
3//! A [Bundler](Bundler) can be used to combine a CSS file and all of its dependencies
4//! into a single merged style sheet. It works together with a [SourceProvider](SourceProvider)
5//! (e.g. [FileProvider](FileProvider)) to read files from the file system or another source,
6//! and returns a [StyleSheet](super::stylesheet::StyleSheet) containing the rules from all
7//! of the dependencies of the entry file, recursively.
8//!
9//! Rules are bundled following `@import` order, and wrapped in the necessary `@media`, `@supports`,
10//! and `@layer` rules as appropriate to preserve the authored behavior.
11//!
12//! # Example
13//!
14//! ```no_run
15//! use std::path::Path;
16//! use rspack_lightningcss::{
17//!   bundler::{Bundler, FileProvider},
18//!   stylesheet::ParserOptions
19//! };
20//!
21//! let fs = FileProvider::new();
22//! let mut bundler = Bundler::new(&fs, None::<&mut ()>, ParserOptions::default());
23//! let stylesheet = bundler.bundle(Path::new("style.css")).unwrap();
24//! ```
25
26use crate::{
27  error::ErrorLocation,
28  parser::DefaultAtRuleParser,
29  properties::{
30    css_modules::Specifier,
31    custom::{
32      CustomProperty, EnvironmentVariableName, TokenList, TokenOrValue, UnparsedProperty, UnresolvedColor,
33    },
34    Property,
35  },
36  rules::{
37    layer::{LayerBlockRule, LayerName},
38    Location,
39  },
40  traits::{AtRuleParser, ToCss},
41  values::ident::DashedIdentReference,
42};
43use crate::{
44  error::{Error, ParserError},
45  media_query::MediaList,
46  printer::SourceMap,
47  rules::{
48    import::ImportRule,
49    media::MediaRule,
50    supports::{SupportsCondition, SupportsRule},
51    CssRule, CssRuleList,
52  },
53  stylesheet::{ParserOptions, StyleSheet},
54};
55use dashmap::DashMap;
56use rayon::prelude::*;
57use std::{
58  collections::HashSet,
59  fs,
60  path::{Path, PathBuf},
61  sync::Mutex,
62};
63
64/// A Bundler combines a CSS file and all imported dependencies together into
65/// a single merged style sheet.
66pub struct Bundler<'a, 's, P, T: AtRuleParser<'a>, S = ()> {
67  source_map: Option<Mutex<&'s mut S>>,
68  fs: &'a P,
69  source_indexes: DashMap<PathBuf, u32>,
70  stylesheets: Mutex<Vec<BundleStyleSheet<'a, T::AtRule>>>,
71  options: ParserOptions<'a>,
72  at_rule_parser: Mutex<AtRuleParserValue<'s, T>>,
73}
74
75enum AtRuleParserValue<'a, T> {
76  Owned(T),
77  Borrowed(&'a mut T),
78}
79
80struct BundleStyleSheet<'i, T> {
81  stylesheet: Option<StyleSheet<'i, T>>,
82  source_map_source_index: Option<u32>,
83  dependencies: Vec<Dependency>,
84  css_modules_deps: Vec<u32>,
85  parent_source_index: u32,
86  parent_dep_index: u32,
87  layer: Option<Option<LayerName<'i>>>,
88  supports: Option<SupportsCondition<'i>>,
89  media: MediaList<'i>,
90  loc: Location,
91}
92
93#[derive(Debug, Clone)]
94enum Dependency {
95  File(u32),
96  External(String),
97}
98
99/// The result of [SourceProvider::resolve].
100#[derive(Debug)]
101#[cfg_attr(
102  any(feature = "serde", feature = "nodejs"),
103  derive(serde::Deserialize),
104  serde(rename_all = "lowercase")
105)]
106pub enum ResolveResult {
107  /// An external URL.
108  External(String),
109  /// A file path.
110  #[cfg_attr(any(feature = "serde", feature = "nodejs"), serde(untagged))]
111  File(PathBuf),
112}
113
114impl From<PathBuf> for ResolveResult {
115  fn from(path: PathBuf) -> Self {
116    ResolveResult::File(path)
117  }
118}
119
120/// A trait to provide the contents of files to a Bundler.
121///
122/// See [FileProvider](FileProvider) for an implementation that uses the
123/// file system.
124pub trait SourceProvider: Send + Sync {
125  /// A custom error.
126  type Error: std::error::Error + Send + Sync;
127
128  /// Reads the contents of the given file path to a string.
129  fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error>;
130
131  /// Resolves the given import specifier to a file path given the file
132  /// which the import originated from.
133  fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error>;
134}
135
136/// Provides an implementation of [SourceProvider](SourceProvider)
137/// that reads files from the file system.
138pub struct FileProvider {
139  inputs: Mutex<Vec<*mut String>>,
140}
141
142impl FileProvider {
143  /// Creates a new FileProvider.
144  pub fn new() -> FileProvider {
145    FileProvider {
146      inputs: Mutex::new(Vec::new()),
147    }
148  }
149}
150
151unsafe impl Sync for FileProvider {}
152unsafe impl Send for FileProvider {}
153
154impl SourceProvider for FileProvider {
155  type Error = std::io::Error;
156
157  fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
158    let source = fs::read_to_string(file)?;
159    let ptr = Box::into_raw(Box::new(source));
160    self.inputs.lock().unwrap().push(ptr);
161    // SAFETY: this is safe because the pointer is not dropped
162    // until the FileProvider is, and we never remove from the
163    // list of pointers stored in the vector.
164    Ok(unsafe { &*ptr })
165  }
166
167  fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error> {
168    // Assume the specifier is a relative file path and join it with current path.
169    Ok(originating_file.with_file_name(specifier).into())
170  }
171}
172
173impl Drop for FileProvider {
174  fn drop(&mut self) {
175    for ptr in self.inputs.lock().unwrap().iter() {
176      std::mem::drop(unsafe { Box::from_raw(*ptr) })
177    }
178  }
179}
180
181/// An error that could occur during bundling.
182#[derive(Debug)]
183#[cfg_attr(any(feature = "serde", feature = "nodejs"), derive(serde::Serialize))]
184pub enum BundleErrorKind<'i, T: std::error::Error> {
185  /// A parser error occurred.
186  ParserError(ParserError<'i>),
187  /// An unsupported `@import` condition was encountered.
188  UnsupportedImportCondition,
189  /// An unsupported cascade layer combination was encountered.
190  UnsupportedLayerCombination,
191  /// Unsupported media query boolean logic was encountered.
192  UnsupportedMediaBooleanLogic,
193  /// An external module was referenced with a CSS module "from" clause.
194  ReferencedExternalModuleWithCssModuleFrom,
195  /// An external `@import` was found after a bundled `@import`.
196  /// This may result in unintended selector order.
197  ExternalImportAfterBundledImport,
198  /// A custom resolver error.
199  ResolverError(#[cfg_attr(any(feature = "serde", feature = "nodejs"), serde(skip))] T),
200}
201
202impl<'i, T: std::error::Error> From<Error<ParserError<'i>>> for Error<BundleErrorKind<'i, T>> {
203  fn from(err: Error<ParserError<'i>>) -> Self {
204    Error {
205      kind: BundleErrorKind::ParserError(err.kind),
206      loc: err.loc,
207    }
208  }
209}
210
211impl<'i, T: std::error::Error> std::fmt::Display for BundleErrorKind<'i, T> {
212  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213    use BundleErrorKind::*;
214    match self {
215      ParserError(err) => err.fmt(f),
216      UnsupportedImportCondition => write!(f, "Unsupported import condition"),
217      UnsupportedLayerCombination => write!(f, "Unsupported layer combination in @import"),
218      UnsupportedMediaBooleanLogic => write!(f, "Unsupported boolean logic in @import media query"),
219      ReferencedExternalModuleWithCssModuleFrom => {
220        write!(f, "Referenced external module with CSS module \"from\" clause")
221      }
222      ExternalImportAfterBundledImport => write!(
223        f,
224        "An external `@import` was found after a bundled `@import`. This may result in unintended selector order."
225      ),
226      ResolverError(err) => std::fmt::Display::fmt(&err, f),
227    }
228  }
229}
230
231impl<'i, T: std::error::Error> BundleErrorKind<'i, T> {
232  #[deprecated(note = "use `BundleErrorKind::to_string()` or `std::fmt::Display` instead")]
233  #[allow(missing_docs)]
234  pub fn reason(&self) -> String {
235    self.to_string()
236  }
237}
238
239impl<'a, 's, P: SourceProvider, S: SourceMap + Send> Bundler<'a, 's, P, DefaultAtRuleParser, S> {
240  /// Creates a new Bundler using the given source provider.
241  /// If a source map is given, the content of each source file included in the bundle will
242  /// be added accordingly.
243  pub fn new(
244    fs: &'a P,
245    source_map: Option<&'s mut S>,
246    options: ParserOptions<'a>,
247  ) -> Bundler<'a, 's, P, DefaultAtRuleParser, S> {
248    Bundler {
249      source_map: source_map.map(Mutex::new),
250      fs,
251      source_indexes: DashMap::new(),
252      stylesheets: Mutex::new(Vec::new()),
253      options,
254      at_rule_parser: Mutex::new(AtRuleParserValue::Owned(DefaultAtRuleParser)),
255    }
256  }
257}
258
259impl<'a, 's, P: SourceProvider, T: AtRuleParser<'a> + Clone + Sync + Send, S: SourceMap + Send>
260  Bundler<'a, 's, P, T, S>
261where
262  T::AtRule: Sync + Send + ToCss + Clone,
263{
264  /// Creates a new Bundler using the given source provider.
265  /// If a source map is given, the content of each source file included in the bundle will
266  /// be added accordingly.
267  pub fn new_with_at_rule_parser(
268    fs: &'a P,
269    source_map: Option<&'s mut S>,
270    options: ParserOptions<'a>,
271    at_rule_parser: &'s mut T,
272  ) -> Self {
273    Bundler {
274      source_map: source_map.map(Mutex::new),
275      fs,
276      source_indexes: DashMap::new(),
277      stylesheets: Mutex::new(Vec::new()),
278      options,
279      at_rule_parser: Mutex::new(AtRuleParserValue::Borrowed(at_rule_parser)),
280    }
281  }
282
283  /// Bundles the given entry file and all dependencies into a single style sheet.
284  pub fn bundle<'e>(
285    &mut self,
286    entry: &'e Path,
287  ) -> Result<StyleSheet<'a, T::AtRule>, Error<BundleErrorKind<'a, P::Error>>> {
288    // Phase 1: load and parse all files. This is done in parallel.
289    self.load_file(
290      &entry,
291      ImportRule {
292        url: "".into(),
293        layer: None,
294        supports: None,
295        media: MediaList::new(),
296        loc: Location {
297          source_index: 0,
298          line: 0,
299          column: 0,
300        },
301      },
302    )?;
303
304    // Phase 2: determine the order that the files should be concatenated.
305    self.order();
306
307    // Phase 3: concatenate.
308    let mut rules: Vec<CssRule<'a, T::AtRule>> = Vec::new();
309    self.inline(&mut rules)?;
310
311    let sources = self
312      .stylesheets
313      .get_mut()
314      .unwrap()
315      .iter()
316      .flat_map(|s| s.stylesheet.as_ref().unwrap().sources.iter().cloned())
317      .collect();
318
319    let mut stylesheet = StyleSheet::new(sources, CssRuleList(rules), self.options.clone());
320
321    if self.source_map.is_some() {
322      stylesheet.source_map_source_indices = self
323        .stylesheets
324        .get_mut()
325        .unwrap()
326        .iter()
327        .map(|s| s.source_map_source_index)
328        .collect();
329    }
330
331    stylesheet.source_map_urls = self
332      .stylesheets
333      .get_mut()
334      .unwrap()
335      .iter()
336      .flat_map(|s| s.stylesheet.as_ref().unwrap().source_map_urls.iter().cloned())
337      .collect();
338
339    stylesheet.license_comments = self
340      .stylesheets
341      .get_mut()
342      .unwrap()
343      .iter()
344      .flat_map(|s| s.stylesheet.as_ref().unwrap().license_comments.iter().cloned())
345      .collect();
346
347    if let Some(config) = &self.options.css_modules {
348      if config.pattern.has_content_hash() {
349        stylesheet.content_hashes = Some(
350          self
351            .stylesheets
352            .get_mut()
353            .unwrap()
354            .iter()
355            .flat_map(|s| {
356              let s = s.stylesheet.as_ref().unwrap();
357              s.content_hashes.as_ref().unwrap().iter().cloned()
358            })
359            .collect(),
360        );
361      }
362    }
363
364    Ok(stylesheet)
365  }
366
367  fn find_filename(&self, source_index: u32) -> String {
368    // This function is only used for error handling, so it's ok if this is a bit slow.
369    let entry = self.source_indexes.iter().find(|x| *x.value() == source_index).unwrap();
370    entry.key().to_str().unwrap().into()
371  }
372
373  fn load_file(&self, file: &Path, rule: ImportRule<'a>) -> Result<u32, Error<BundleErrorKind<'a, P::Error>>> {
374    // Check if we already loaded this file.
375    let mut stylesheets = self.stylesheets.lock().unwrap();
376    let source_index = match self.source_indexes.get(file) {
377      Some(source_index) => {
378        // If we already loaded this file, combine the media queries and supports conditions
379        // from this import rule with the existing ones using a logical or operator.
380        let entry = &mut stylesheets[*source_index as usize];
381
382        // We cannot combine a media query and a supports query from different @import rules.
383        // e.g. @import "a.css" print; @import "a.css" supports(color: red);
384        // This would require duplicating the actual rules in the file.
385        if (!rule.media.media_queries.is_empty() && !entry.supports.is_none())
386          || (!entry.media.media_queries.is_empty() && !rule.supports.is_none())
387        {
388          return Err(Error {
389            kind: BundleErrorKind::UnsupportedImportCondition,
390            loc: Some(ErrorLocation::new(rule.loc, self.find_filename(rule.loc.source_index))),
391          });
392        }
393
394        if rule.media.media_queries.is_empty() {
395          entry.media.media_queries.clear();
396        } else if !entry.media.media_queries.is_empty() {
397          entry.media.or(&rule.media);
398        }
399
400        if let Some(supports) = rule.supports {
401          if let Some(existing_supports) = &mut entry.supports {
402            existing_supports.or(&supports)
403          }
404        } else {
405          entry.supports = None;
406        }
407
408        if let Some(layer) = &rule.layer {
409          if let Some(existing_layer) = &entry.layer {
410            // We can't OR layer names without duplicating all of the nested rules, so error for now.
411            if layer != existing_layer || (layer.is_none() && existing_layer.is_none()) {
412              return Err(Error {
413                kind: BundleErrorKind::UnsupportedLayerCombination,
414                loc: Some(ErrorLocation::new(rule.loc, self.find_filename(rule.loc.source_index))),
415              });
416            }
417          } else {
418            entry.layer = rule.layer;
419          }
420        }
421
422        return Ok(*source_index);
423      }
424      None => {
425        let source_index = stylesheets.len() as u32;
426        self.source_indexes.insert(file.to_owned(), source_index);
427
428        stylesheets.push(BundleStyleSheet {
429          stylesheet: None,
430          source_map_source_index: None,
431          layer: rule.layer.clone(),
432          media: rule.media.clone(),
433          supports: rule.supports.clone(),
434          loc: rule.loc.clone(),
435          dependencies: Vec::new(),
436          css_modules_deps: Vec::new(),
437          parent_source_index: 0,
438          parent_dep_index: 0,
439        });
440
441        source_index
442      }
443    };
444
445    drop(stylesheets); // ensure we aren't holding the lock anymore
446
447    let code = self.fs.read(file).map_err(|e| Error {
448      kind: BundleErrorKind::ResolverError(e),
449      loc: if rule.loc.column == 0 {
450        None
451      } else {
452        Some(ErrorLocation::new(rule.loc, self.find_filename(rule.loc.source_index)))
453      },
454    })?;
455
456    let mut opts = self.options.clone();
457    let filename = file.to_str().unwrap();
458    opts.filename = filename.to_owned();
459    opts.source_index = source_index;
460
461    let mut stylesheet = {
462      let mut at_rule_parser = self.at_rule_parser.lock().unwrap();
463      let at_rule_parser = match &mut *at_rule_parser {
464        AtRuleParserValue::Owned(owned) => owned,
465        AtRuleParserValue::Borrowed(borrowed) => *borrowed,
466      };
467
468      StyleSheet::<T::AtRule>::parse_with(code, opts, at_rule_parser)?
469    };
470
471    let mut source_map_source_index = None;
472    if let Some(source_map) = &self.source_map {
473      // Only omit the CSS source when the input source map can actually be read.
474      // Otherwise, the printer needs this index as a fallback for generated mappings.
475      if stylesheet.source_map::<S>(0).is_none() {
476        let mut source_map = source_map.lock().unwrap();
477        let source_index = source_map.add_source(filename);
478        source_map.set_source_content(source_index, code);
479        source_map_source_index = Some(source_index);
480      }
481    }
482
483    // Collect and load dependencies for this stylesheet in parallel.
484    let dependencies: Result<Vec<Dependency>, _> = stylesheet
485      .rules
486      .0
487      .par_iter_mut()
488      .filter_map(|r| {
489        // Prepend parent layer name to @layer statements.
490        if let CssRule::LayerStatement(layer) = r {
491          if let Some(Some(parent_layer)) = &rule.layer {
492            for name in &mut layer.names {
493              name.0.insert_many(0, parent_layer.0.iter().cloned())
494            }
495          }
496        }
497
498        if let CssRule::Import(import) = r {
499          let specifier = &import.url;
500
501          // Combine media queries and supports conditions from parent
502          // stylesheet with @import rule using a logical and operator.
503          let mut media = rule.media.clone();
504          let result = media.and(&import.media).map_err(|_| Error {
505            kind: BundleErrorKind::UnsupportedMediaBooleanLogic,
506            loc: Some(ErrorLocation::new(
507              import.loc,
508              self.find_filename(import.loc.source_index),
509            )),
510          });
511
512          if let Err(e) = result {
513            return Some(Err(e));
514          }
515
516          let layer = if (rule.layer == Some(None) && import.layer.is_some())
517            || (import.layer == Some(None) && rule.layer.is_some())
518          {
519            // Cannot combine anonymous layers
520            return Some(Err(Error {
521              kind: BundleErrorKind::UnsupportedLayerCombination,
522              loc: Some(ErrorLocation::new(
523                import.loc,
524                self.find_filename(import.loc.source_index),
525              )),
526            }));
527          } else if let Some(Some(a)) = &rule.layer {
528            if let Some(Some(b)) = &import.layer {
529              let mut name = a.clone();
530              name.0.extend(b.0.iter().cloned());
531              Some(Some(name))
532            } else {
533              Some(Some(a.clone()))
534            }
535          } else {
536            import.layer.clone()
537          };
538
539          let result = match self.fs.resolve(&specifier, file) {
540            Ok(ResolveResult::File(path)) => self
541              .load_file(
542                &path,
543                ImportRule {
544                  layer,
545                  media,
546                  supports: combine_supports(rule.supports.clone(), &import.supports),
547                  url: "".into(),
548                  loc: import.loc,
549                },
550              )
551              .map(Dependency::File),
552            Ok(ResolveResult::External(url)) => Ok(Dependency::External(url)),
553            Err(err) => Err(Error {
554              kind: BundleErrorKind::ResolverError(err),
555              loc: Some(ErrorLocation::new(
556                import.loc,
557                self.find_filename(import.loc.source_index),
558              )),
559            }),
560          };
561
562          Some(result)
563        } else {
564          None
565        }
566      })
567      .collect();
568
569    // Collect CSS modules dependencies from the `composes` property.
570    let css_modules_deps: Result<Vec<u32>, _> = if self.options.css_modules.is_some() {
571      stylesheet
572        .rules
573        .0
574        .par_iter_mut()
575        .filter_map(|r| {
576          if let CssRule::Style(style) = r {
577            Some(
578              style
579                .declarations
580                .declarations
581                .par_iter_mut()
582                .chain(style.declarations.important_declarations.par_iter_mut())
583                .filter_map(|d| match d {
584                  Property::Composes(composes) => self
585                    .add_css_module_dep(file, &rule, style.loc, composes.loc, &mut composes.from)
586                    .map(|result| rayon::iter::Either::Left(rayon::iter::once(result))),
587
588                  // Handle variable references if the dashed_idents option is present.
589                  Property::Custom(CustomProperty { value, .. })
590                  | Property::Unparsed(UnparsedProperty { value, .. })
591                    if matches!(&self.options.css_modules, Some(css_modules) if css_modules.dashed_idents) =>
592                  {
593                    Some(rayon::iter::Either::Right(visit_vars(value).filter_map(|name| {
594                      self.add_css_module_dep(
595                        file,
596                        &rule,
597                        style.loc,
598                        // TODO: store loc in variable reference?
599                        crate::dependencies::Location {
600                          line: style.loc.line,
601                          column: style.loc.column,
602                        },
603                        &mut name.from,
604                      )
605                    })))
606                  }
607                  _ => None,
608                })
609                .flatten(),
610            )
611          } else {
612            None
613          }
614        })
615        .flatten()
616        .collect()
617    } else {
618      Ok(vec![])
619    };
620
621    let entry = &mut self.stylesheets.lock().unwrap()[source_index as usize];
622    entry.stylesheet = Some(stylesheet);
623    entry.source_map_source_index = source_map_source_index;
624    entry.dependencies = dependencies?;
625    entry.css_modules_deps = css_modules_deps?;
626
627    Ok(source_index)
628  }
629
630  fn add_css_module_dep(
631    &self,
632    file: &Path,
633    rule: &ImportRule<'a>,
634    style_loc: Location,
635    loc: crate::dependencies::Location,
636    specifier: &mut Option<Specifier>,
637  ) -> Option<Result<u32, Error<BundleErrorKind<'a, P::Error>>>> {
638    if let Some(Specifier::File(f)) = specifier {
639      let result = match self.fs.resolve(&f, file) {
640        Ok(ResolveResult::File(path)) => {
641          let res = self.load_file(
642            &path,
643            ImportRule {
644              layer: rule.layer.clone(),
645              media: rule.media.clone(),
646              supports: rule.supports.clone(),
647              url: "".into(),
648              loc: Location {
649                source_index: style_loc.source_index,
650                line: loc.line,
651                column: loc.column,
652              },
653            },
654          );
655
656          if let Ok(source_index) = res {
657            *specifier = Some(Specifier::SourceIndex(source_index));
658          }
659
660          res
661        }
662        Ok(ResolveResult::External(_)) => Err(Error {
663          kind: BundleErrorKind::ReferencedExternalModuleWithCssModuleFrom,
664          loc: Some(ErrorLocation::new(
665            style_loc,
666            self.find_filename(style_loc.source_index),
667          )),
668        }),
669        Err(err) => Err(Error {
670          kind: BundleErrorKind::ResolverError(err),
671          loc: Some(ErrorLocation::new(
672            style_loc,
673            self.find_filename(style_loc.source_index),
674          )),
675        }),
676      };
677      Some(result)
678    } else {
679      None
680    }
681  }
682
683  fn order(&mut self) {
684    process(self.stylesheets.get_mut().unwrap(), 0, &mut HashSet::new());
685
686    fn process<'i, T>(
687      stylesheets: &mut Vec<BundleStyleSheet<'i, T>>,
688      source_index: u32,
689      visited: &mut HashSet<u32>,
690    ) {
691      if visited.contains(&source_index) {
692        return;
693      }
694
695      visited.insert(source_index);
696
697      let mut dep_index = 0;
698      for i in 0..stylesheets[source_index as usize].css_modules_deps.len() {
699        let dep_source_index = stylesheets[source_index as usize].css_modules_deps[i];
700        let resolved = &mut stylesheets[dep_source_index as usize];
701
702        // CSS modules preserve the first instance of composed stylesheets.
703        if !visited.contains(&dep_source_index) {
704          resolved.parent_dep_index = dep_index;
705          resolved.parent_source_index = source_index;
706          process(stylesheets, dep_source_index, visited);
707        }
708
709        dep_index += 1;
710      }
711
712      for i in 0..stylesheets[source_index as usize].dependencies.len() {
713        let Dependency::File(dep_source_index) = stylesheets[source_index as usize].dependencies[i] else {
714          continue;
715        };
716        let resolved = &mut stylesheets[dep_source_index as usize];
717
718        // In browsers, every instance of an @import is evaluated, so we preserve the last.
719        resolved.parent_dep_index = dep_index;
720        resolved.parent_source_index = source_index;
721
722        process(stylesheets, dep_source_index, visited);
723        dep_index += 1;
724      }
725    }
726  }
727
728  fn inline(
729    &mut self,
730    dest: &mut Vec<CssRule<'a, T::AtRule>>,
731  ) -> Result<(), Error<BundleErrorKind<'a, P::Error>>> {
732    fn process<'a, T, E: std::error::Error>(
733      stylesheets: &mut Vec<BundleStyleSheet<'a, T>>,
734      source_index: u32,
735      dest: &mut Vec<CssRule<'a, T>>,
736      filename: &String,
737    ) -> Result<(), Error<BundleErrorKind<'a, E>>> {
738      let stylesheet = &mut stylesheets[source_index as usize];
739      let mut rules = std::mem::take(&mut stylesheet.stylesheet.as_mut().unwrap().rules.0);
740
741      // Hoist css modules deps
742      let mut dep_index = 0;
743      for i in 0..stylesheet.css_modules_deps.len() {
744        let dep_source_index = stylesheets[source_index as usize].css_modules_deps[i];
745        let resolved = &stylesheets[dep_source_index as usize];
746
747        // Include the dependency if this is the first instance as computed earlier.
748        if resolved.parent_source_index == source_index && resolved.parent_dep_index == dep_index as u32 {
749          process(stylesheets, dep_source_index, dest, filename)?;
750        }
751
752        dep_index += 1;
753      }
754
755      let mut import_index = 0;
756      let mut has_bundled_import = false;
757      for rule in &mut rules {
758        match rule {
759          CssRule::Import(import_rule) => {
760            let dep_source = &stylesheets[source_index as usize].dependencies[import_index];
761            match dep_source {
762              Dependency::File(dep_source_index) => {
763                let resolved = &stylesheets[*dep_source_index as usize];
764
765                // Include the dependency if this is the last instance as computed earlier.
766                if resolved.parent_source_index == source_index && resolved.parent_dep_index == dep_index {
767                  has_bundled_import = true;
768                  process(stylesheets, *dep_source_index, dest, filename)?;
769                }
770
771                *rule = CssRule::Ignored;
772                dep_index += 1;
773              }
774              Dependency::External(url) => {
775                if has_bundled_import {
776                  return Err(Error {
777                    kind: BundleErrorKind::ExternalImportAfterBundledImport,
778                    loc: Some(ErrorLocation {
779                      filename: filename.clone(),
780                      line: import_rule.loc.line,
781                      column: import_rule.loc.column,
782                    }),
783                  });
784                }
785                import_rule.url = url.to_owned().into();
786                let imp = std::mem::replace(rule, CssRule::Ignored);
787                dest.push(imp);
788              }
789            }
790            import_index += 1;
791          }
792          CssRule::LayerStatement(_) => {
793            // @layer rules are the only rules that may appear before an @import.
794            // We must preserve this order to ensure correctness.
795            let layer = std::mem::replace(rule, CssRule::Ignored);
796            dest.push(layer);
797          }
798          CssRule::Ignored => {}
799          _ => break,
800        }
801      }
802
803      // Wrap rules in the appropriate @layer, @media, and @supports rules.
804      let stylesheet = &mut stylesheets[source_index as usize];
805
806      if stylesheet.layer.is_some() {
807        rules = vec![CssRule::LayerBlock(LayerBlockRule {
808          name: stylesheet.layer.take().unwrap(),
809          rules: CssRuleList(rules),
810          loc: stylesheet.loc,
811        })]
812      }
813
814      if !stylesheet.media.media_queries.is_empty() {
815        rules = vec![CssRule::Media(MediaRule {
816          query: std::mem::replace(&mut stylesheet.media, MediaList::new()),
817          rules: CssRuleList(rules),
818          loc: stylesheet.loc,
819        })]
820      }
821
822      if stylesheet.supports.is_some() {
823        rules = vec![CssRule::Supports(SupportsRule {
824          condition: stylesheet.supports.take().unwrap(),
825          rules: CssRuleList(rules),
826          loc: stylesheet.loc,
827        })]
828      }
829
830      dest.extend(rules);
831      Ok(())
832    }
833
834    process(self.stylesheets.get_mut().unwrap(), 0, dest, &self.options.filename)
835  }
836}
837
838fn combine_supports<'a>(
839  a: Option<SupportsCondition<'a>>,
840  b: &Option<SupportsCondition<'a>>,
841) -> Option<SupportsCondition<'a>> {
842  if let Some(mut a) = a {
843    if let Some(b) = b {
844      a.and(b)
845    }
846    Some(a)
847  } else {
848    b.clone()
849  }
850}
851
852fn visit_vars<'a, 'b>(
853  token_list: &'b mut TokenList<'a>,
854) -> impl ParallelIterator<Item = &'b mut DashedIdentReference<'a>> {
855  let mut stack = vec![token_list.0.iter_mut()];
856  std::iter::from_fn(move || {
857    while !stack.is_empty() {
858      let iter = stack.last_mut().unwrap();
859      match iter.next() {
860        Some(TokenOrValue::Var(var)) => {
861          if let Some(fallback) = &mut var.fallback {
862            stack.push(fallback.0.iter_mut());
863          }
864          return Some(&mut var.name);
865        }
866        Some(TokenOrValue::Env(env)) => {
867          if let Some(fallback) = &mut env.fallback {
868            stack.push(fallback.0.iter_mut());
869          }
870          if let EnvironmentVariableName::Custom(name) = &mut env.name {
871            return Some(name);
872          }
873        }
874        Some(TokenOrValue::UnresolvedColor(color)) => match color {
875          UnresolvedColor::RGB { alpha, .. } | UnresolvedColor::HSL { alpha, .. } => {
876            stack.push(alpha.0.iter_mut());
877          }
878          UnresolvedColor::LightDark { light, dark } => {
879            stack.push(light.0.iter_mut());
880            stack.push(dark.0.iter_mut());
881          }
882        },
883        None => {
884          stack.pop();
885        }
886        _ => {}
887      }
888    }
889    None
890  })
891  .par_bridge()
892}
893
894#[cfg(test)]
895mod tests {
896  use super::*;
897  use crate::{
898    css_modules::{self, CssModuleExports, CssModuleReference},
899    parser::ParserFlags,
900    stylesheet::{MinifyOptions, PrinterOptions},
901    targets::{Browsers, Targets},
902  };
903  use indoc::indoc;
904  use std::collections::HashMap;
905
906  #[derive(Clone)]
907  struct TestProvider {
908    map: HashMap<PathBuf, String>,
909  }
910
911  impl SourceProvider for TestProvider {
912    type Error = std::io::Error;
913
914    fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
915      Ok(self.map.get(file).unwrap())
916    }
917
918    fn resolve(&self, specifier: &str, originating_file: &Path) -> Result<ResolveResult, Self::Error> {
919      if specifier.starts_with("https:") {
920        Ok(ResolveResult::External(specifier.to_owned()))
921      } else {
922        Ok(originating_file.with_file_name(specifier).into())
923      }
924    }
925  }
926
927  /// Stand-in for a user-authored `SourceProvider` with application-specific logic.
928  struct CustomProvider {
929    map: HashMap<PathBuf, String>,
930  }
931
932  impl SourceProvider for CustomProvider {
933    type Error = std::io::Error;
934
935    /// Read files from in-memory map.
936    fn read<'a>(&'a self, file: &Path) -> Result<&'a str, Self::Error> {
937      Ok(self.map.get(file).unwrap())
938    }
939
940    /// Resolve by stripping a `foo:` prefix off any import. Specifiers without
941    /// this prefix fail with an error.
942    fn resolve(&self, specifier: &str, _originating_file: &Path) -> Result<ResolveResult, Self::Error> {
943      if specifier.starts_with("foo:") {
944        Ok(Path::new(&specifier["foo:".len()..]).to_path_buf().into())
945      } else {
946        let err = std::io::Error::new(
947          std::io::ErrorKind::NotFound,
948          format!(
949            "Failed to resolve `{}`, specifier does not start with `foo:`.",
950            &specifier
951          ),
952        );
953
954        Err(err)
955      }
956    }
957  }
958
959  macro_rules! fs(
960    { $($key:literal: $value:expr),* } => {
961      {
962        #[allow(unused_mut)]
963        let mut m = HashMap::new();
964        $(
965          m.insert(PathBuf::from($key), $value.to_owned());
966        )*
967        m
968      }
969    };
970  );
971
972  fn bundle<P: SourceProvider>(fs: P, entry: &str) -> String {
973    let mut bundler = Bundler::<_, _, ()>::new(&fs, None, ParserOptions::default());
974    let stylesheet = bundler.bundle(Path::new(entry)).unwrap();
975    stylesheet.to_css(PrinterOptions::default(), None::<&mut ()>).unwrap().code
976  }
977
978  fn bundle_css_module<P: SourceProvider>(
979    fs: P,
980    entry: &str,
981    project_root: Option<&str>,
982  ) -> (String, CssModuleExports) {
983    bundle_css_module_with_pattern(fs, entry, project_root, "[hash]_[local]")
984  }
985
986  fn bundle_css_module_with_pattern<P: SourceProvider>(
987    fs: P,
988    entry: &str,
989    project_root: Option<&str>,
990    pattern: &'static str,
991  ) -> (String, CssModuleExports) {
992    let mut bundler = Bundler::<_, _, ()>::new(
993      &fs,
994      None,
995      ParserOptions {
996        css_modules: Some(css_modules::Config {
997          dashed_idents: true,
998          pattern: css_modules::Pattern::parse(pattern).unwrap(),
999          ..Default::default()
1000        }),
1001        ..ParserOptions::default()
1002      },
1003    );
1004    let mut stylesheet = bundler.bundle(Path::new(entry)).unwrap();
1005    stylesheet.minify(MinifyOptions::default()).unwrap();
1006    let res = stylesheet
1007      .to_css(
1008        PrinterOptions {
1009          project_root,
1010          ..PrinterOptions::default()
1011        },
1012        None::<&mut ()>,
1013      )
1014      .unwrap();
1015    (res.code, res.exports.unwrap())
1016  }
1017
1018  fn bundle_custom_media<P: SourceProvider>(fs: P, entry: &str) -> String {
1019    let mut bundler = Bundler::<_, _, ()>::new(
1020      &fs,
1021      None,
1022      ParserOptions {
1023        flags: ParserFlags::CUSTOM_MEDIA,
1024        ..ParserOptions::default()
1025      },
1026    );
1027    let mut stylesheet = bundler.bundle(Path::new(entry)).unwrap();
1028    let targets = Targets {
1029      browsers: Some(Browsers {
1030        safari: Some(13 << 16),
1031        ..Browsers::default()
1032      }),
1033      ..Default::default()
1034    };
1035    stylesheet
1036      .minify(MinifyOptions {
1037        targets,
1038        ..MinifyOptions::default()
1039      })
1040      .unwrap();
1041    stylesheet
1042      .to_css(
1043        PrinterOptions {
1044          targets,
1045          ..PrinterOptions::default()
1046        },
1047        None::<&mut ()>,
1048      )
1049      .unwrap()
1050      .code
1051  }
1052
1053  fn error_test<P: SourceProvider>(
1054    fs: P,
1055    entry: &str,
1056    maybe_cb: Option<Box<dyn FnOnce(BundleErrorKind<P::Error>) -> ()>>,
1057  ) {
1058    let mut bundler = Bundler::<_, _, ()>::new(&fs, None, ParserOptions::default());
1059    let res = bundler.bundle(Path::new(entry));
1060    match res {
1061      Ok(_) => unreachable!(),
1062      Err(e) => {
1063        if let Some(cb) = maybe_cb {
1064          cb(e.kind);
1065        }
1066      }
1067    }
1068  }
1069
1070  fn flatten_exports(exports: CssModuleExports) -> HashMap<String, String> {
1071    let mut res = HashMap::new();
1072    for (name, export) in &exports {
1073      let mut classes = export.name.clone();
1074      for composes in &export.composes {
1075        classes.push(' ');
1076        classes.push_str(match composes {
1077          CssModuleReference::Local { name } => name,
1078          CssModuleReference::Global { name } => name,
1079          _ => unreachable!(),
1080        })
1081      }
1082      res.insert(name.clone(), classes);
1083    }
1084    res
1085  }
1086
1087  #[test]
1088  fn test_bundle() {
1089    let res = bundle(
1090      TestProvider {
1091        map: fs! {
1092          "/a.css": r#"
1093          @import "b.css";
1094          .a { color: red }
1095        "#,
1096          "/b.css": r#"
1097          .b { color: green }
1098        "#
1099        },
1100      },
1101      "/a.css",
1102    );
1103    assert_eq!(
1104      res,
1105      indoc! { r#"
1106      .b {
1107        color: green;
1108      }
1109
1110      .a {
1111        color: red;
1112      }
1113    "#}
1114    );
1115
1116    let res = bundle(
1117      TestProvider {
1118        map: fs! {
1119          "/a.css": r#"
1120          @import "b.css" print;
1121          .a { color: red }
1122        "#,
1123          "/b.css": r#"
1124          .b { color: green }
1125        "#
1126        },
1127      },
1128      "/a.css",
1129    );
1130    assert_eq!(
1131      res,
1132      indoc! { r#"
1133      @media print {
1134        .b {
1135          color: green;
1136        }
1137      }
1138
1139      .a {
1140        color: red;
1141      }
1142    "#}
1143    );
1144
1145    let res = bundle(
1146      TestProvider {
1147        map: fs! {
1148          "/a.css": r#"
1149          @import "b.css" supports(color: green);
1150          .a { color: red }
1151        "#,
1152          "/b.css": r#"
1153          .b { color: green }
1154        "#
1155        },
1156      },
1157      "/a.css",
1158    );
1159    assert_eq!(
1160      res,
1161      indoc! { r#"
1162      @supports (color: green) {
1163        .b {
1164          color: green;
1165        }
1166      }
1167
1168      .a {
1169        color: red;
1170      }
1171    "#}
1172    );
1173
1174    let res = bundle(
1175      TestProvider {
1176        map: fs! {
1177          "/a.css": r#"
1178          @import "b.css" supports(color: green) print;
1179          .a { color: red }
1180        "#,
1181          "/b.css": r#"
1182          .b { color: green }
1183        "#
1184        },
1185      },
1186      "/a.css",
1187    );
1188    assert_eq!(
1189      res,
1190      indoc! { r#"
1191      @supports (color: green) {
1192        @media print {
1193          .b {
1194            color: green;
1195          }
1196        }
1197      }
1198
1199      .a {
1200        color: red;
1201      }
1202    "#}
1203    );
1204
1205    let res = bundle(
1206      TestProvider {
1207        map: fs! {
1208          "/a.css": r#"
1209          @import "b.css" print;
1210          @import "b.css" screen;
1211          .a { color: red }
1212        "#,
1213          "/b.css": r#"
1214          .b { color: green }
1215        "#
1216        },
1217      },
1218      "/a.css",
1219    );
1220    // Parallel imports may merge these commutative conditions in either order.
1221    assert_eq!(
1222      res.replacen("@media screen, print {", "@media print, screen {", 1),
1223      indoc! { r#"
1224      @media print, screen {
1225        .b {
1226          color: green;
1227        }
1228      }
1229
1230      .a {
1231        color: red;
1232      }
1233    "#}
1234    );
1235
1236    let res = bundle(
1237      TestProvider {
1238        map: fs! {
1239          "/a.css": r#"
1240          @import "b.css" supports(color: red);
1241          @import "b.css" supports(foo: bar);
1242          .a { color: red }
1243        "#,
1244          "/b.css": r#"
1245          .b { color: green }
1246        "#
1247        },
1248      },
1249      "/a.css",
1250    );
1251    // Parallel imports may merge these commutative conditions in either order.
1252    assert_eq!(
1253      res.replacen(
1254        "@supports (foo: bar) or (color: red) {",
1255        "@supports (color: red) or (foo: bar) {",
1256        1
1257      ),
1258      indoc! { r#"
1259      @supports (color: red) or (foo: bar) {
1260        .b {
1261          color: green;
1262        }
1263      }
1264
1265      .a {
1266        color: red;
1267      }
1268    "#}
1269    );
1270
1271    let res = bundle(
1272      TestProvider {
1273        map: fs! {
1274          "/a.css": r#"
1275          @import "b.css" print;
1276          .a { color: red }
1277        "#,
1278          "/b.css": r#"
1279          @import "c.css" (color);
1280          .b { color: yellow }
1281        "#,
1282          "/c.css": r#"
1283          .c { color: green }
1284        "#
1285        },
1286      },
1287      "/a.css",
1288    );
1289    assert_eq!(
1290      res,
1291      indoc! { r#"
1292      @media print and (color) {
1293        .c {
1294          color: green;
1295        }
1296      }
1297
1298      @media print {
1299        .b {
1300          color: #ff0;
1301        }
1302      }
1303
1304      .a {
1305        color: red;
1306      }
1307    "#}
1308    );
1309
1310    let res = bundle(
1311      TestProvider {
1312        map: fs! {
1313          "/a.css": r#"
1314          @import "b.css";
1315          .a { color: red }
1316        "#,
1317          "/b.css": r#"
1318          @import "c.css";
1319        "#,
1320          "/c.css": r#"
1321          @import "a.css";
1322          .c { color: green }
1323        "#
1324        },
1325      },
1326      "/a.css",
1327    );
1328    assert_eq!(
1329      res,
1330      indoc! { r#"
1331      .c {
1332        color: green;
1333      }
1334
1335      .a {
1336        color: red;
1337      }
1338    "#}
1339    );
1340
1341    let res = bundle(
1342      TestProvider {
1343        map: fs! {
1344          "/a.css": r#"
1345          @import "b/c.css";
1346          .a { color: red }
1347        "#,
1348          "/b/c.css": r#"
1349          .b { color: green }
1350        "#
1351        },
1352      },
1353      "/a.css",
1354    );
1355    assert_eq!(
1356      res,
1357      indoc! { r#"
1358      .b {
1359        color: green;
1360      }
1361
1362      .a {
1363        color: red;
1364      }
1365    "#}
1366    );
1367
1368    let res = bundle(
1369      TestProvider {
1370        map: fs! {
1371          "/a.css": r#"
1372          @import "./b/c.css";
1373          .a { color: red }
1374        "#,
1375          "/b/c.css": r#"
1376          .b { color: green }
1377        "#
1378        },
1379      },
1380      "/a.css",
1381    );
1382    assert_eq!(
1383      res,
1384      indoc! { r#"
1385      .b {
1386        color: green;
1387      }
1388
1389      .a {
1390        color: red;
1391      }
1392    "#}
1393    );
1394
1395    let res = bundle_custom_media(
1396      TestProvider {
1397        map: fs! {
1398          "/a.css": r#"
1399          @import "media.css";
1400          @import "b.css";
1401          .a { color: red }
1402        "#,
1403          "/media.css": r#"
1404          @custom-media --foo print;
1405        "#,
1406          "/b.css": r#"
1407          @media (--foo) {
1408            .a { color: green }
1409          }
1410        "#
1411        },
1412      },
1413      "/a.css",
1414    );
1415    assert_eq!(
1416      res,
1417      indoc! { r#"
1418      @media print {
1419        .a {
1420          color: green;
1421        }
1422      }
1423
1424      .a {
1425        color: red;
1426      }
1427    "#}
1428    );
1429
1430    let res = bundle(
1431      TestProvider {
1432        map: fs! {
1433          "/a.css": r#"
1434          @import "b.css" layer(foo);
1435          .a { color: red }
1436        "#,
1437          "/b.css": r#"
1438          .b { color: green }
1439        "#
1440        },
1441      },
1442      "/a.css",
1443    );
1444    assert_eq!(
1445      res,
1446      indoc! { r#"
1447      @layer foo {
1448        .b {
1449          color: green;
1450        }
1451      }
1452
1453      .a {
1454        color: red;
1455      }
1456    "#}
1457    );
1458
1459    let res = bundle(
1460      TestProvider {
1461        map: fs! {
1462          "/a.css": r#"
1463          @import "b.css" layer;
1464          .a { color: red }
1465        "#,
1466          "/b.css": r#"
1467          .b { color: green }
1468        "#
1469        },
1470      },
1471      "/a.css",
1472    );
1473    assert_eq!(
1474      res,
1475      indoc! { r#"
1476      @layer {
1477        .b {
1478          color: green;
1479        }
1480      }
1481
1482      .a {
1483        color: red;
1484      }
1485    "#}
1486    );
1487
1488    let res = bundle(
1489      TestProvider {
1490        map: fs! {
1491          "/a.css": r#"
1492          @import "b.css" layer(foo);
1493          .a { color: red }
1494        "#,
1495          "/b.css": r#"
1496          @import "c.css" layer(bar);
1497          .b { color: green }
1498        "#,
1499          "/c.css": r#"
1500          .c { color: green }
1501        "#
1502        },
1503      },
1504      "/a.css",
1505    );
1506    assert_eq!(
1507      res,
1508      indoc! { r#"
1509      @layer foo.bar {
1510        .c {
1511          color: green;
1512        }
1513      }
1514
1515      @layer foo {
1516        .b {
1517          color: green;
1518        }
1519      }
1520
1521      .a {
1522        color: red;
1523      }
1524    "#}
1525    );
1526
1527    let res = bundle(
1528      TestProvider {
1529        map: fs! {
1530          "/a.css": r#"
1531          @import "b.css" layer(foo);
1532          @import "b.css" layer(foo);
1533        "#,
1534          "/b.css": r#"
1535          .b { color: green }
1536        "#
1537        },
1538      },
1539      "/a.css",
1540    );
1541    assert_eq!(
1542      res,
1543      indoc! { r#"
1544      @layer foo {
1545        .b {
1546          color: green;
1547        }
1548      }
1549    "#}
1550    );
1551
1552    let res = bundle(
1553      TestProvider {
1554        map: fs! {
1555          "/a.css": r#"
1556          @layer bar, foo;
1557          @import "b.css" layer(foo);
1558
1559          @layer bar {
1560            div {
1561              background: red;
1562            }
1563          }
1564        "#,
1565          "/b.css": r#"
1566          @layer qux, baz;
1567          @import "c.css" layer(baz);
1568
1569          @layer qux {
1570            div {
1571              background: green;
1572            }
1573          }
1574        "#,
1575          "/c.css": r#"
1576          div {
1577            background: yellow;
1578          }
1579        "#
1580        },
1581      },
1582      "/a.css",
1583    );
1584    assert_eq!(
1585      res,
1586      indoc! { r#"
1587      @layer bar, foo;
1588      @layer foo.qux, foo.baz;
1589
1590      @layer foo.baz {
1591        div {
1592          background: #ff0;
1593        }
1594      }
1595
1596      @layer foo {
1597        @layer qux {
1598          div {
1599            background: green;
1600          }
1601        }
1602      }
1603
1604      @layer bar {
1605        div {
1606          background: red;
1607        }
1608      }
1609    "#}
1610    );
1611
1612    // Layer order depends on @import conditions.
1613    let res = bundle(
1614      TestProvider {
1615        map: fs! {
1616          "/a.css": r#"
1617          @import "b.css" layer(bar) (min-width: 1000px);
1618
1619          @layer baz {
1620            #box { background: purple }
1621          }
1622
1623          @layer bar {
1624            #box { background: yellow }
1625          }
1626        "#,
1627          "/b.css": r#"
1628          #box { background: green }
1629        "#
1630        },
1631      },
1632      "/a.css",
1633    );
1634    assert_eq!(
1635      res,
1636      indoc! { r#"
1637      @media (width >= 1000px) {
1638        @layer bar {
1639          #box {
1640            background: green;
1641          }
1642        }
1643      }
1644
1645      @layer baz {
1646        #box {
1647          background: purple;
1648        }
1649      }
1650
1651      @layer bar {
1652        #box {
1653          background: #ff0;
1654        }
1655      }
1656    "#}
1657    );
1658
1659    let res = bundle(
1660      TestProvider {
1661        map: fs! {
1662          "/a.css": r#"
1663          @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
1664          @import './b.css';
1665        "#,
1666          "/b.css": r#"
1667          .b { color: green }
1668        "#
1669        },
1670      },
1671      "/a.css",
1672    );
1673    assert_eq!(
1674      res,
1675      indoc! { r#"
1676        @import "https://fonts.googleapis.com/css2?family=Roboto&display=swap";
1677
1678        .b {
1679          color: green;
1680        }
1681    "#}
1682    );
1683
1684    error_test(
1685      TestProvider {
1686        map: fs! {
1687          "/a.css": r#"
1688          @import './b.css';
1689          @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
1690        "#,
1691          "/b.css": r#"
1692          .b { color: green }
1693        "#
1694        },
1695      },
1696      "/a.css",
1697      Some(Box::new(|err| {
1698        assert!(matches!(err, BundleErrorKind::ExternalImportAfterBundledImport));
1699      })),
1700    );
1701
1702    error_test(
1703      TestProvider {
1704        map: fs! {
1705          "/a.css": r#"
1706          @import "b.css" layer(foo);
1707          @import "b.css" layer(bar);
1708        "#,
1709          "/b.css": r#"
1710          .b { color: red }
1711        "#
1712        },
1713      },
1714      "/a.css",
1715      Some(Box::new(|err| {
1716        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1717      })),
1718    );
1719
1720    error_test(
1721      TestProvider {
1722        map: fs! {
1723          "/a.css": r#"
1724          @import "b.css" layer;
1725          @import "b.css" layer;
1726        "#,
1727          "/b.css": r#"
1728          .b { color: red }
1729        "#
1730        },
1731      },
1732      "/a.css",
1733      Some(Box::new(|err| {
1734        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1735      })),
1736    );
1737
1738    error_test(
1739      TestProvider {
1740        map: fs! {
1741          "/a.css": r#"
1742          @import "b.css" layer;
1743          .a { color: red }
1744        "#,
1745          "/b.css": r#"
1746          @import "c.css" layer;
1747          .b { color: green }
1748        "#,
1749          "/c.css": r#"
1750          .c { color: green }
1751        "#
1752        },
1753      },
1754      "/a.css",
1755      Some(Box::new(|err| {
1756        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1757      })),
1758    );
1759
1760    error_test(
1761      TestProvider {
1762        map: fs! {
1763          "/a.css": r#"
1764          @import "b.css" layer;
1765          .a { color: red }
1766        "#,
1767          "/b.css": r#"
1768          @import "c.css" layer(foo);
1769          .b { color: green }
1770        "#,
1771          "/c.css": r#"
1772          .c { color: green }
1773        "#
1774        },
1775      },
1776      "/a.css",
1777      Some(Box::new(|err| {
1778        assert!(matches!(err, BundleErrorKind::UnsupportedLayerCombination));
1779      })),
1780    );
1781
1782    let res = bundle(
1783      TestProvider {
1784        map: fs! {
1785          "/index.css": r#"
1786          @import "a.css";
1787          @import "b.css";
1788        "#,
1789          "/a.css": r#"
1790          @import "./c.css";
1791          body { background: red; }
1792        "#,
1793          "/b.css": r#"
1794          @import "./c.css";
1795          body { color: red; }
1796        "#,
1797          "/c.css": r#"
1798          body {
1799            background: white;
1800            color: black;
1801          }
1802        "#
1803        },
1804      },
1805      "/index.css",
1806    );
1807    assert_eq!(
1808      res,
1809      indoc! { r#"
1810      body {
1811        background: red;
1812      }
1813
1814      body {
1815        background: #fff;
1816        color: #000;
1817      }
1818
1819      body {
1820        color: red;
1821      }
1822    "#}
1823    );
1824
1825    let res = bundle(
1826      TestProvider {
1827        map: fs! {
1828          "/index.css": r#"
1829          @import "a.css";
1830          @import "b.css";
1831          @import "a.css";
1832        "#,
1833          "/a.css": r#"
1834          body { background: green; }
1835        "#,
1836          "/b.css": r#"
1837          body { background: red; }
1838        "#
1839        },
1840      },
1841      "/index.css",
1842    );
1843    assert_eq!(
1844      res,
1845      indoc! { r#"
1846      body {
1847        background: red;
1848      }
1849
1850      body {
1851        background: green;
1852      }
1853    "#}
1854    );
1855
1856    let res = bundle(
1857      CustomProvider {
1858        map: fs! {
1859          "/a.css": r#"
1860            @import "foo:/b.css";
1861            .a { color: red; }
1862          "#,
1863          "/b.css": ".b { color: green; }"
1864        },
1865      },
1866      "/a.css",
1867    );
1868    assert_eq!(
1869      res,
1870      indoc! { r#"
1871        .b {
1872          color: green;
1873        }
1874
1875        .a {
1876          color: red;
1877        }
1878      "# }
1879    );
1880
1881    error_test(
1882      CustomProvider {
1883        map: fs! {
1884          "/a.css": r#"
1885            /* Forgot to prefix with `foo:`. */
1886            @import "/b.css";
1887            .a { color: red; }
1888          "#,
1889          "/b.css": ".b { color: green; }"
1890        },
1891      },
1892      "/a.css",
1893      Some(Box::new(|err| {
1894        let kind = match err {
1895          BundleErrorKind::ResolverError(ref error) => error.kind(),
1896          _ => unreachable!(),
1897        };
1898        assert!(matches!(kind, std::io::ErrorKind::NotFound));
1899        assert!(err
1900          .to_string()
1901          .contains("Failed to resolve `/b.css`, specifier does not start with `foo:`."));
1902      })),
1903    );
1904
1905    // let res = bundle(fs! {
1906    //   "/a.css": r#"
1907    //     @import "b.css" supports(color: red) (color);
1908    //     @import "b.css" supports(foo: bar) (orientation: horizontal);
1909    //     .a { color: red }
1910    //   "#,
1911    //   "/b.css": r#"
1912    //     .b { color: green }
1913    //   "#
1914    // }, "/a.css");
1915
1916    // let res = bundle(fs! {
1917    //   "/a.css": r#"
1918    //     @import "b.css" not print;
1919    //     .a { color: red }
1920    //   "#,
1921    //   "/b.css": r#"
1922    //     @import "c.css" not screen;
1923    //     .b { color: green }
1924    //   "#,
1925    //   "/c.css": r#"
1926    //     .c { color: yellow }
1927    //   "#
1928    // }, "/a.css");
1929  }
1930
1931  #[test]
1932  fn test_css_module() {
1933    macro_rules! map {
1934      { $($key:expr => $val:expr),* } => {
1935        HashMap::from([
1936          $(($key.to_owned(), $val.to_owned()),)*
1937        ])
1938      };
1939    }
1940
1941    let (code, exports) = bundle_css_module(
1942      TestProvider {
1943        map: fs! {
1944          "/a.css": r#"
1945          @import "b.css";
1946          .a { color: red }
1947        "#,
1948          "/b.css": r#"
1949          .a { color: green }
1950        "#
1951        },
1952      },
1953      "/a.css",
1954      None,
1955    );
1956    assert_eq!(
1957      code,
1958      indoc! { r#"
1959      ._9z6RGq_a {
1960        color: green;
1961      }
1962
1963      ._6lixEq_a {
1964        color: red;
1965      }
1966    "#}
1967    );
1968    assert_eq!(
1969      flatten_exports(exports),
1970      map! {
1971        "a" => "_6lixEq_a"
1972      }
1973    );
1974
1975    let (code, exports) = bundle_css_module(
1976      TestProvider {
1977        map: fs! {
1978          "/a.css": r#"
1979          .a { composes: x from './b.css'; color: red; }
1980          .b { color: yellow }
1981        "#,
1982          "/b.css": r#"
1983          .x { composes: y; background: green }
1984          .y { font: Helvetica }
1985        "#
1986        },
1987      },
1988      "/a.css",
1989      None,
1990    );
1991    assert_eq!(
1992      code,
1993      indoc! { r#"
1994      ._8Cs9ZG_x {
1995        background: green;
1996      }
1997
1998      ._8Cs9ZG_y {
1999        font: Helvetica;
2000      }
2001
2002      ._6lixEq_a {
2003        color: red;
2004      }
2005
2006      ._6lixEq_b {
2007        color: #ff0;
2008      }
2009    "#}
2010    );
2011    assert_eq!(
2012      flatten_exports(exports),
2013      map! {
2014        "a" => "_6lixEq_a _8Cs9ZG_x _8Cs9ZG_y",
2015        "b" => "_6lixEq_b"
2016      }
2017    );
2018
2019    let (code, exports) = bundle_css_module(
2020      TestProvider {
2021        map: fs! {
2022          "/a.css": r#"
2023          .a { composes: x from './b.css'; background: red; }
2024        "#,
2025          "/b.css": r#"
2026          .a { background: red }
2027        "#
2028        },
2029      },
2030      "/a.css",
2031      None,
2032    );
2033    assert_eq!(
2034      code,
2035      indoc! { r#"
2036      ._8Cs9ZG_a {
2037        background: red;
2038      }
2039
2040      ._6lixEq_a {
2041        background: red;
2042      }
2043    "#}
2044    );
2045    assert_eq!(
2046      flatten_exports(exports),
2047      map! {
2048        "a" => "_6lixEq_a"
2049      }
2050    );
2051
2052    let (code, exports) = bundle_css_module(
2053      TestProvider {
2054        map: fs! {
2055          "/a.css": r#"
2056          .a {
2057            background: var(--bg from "./b.css", var(--fallback from "./b.css"));
2058            color: rgb(255 255 255 / var(--opacity from "./b.css"));
2059            width: env(--env, var(--env-fallback from "./env.css"));
2060          }
2061        "#,
2062          "/b.css": r#"
2063          .b {
2064            --bg: red;
2065            --fallback: yellow;
2066            --opacity: 0.5;
2067          }
2068        "#,
2069          "/env.css": r#"
2070          .env {
2071            --env-fallback: 20px;
2072          }
2073        "#
2074        },
2075      },
2076      "/a.css",
2077      None,
2078    );
2079    assert_eq!(
2080      code,
2081      indoc! { r#"
2082      ._8Cs9ZG_b {
2083        --_8Cs9ZG_bg: red;
2084        --_8Cs9ZG_fallback: yellow;
2085        --_8Cs9ZG_opacity: .5;
2086      }
2087
2088      .GbJUva_env {
2089        --GbJUva_env-fallback: 20px;
2090      }
2091
2092      ._6lixEq_a {
2093        background: var(--_8Cs9ZG_bg, var(--_8Cs9ZG_fallback));
2094        color: rgb(255 255 255 / var(--_8Cs9ZG_opacity));
2095        width: env(--_6lixEq_env, var(--GbJUva_env-fallback));
2096      }
2097    "#}
2098    );
2099    assert_eq!(
2100      flatten_exports(exports),
2101      map! {
2102        "a" => "_6lixEq_a",
2103        "--env" => "--_6lixEq_env"
2104      }
2105    );
2106
2107    // Hashes are stable between project roots.
2108    let expected = indoc! { r#"
2109    .dyGcAa_b {
2110      background: #ff0;
2111    }
2112
2113    .CK9avG_a {
2114      background: #fff;
2115    }
2116  "#};
2117
2118    let (code, _) = bundle_css_module(
2119      TestProvider {
2120        map: fs! {
2121          "/foo/bar/a.css": r#"
2122        @import "b.css";
2123        .a {
2124          background: white;
2125        }
2126      "#,
2127          "/foo/bar/b.css": r#"
2128        .b {
2129          background: yellow;
2130        }
2131      "#
2132        },
2133      },
2134      "/foo/bar/a.css",
2135      Some("/foo/bar"),
2136    );
2137    assert_eq!(code, expected);
2138
2139    let (code, _) = bundle_css_module(
2140      TestProvider {
2141        map: fs! {
2142          "/x/y/z/a.css": r#"
2143      @import "b.css";
2144      .a {
2145        background: white;
2146      }
2147    "#,
2148          "/x/y/z/b.css": r#"
2149      .b {
2150        background: yellow;
2151      }
2152    "#
2153        },
2154      },
2155      "/x/y/z/a.css",
2156      Some("/x/y/z"),
2157    );
2158    assert_eq!(code, expected);
2159
2160    let (code, _) = bundle_css_module_with_pattern(
2161      TestProvider {
2162        map: fs! {
2163          "/a.css": r#"
2164          @import "b.css";
2165          .a { color: red }
2166        "#,
2167          "/b.css": r#"
2168          .a { color: green }
2169        "#
2170        },
2171      },
2172      "/a.css",
2173      None,
2174      "[content-hash]-[local]",
2175    );
2176    assert_eq!(
2177      code,
2178      indoc! { r#"
2179      .do5n2W-a {
2180        color: green;
2181      }
2182
2183      .pP97eq-a {
2184        color: red;
2185      }
2186    "#}
2187    );
2188  }
2189
2190  #[test]
2191  #[cfg(feature = "sourcemap")]
2192  fn test_source_map() {
2193    let source = r#".imported {
2194      content: "yay, file support!";
2195    }
2196
2197    .selector {
2198      margin: 1em;
2199      background-color: #f60;
2200    }
2201
2202    .selector .nested {
2203      margin: 0.5em;
2204    }
2205
2206    /*# sourceMappingURL=data:application/json;base64,ewoJInZlcnNpb24iOiAzLAoJInNvdXJjZVJvb3QiOiAicm9vdCIsCgkiZmlsZSI6ICJzdGRvdXQiLAoJInNvdXJjZXMiOiBbCgkJInN0ZGluIiwKCQkic2Fzcy9fdmFyaWFibGVzLnNjc3MiLAoJCSJzYXNzL19kZW1vLnNjc3MiCgldLAoJInNvdXJjZXNDb250ZW50IjogWwoJCSJAaW1wb3J0IFwiX3ZhcmlhYmxlc1wiO1xuQGltcG9ydCBcIl9kZW1vXCI7XG5cbi5zZWxlY3RvciB7XG4gIG1hcmdpbjogJHNpemU7XG4gIGJhY2tncm91bmQtY29sb3I6ICRicmFuZENvbG9yO1xuXG4gIC5uZXN0ZWQge1xuICAgIG1hcmdpbjogJHNpemUgLyAyO1xuICB9XG59IiwKCQkiJGJyYW5kQ29sb3I6ICNmNjA7XG4kc2l6ZTogMWVtOyIsCgkJIi5pbXBvcnRlZCB7XG4gIGNvbnRlbnQ6IFwieWF5LCBmaWxlIHN1cHBvcnQhXCI7XG59IgoJXSwKCSJtYXBwaW5ncyI6ICJBRUFBLFNBQVMsQ0FBQztFQUNSLE9BQU8sRUFBRSxvQkFBcUI7Q0FDL0I7O0FGQ0QsU0FBUyxDQUFDO0VBQ1IsTUFBTSxFQ0hELEdBQUc7RURJUixnQkFBZ0IsRUNMTCxJQUFJO0NEVWhCOztBQVBELFNBQVMsQ0FJUCxPQUFPLENBQUM7RUFDTixNQUFNLEVDUEgsS0FBRztDRFFQIiwKCSJuYW1lcyI6IFtdCn0= */"#;
2207
2208    let fs = TestProvider {
2209      map: fs! {
2210        "/a.css": r#"
2211        @import "/b.css";
2212        .a { color: red; }
2213      "#,
2214        "/b.css": source
2215      },
2216    };
2217
2218    let mut sm = parcel_sourcemap::SourceMap::new("/");
2219    let mut bundler = Bundler::new(&fs, Some(&mut sm), ParserOptions::default());
2220    let mut stylesheet = bundler.bundle(Path::new("/a.css")).unwrap();
2221    stylesheet.minify(MinifyOptions::default()).unwrap();
2222    stylesheet
2223      .to_css(
2224        PrinterOptions {
2225          minify: true,
2226          ..PrinterOptions::default()
2227        },
2228        Some(&mut sm),
2229      )
2230      .unwrap();
2231    let map = sm.to_json(None).unwrap();
2232    assert_eq!(
2233      map,
2234      r#"{"version":3,"sourceRoot":null,"mappings":"ACAA,uCCGA,2CAAA,8BFDQ","sources":["a.css","sass/_demo.scss","stdin"],"sourcesContent":["\n        @import \"/b.css\";\n        .a { color: red; }\n      ",".imported {\n  content: \"yay, file support!\";\n}","@import \"_variables\";\n@import \"_demo\";\n\n.selector {\n  margin: $size;\n  background-color: $brandColor;\n\n  .nested {\n    margin: $size / 2;\n  }\n}"],"names":[]}"#
2235    );
2236  }
2237
2238  #[test]
2239  fn test_license_comments() {
2240    let res = bundle(
2241      TestProvider {
2242        map: fs! {
2243          "/a.css": r#"
2244          /*! Copyright 2023 Someone awesome */
2245          @import "b.css";
2246          .a { color: red }
2247        "#,
2248          "/b.css": r#"
2249          /*! Copyright 2023 Someone else */
2250          .b { color: green }
2251        "#
2252        },
2253      },
2254      "/a.css",
2255    );
2256    assert_eq!(
2257      res,
2258      indoc! { r#"
2259      /*! Copyright 2023 Someone awesome */
2260      /*! Copyright 2023 Someone else */
2261      .b {
2262        color: green;
2263      }
2264
2265      .a {
2266        color: red;
2267      }
2268    "#}
2269    );
2270  }
2271}