1#![deny(unsafe_code)]
7
8use crate::context::{DeclarationContext, PropertyHandlerContext};
9use crate::css_modules::{hash, CssModule, CssModuleExports, CssModuleReferences};
10use crate::declaration::{DeclarationBlock, DeclarationHandler};
11use crate::dependencies::Dependency;
12use crate::error::{Error, ErrorLocation, MinifyErrorKind, ParserError, PrinterError, PrinterErrorKind};
13use crate::parser::{DefaultAtRule, DefaultAtRuleParser, TopLevelRuleParser};
14use crate::printer::Printer;
15#[cfg(feature = "custom_sourcemap")]
16use crate::printer::SourceMap;
17use crate::rules::{CssRule, CssRuleList, MinifyContext};
18use crate::targets::{should_compile, Targets, TargetsWithSupportsScope};
19use crate::traits::{AtRuleParser, ToCss};
20use crate::values::string::CowArcStr;
21#[cfg(feature = "visitor")]
22use crate::visitor::{Visit, VisitTypes, Visitor};
23use cssparser::{Parser, ParserInput, StyleSheetParser};
24use std::collections::{HashMap, HashSet};
25use std::fmt::Write;
26
27pub use crate::parser::{ParserFlags, ParserOptions};
28pub use crate::printer::PrinterOptions;
29pub use crate::printer::PseudoClasses;
30
31#[derive(Debug, Clone)]
65#[cfg_attr(
66 feature = "serde",
67 derive(serde::Serialize, serde::Deserialize),
68 serde(rename_all = "camelCase")
69)]
70#[cfg_attr(
71 feature = "jsonschema",
72 derive(schemars::JsonSchema),
73 schemars(rename = "StyleSheet", bound = "T: schemars::JsonSchema")
74)]
75#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
76pub struct StyleSheet<'i, T = DefaultAtRule> {
77 #[cfg_attr(feature = "serde", serde(borrow))]
79 pub rules: CssRuleList<'i, T>,
80 pub sources: Vec<String>,
83 pub source_map_urls: Vec<Option<String>>,
85 #[cfg(feature = "custom_sourcemap")]
87 #[cfg_attr(feature = "serde", serde(skip))]
88 pub(crate) source_map_source_indices: Vec<Option<u32>>,
89 pub license_comments: Vec<CowArcStr<'i>>,
91 #[cfg_attr(feature = "serde", serde(skip))]
94 pub(crate) content_hashes: Option<Vec<String>>,
95 #[cfg_attr(feature = "serde", serde(skip))]
96 options: ParserOptions<'i>,
98}
99
100#[derive(Default)]
103pub struct MinifyOptions {
104 pub targets: Targets,
106 pub unused_symbols: HashSet<String>,
109}
110
111#[derive(Debug)]
114pub struct ToCssResult {
115 pub code: String,
117 pub exports: Option<CssModuleExports>,
120 pub references: Option<CssModuleReferences>,
123 pub dependencies: Option<Vec<Dependency>>,
126}
127
128impl<'i, 'o> StyleSheet<'i, DefaultAtRule> {
129 pub fn parse(code: &'i str, options: ParserOptions<'i>) -> Result<Self, Error<ParserError<'i>>> {
131 Self::parse_with(code, options, &mut DefaultAtRuleParser)
132 }
133}
134
135impl<'i, T> StyleSheet<'i, T>
136where
137 T: ToCss + Clone,
138{
139 pub fn new(sources: Vec<String>, rules: CssRuleList<'i, T>, options: ParserOptions<'i>) -> StyleSheet<'i, T> {
141 StyleSheet {
142 sources,
143 source_map_urls: Vec::new(),
144 #[cfg(feature = "custom_sourcemap")]
145 source_map_source_indices: Vec::new(),
146 license_comments: Vec::new(),
147 content_hashes: None,
148 rules,
149 options,
150 }
151 }
152
153 pub fn parse_with<P: AtRuleParser<'i, AtRule = T>>(
155 code: &'i str,
156 mut options: ParserOptions<'i>,
157 at_rule_parser: &mut P,
158 ) -> Result<Self, Error<ParserError<'i>>> {
159 let mut input = ParserInput::new(&code);
160 let mut parser = Parser::new(&mut input);
161 let mut license_comments = Vec::new();
162
163 let mut content_hashes = None;
164 if let Some(config) = &options.css_modules {
165 if config.pattern.has_content_hash() {
166 content_hashes = Some(vec![hash(
167 &code,
168 matches!(config.pattern.segments[0], crate::css_modules::Segment::ContentHash),
169 )]);
170 }
171 }
172
173 let mut state = parser.state();
174 while let Ok(token) = parser.next_including_whitespace_and_comments() {
175 match token {
176 cssparser::Token::WhiteSpace(..) => {}
177 cssparser::Token::Comment(comment) if comment.starts_with('!') => {
178 license_comments.push((*comment).into());
179 }
180 cssparser::Token::Comment(comment) if comment.contains("cssmodules-pure-no-check") => {
181 if let Some(css_modules) = &mut options.css_modules {
182 css_modules.pure = false;
183 }
184 }
185 _ => break,
186 }
187 state = parser.state();
188 }
189 parser.reset(&state);
190
191 let mut rules = CssRuleList(vec![]);
192 let mut rule_parser = TopLevelRuleParser::new(&mut options, at_rule_parser, &mut rules);
193 let mut rule_list_parser = StyleSheetParser::new(&mut parser, &mut rule_parser);
194
195 while let Some(rule) = rule_list_parser.next() {
196 match rule {
197 Ok(()) => {}
198 Err((e, _)) => {
199 let options = &mut rule_list_parser.parser.options;
200 if options.error_recovery {
201 options.warn(e);
202 continue;
203 }
204
205 return Err(Error::from(e, options.filename.clone()));
206 }
207 }
208 }
209
210 Ok(StyleSheet {
211 sources: vec![options.filename.clone()],
212 source_map_urls: vec![parser.current_source_map_url().map(|s| s.to_owned())],
213 #[cfg(feature = "custom_sourcemap")]
214 source_map_source_indices: Vec::new(),
215 content_hashes,
216 rules,
217 license_comments,
218 options,
219 })
220 }
221
222 pub fn source_map_url(&self, source_index: usize) -> Option<&String> {
224 self.source_map_urls.get(source_index)?.as_ref()
225 }
226
227 #[cfg(feature = "custom_sourcemap")]
229 pub fn source_map<S: SourceMap>(&self, source_index: usize) -> Option<S> {
230 S::from_data_url("/", self.source_map_url(source_index)?)
231 }
232
233 pub fn minify(&mut self, options: MinifyOptions) -> Result<(), Error<MinifyErrorKind>> {
235 let context = PropertyHandlerContext::new(options.targets, &options.unused_symbols);
236 let mut handler = DeclarationHandler::default();
237 let mut important_handler = DeclarationHandler::default();
238
239 let custom_media = if self.options.flags.contains(ParserFlags::CUSTOM_MEDIA)
242 && should_compile!(options.targets, CustomMediaQueries)
243 {
244 let mut custom_media = HashMap::new();
245 for rule in &self.rules.0 {
246 if let CssRule::CustomMedia(rule) = rule {
247 custom_media.insert(rule.name.0.clone(), rule.clone());
248 }
249 }
250 Some(custom_media)
251 } else {
252 None
253 };
254
255 let mut ctx = MinifyContext {
256 targets: TargetsWithSupportsScope::new(options.targets),
257 handler: &mut handler,
258 important_handler: &mut important_handler,
259 handler_context: context,
260 unused_symbols: &options.unused_symbols,
261 custom_media,
262 css_modules: self.options.css_modules.is_some(),
263 pure_css_modules: self.options.css_modules.as_ref().map(|c| c.pure).unwrap_or_default(),
264 };
265
266 self.rules.minify(&mut ctx, false).map_err(|e| Error {
267 kind: e.kind,
268 loc: Some(ErrorLocation::new(
269 e.loc,
270 self.sources[e.loc.source_index as usize].clone(),
271 )),
272 })?;
273
274 Ok(())
275 }
276
277 pub fn to_css<'a, #[cfg(feature = "custom_sourcemap")] S: SourceMap>(
279 &self,
280 #[cfg(feature = "custom_sourcemap")] options: PrinterOptions<'a, S>,
281 #[cfg(not(feature = "custom_sourcemap"))] options: PrinterOptions<'a>,
282 ) -> Result<ToCssResult, Error<PrinterErrorKind>> {
283 let mut dest = String::with_capacity(1);
285 let project_root = options.project_root.clone();
286 let mut printer = Printer::new(&mut dest, options);
287 printer.sources = Some(&self.sources);
288
289 #[cfg(feature = "custom_sourcemap")]
290 if printer.source_map.is_some() {
291 printer.source_maps = self.sources.iter().enumerate().map(|(i, _)| self.source_map::<S>(i)).collect();
292 printer.source_map_source_indices = &self.source_map_source_indices;
293 }
294
295 for comment in &self.license_comments {
296 printer.write_str("/*")?;
297 printer.write_str(comment)?;
298 printer.write_str("*/\n")?;
299 }
300
301 if let Some(config) = &self.options.css_modules {
302 let mut references = CssModuleReferences::new();
303 printer.state.css_module = Some(CssModule::new(
304 config,
305 &self.sources,
306 project_root,
307 &mut references,
308 &self.content_hashes,
309 ));
310
311 self.rules.to_css(&mut printer)?;
312 printer.newline()?;
313
314 Ok(ToCssResult {
315 dependencies: printer.state.dependencies,
316 exports: Some(std::mem::take(
317 &mut printer.state.css_module.unwrap().exports_by_source_index[0],
318 )),
319 code: dest,
320 references: Some(references),
321 })
322 } else {
323 self.rules.to_css(&mut printer)?;
324 printer.newline()?;
325
326 Ok(ToCssResult {
327 dependencies: printer.state.dependencies,
328 code: dest,
329 exports: None,
330 references: None,
331 })
332 }
333 }
334}
335
336#[cfg(feature = "visitor")]
337#[cfg_attr(docsrs, doc(cfg(feature = "visitor")))]
338impl<'i, T, V> Visit<'i, T, V> for StyleSheet<'i, T>
339where
340 T: Visit<'i, T, V>,
341 V: ?Sized + Visitor<'i, T>,
342{
343 const CHILD_TYPES: VisitTypes = VisitTypes::all();
344
345 fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
346 visitor.visit_stylesheet(self)
347 }
348
349 fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
350 self.rules.visit(visitor)
351 }
352}
353
354#[cfg_attr(feature = "visitor", derive(Visit))]
380#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
381pub struct StyleAttribute<'i> {
382 pub declarations: DeclarationBlock<'i>,
384 #[cfg_attr(feature = "visitor", skip_visit)]
385 sources: Vec<String>,
386}
387
388impl<'i> StyleAttribute<'i> {
389 pub fn parse(code: &'i str, options: ParserOptions<'i>) -> Result<StyleAttribute<'i>, Error<ParserError<'i>>> {
391 let mut input = ParserInput::new(&code);
392 let mut parser = Parser::new(&mut input);
393 Ok(StyleAttribute {
394 declarations: DeclarationBlock::parse(&mut parser, &options).map_err(|e| Error::from(e, "".into()))?,
395 sources: vec![options.filename],
396 })
397 }
398
399 pub fn minify(&mut self, options: MinifyOptions) {
401 let mut context = PropertyHandlerContext::new(options.targets, &options.unused_symbols);
402 let mut handler = DeclarationHandler::default();
403 let mut important_handler = DeclarationHandler::default();
404 context.context = DeclarationContext::StyleAttribute;
405 self.declarations.minify(&mut handler, &mut important_handler, &mut context);
406 }
407
408 pub fn to_css(&self, options: PrinterOptions) -> Result<ToCssResult, PrinterError> {
410 let mut dest = String::with_capacity(1);
412 let mut printer = Printer::new(&mut dest, options);
413 printer.sources = Some(&self.sources);
414
415 self.declarations.to_css(&mut printer)?;
416
417 Ok(ToCssResult {
418 dependencies: printer.take_dependencies(),
419 code: dest,
420 exports: None,
421 references: None,
422 })
423 }
424}