use std::{ collections::{HashMap, HashSet}, sync::Arc, }; use lightningcss::{ css_modules::{CssModuleExports, CssModuleReference}, error::Error, stylesheet::{StyleAttribute, StyleSheet}, }; use parcel_core::*; pub mod bundling; mod packager; mod transformer; pub use transformer::{CssTransformer, StyleAttrTransformer}; use crate::transformer::PseudoClasses; #[derive(Debug)] pub struct CssContent { source_size: usize, stylesheet: StyleSheet<'static>, order_flags: bundling::OrderFlags, exports: CssModuleExports, references: HashMap, pseudo_classes: Option>, } impl Content for CssContent { fn estimate_size(&self) -> Result { Ok(self.source_size) } fn read(&self) -> Result, Diagnostic> { todo!() } fn bundle_dependencies(&self, bundle_graph: &BundleGraph, bundle: &Bundle) -> Vec { // Cross-bundle @imports and url()s embed the target's URL or inline content, and referenced // CSS bundles may be @imported (see `packager::imports_references`). let mut dependencies: Vec = bundle_graph.bundle_dependency_targets(bundle).collect(); if packager::imports_references(bundle_graph, bundle) { dependencies.extend( bundle .referenced_bundles .iter() .copied() .filter(|&index| bundle_graph.bundles[index].ty == AssetType::Css), ); } dependencies } fn package( &self, bundle_graph: &BundleGraph, bundle: &Bundle, get_inline_bundle_content: &dyn Fn(usize) -> Result, DiagnosticList>, options: &ParcelOptions, ) -> Result, DiagnosticList> { self.package_impl(bundle_graph, bundle, get_inline_bundle_content, options) } fn ty(&self) -> ContentType { parcel_core::content_type!("CssContent") } } /// The assets whose content `resolve_css_module_export` may read for `asset_index`: the CSS /// module itself, and the modules its classes compose from, transitively. pub fn css_module_export_sources( asset_graph: &AssetGraph, asset_index: AssetIndex, ) -> Vec { let mut sources = vec![asset_index]; let mut index = 0; while let Some(&asset_index) = sources.get(index) { index += 1; for dep in &asset_graph.asset(asset_index).dependencies { if dep.specifier_type == SpecifierType::Esm && let Some((resolved, _)) = asset_graph.resolved_asset(dep) && !sources.contains(&resolved) { sources.push(resolved); } } } sources } pub fn resolve_css_module_export( asset_graph: &AssetGraph, asset_index: AssetIndex, name: &str, ) -> Option { resolve_css_module_export_inner(asset_graph, asset_index, name, &mut HashSet::new()) } fn resolve_css_module_export_inner<'a>( asset_graph: &'a AssetGraph, asset_index: AssetIndex, name: &'a str, seen: &mut HashSet<(AssetIndex, &'a str)>, ) -> Option { let key = (asset_index, name); if !seen.insert(key) { return None; } let asset = &asset_graph.asset(asset_index); let Some(content) = asset.content.downcast_ref::() else { seen.remove(&key); return None; }; let res = if let Some(export) = content.exports.get(name) { let mut res = export.name.clone(); for composes in &export.composes { res.push(' '); match composes { CssModuleReference::Global { name } => { res.push_str(name); } CssModuleReference::Local { name } => { if let Some((local_name, _)) = content .exports .iter() .find(|(_, export)| export.name == name.as_str()) && let Some(resolved) = resolve_css_module_export_inner(asset_graph, asset_index, local_name, seen) { res.push_str(&resolved); } else { res.push_str(name); } } CssModuleReference::Dependency { name, specifier } => { if let Some(dep) = asset .dependencies .iter() .find(|d| &*d.specifier == &*specifier && d.specifier_type == SpecifierType::Esm) { if let Some((resolved, _)) = asset_graph.resolved_asset(dep) { if let Some(resolved) = resolve_css_module_export_inner(asset_graph, resolved, name, seen) { res.push_str(&resolved); } } } } } } Some(res) } else { None }; seen.remove(&key); res } fn convert_version(c: Version) -> u32 { ((c.major() as u32) << 16) | ((c.minor() as u32) << 8) } fn convert_error(url: Option, err: Error) -> Diagnostic { Diagnostic { origin: Some("@parcel/transformer-css".into()), message: err.to_string(), code_frames: if let Some(loc) = err.loc { vec![CodeFrame { code: None, code_highlights: vec![CodeHighlight { message: None, start: Location { line: loc.line, column: loc.column, }, end: Location { line: loc.line, column: loc.column, }, }], language: None, url, }] } else { Vec::new() }, hints: Vec::new(), documentation_url: None, severity: DiagnosticSeverity::Error, } } struct StyleAttrContent { source_size: usize, attr: StyleAttribute<'static>, } impl std::fmt::Debug for StyleAttrContent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "todo") } } impl Content for StyleAttrContent { fn estimate_size(&self) -> Result { Ok(self.source_size) } fn read(&self) -> Result, Diagnostic> { todo!() } fn bundle_dependencies(&self, bundle_graph: &BundleGraph, bundle: &Bundle) -> Vec { // url()s embed the target's URL or inline content. bundle_graph.bundle_dependency_targets(bundle).collect() } fn package( &self, bundle_graph: &BundleGraph, bundle: &Bundle, get_inline_bundle_content: &dyn Fn(usize) -> Result, DiagnosticList>, options: &ParcelOptions, ) -> Result, DiagnosticList> { self.package_impl(bundle_graph, bundle, get_inline_bundle_content, options) } fn ty(&self) -> ContentType { parcel_core::content_type!("StyleAttrContent") } } /// Converts a stylesheet filename (a `project://` stable id) to the project-relative /// path used for sources in generated maps. pub(crate) fn map_source(source: &str) -> &str { match source.strip_prefix("project:///") { Some(path) => path.split('?').next().unwrap_or(path), None => source.strip_prefix("file://").unwrap_or(source), } }