Skip to main content

mini_static/
minify.rs

1use std::path::Path;
2
3use bytes::Bytes;
4
5use crate::reload::ChangeType;
6
7/// Why [`minify`] could not produce output for the given bytes.
8#[derive(Debug)]
9pub enum MinifyError {
10    /// The bytes were not valid UTF-8 (both minifiers work on text, not arbitrary bytes).
11    NotUtf8,
12    /// The CSS minifier rejected the input.
13    Css(String),
14    /// The JS minifier rejected the input.
15    Js(String),
16    /// Reading the source file failed while minifying it on demand.
17    Io(std::io::Error),
18}
19
20impl std::fmt::Display for MinifyError {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        match self {
23            MinifyError::NotUtf8 => write!(f, "input is not valid UTF-8"),
24            MinifyError::Css(msg) => write!(f, "CSS minification failed: {msg}"),
25            MinifyError::Js(msg) => write!(f, "JS minification failed: {msg}"),
26            MinifyError::Io(e) => write!(f, "reading source file failed: {e}"),
27        }
28    }
29}
30
31impl std::error::Error for MinifyError {}
32
33/// Minify `bytes` according to `change_type`'s file kind.
34///
35/// `Css` is minified with `lightningcss`, `Script` with `minify-js`. `Html` and `Other`
36/// pass through unchanged — this function is never called for those kinds (see
37/// `Server::with_minify`), but passthrough is the correct behavior if it ever is.
38///
39/// # Errors
40///
41/// Returns `Err` if `bytes` isn't valid UTF-8, or if the relevant minifier rejects the
42/// input as malformed. Never panics — malformed CSS/JS on disk is a real possibility
43/// (a hand-edited file, a build tool's bug), not a state to unwrap through.
44pub fn minify(bytes: &[u8], change_type: ChangeType) -> Result<Bytes, MinifyError> {
45    match change_type {
46        ChangeType::Css => minify_css(bytes),
47        ChangeType::Script => minify_js(bytes),
48        ChangeType::Html | ChangeType::Other => Ok(Bytes::copy_from_slice(bytes)),
49    }
50}
51
52pub(crate) fn minify_css(bytes: &[u8]) -> Result<Bytes, MinifyError> {
53    let source = std::str::from_utf8(bytes).map_err(|_| MinifyError::NotUtf8)?;
54
55    let mut stylesheet = lightningcss::stylesheet::StyleSheet::parse(
56        source,
57        lightningcss::stylesheet::ParserOptions::default(),
58    )
59    .map_err(|e| MinifyError::Css(e.to_string()))?;
60
61    stylesheet
62        .minify(lightningcss::stylesheet::MinifyOptions::default())
63        .map_err(|e| MinifyError::Css(e.to_string()))?;
64
65    let result = stylesheet
66        .to_css(lightningcss::printer::PrinterOptions {
67            minify: true,
68            ..Default::default()
69        })
70        .map_err(|e| MinifyError::Css(e.to_string()))?;
71
72    Ok(Bytes::from(result.code.into_bytes()))
73}
74
75fn minify_js(bytes: &[u8]) -> Result<Bytes, MinifyError> {
76    std::str::from_utf8(bytes).map_err(|_| MinifyError::NotUtf8)?;
77    let session = minify_js::Session::new();
78    let mut output = Vec::new();
79    minify_js::minify(&session, minify_js::TopLevelMode::Global, bytes, &mut output)
80        .map_err(|e| MinifyError::Js(format!("{:?}", e)))?;
81    Ok(Bytes::from(output))
82}
83
84/// True if `path`'s filename indicates it's already minified (`*.min.css` /
85/// `*.min.js`). Such files should be served as-is — running a minifier on
86/// already-minified input is wasted work at best and a correctness risk at worst (a
87/// minifier is not guaranteed to be idempotent on its own output).
88pub(crate) fn is_already_minified(path: &Path) -> bool {
89    path.file_name()
90        .and_then(|name| name.to_str())
91        .is_some_and(|name| name.ends_with(".min.css") || name.ends_with(".min.js"))
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn minifies_css_dropping_whitespace_and_comments() {
100        let source = b"body {\n  /* comment */\n  color: red;\n}\n";
101        let minified = minify(source, ChangeType::Css).expect("valid CSS should minify");
102        let minified = std::str::from_utf8(&minified).unwrap();
103
104        assert!(minified.len() < source.len(), "minified output should be shorter");
105        assert!(!minified.contains("comment"), "comment should be dropped");
106        assert!(minified.contains("color:red") || minified.contains("color: red"), "rule should survive: {minified}");
107    }
108
109    #[test]
110    fn rejects_malformed_css() {
111        // Note: an unterminated declaration (e.g. `"body { color: "`) is NOT malformed
112        // under lightningcss — its spec-compliant EOF recovery closes it to
113        // `body{color: }` rather than erroring, unlike the previous minifier
114        // (css-minify), whose stricter — and, per the bug this module's history fixed,
115        // overly fragile — parser rejected it. Unbalanced braces is a case that
116        // genuinely has no valid recovery.
117        let result = minify(b"body {{{{ color: red; }", ChangeType::Css);
118        assert!(result.is_err(), "unbalanced braces should be rejected, not silently passed through");
119    }
120
121    #[test]
122    fn minifies_calc_with_nested_var() {
123        let source = b"body { top: calc(var(--half) * -1); }";
124        let minified = minify(source, ChangeType::Css).expect("calc(var()) must minify, not error");
125        let minified = std::str::from_utf8(&minified).unwrap();
126        assert!(minified.contains("calc(var(--half)"), "nested var() inside calc() must survive: {minified}");
127    }
128
129    #[test]
130    fn minifies_nested_gradient_with_rgba_and_var() {
131        let source = b".x { background: repeating-linear-gradient(45deg, rgba(var(--r), var(--g), var(--b), 0.5) 0px, rgba(0,0,0,0.2) 10px, var(--fallback) 20px); }";
132        let minified = minify(source, ChangeType::Css)
133            .expect("multi-layer nested function calls in gradients must minify, not error");
134        let minified = std::str::from_utf8(&minified).unwrap();
135        assert!(minified.contains("repeating-linear-gradient"), "gradient must survive: {minified}");
136        assert!(
137            minified.contains("var(--r)") && minified.contains("var(--fallback)"),
138            "nested var()s must survive: {minified}"
139        );
140    }
141
142    #[test]
143    fn minifies_has_with_nested_pseudo_class() {
144        let source = b"table:has(~ tr:not([hidden])) { color: blue; }";
145        let minified = minify(source, ChangeType::Css).expect(":has() with nested pseudo-class must minify, not error");
146        let minified = std::str::from_utf8(&minified).unwrap();
147        assert!(
148            minified.contains(":has(~tr:not([hidden]))"),
149            ":has() selector must round-trip uncorrupted: {minified}"
150        );
151    }
152
153    #[test]
154    fn rejects_malformed_js() {
155        let result = minify(b"function( {{{ !!!", ChangeType::Script);
156        assert!(result.is_err(), "malformed JS should be rejected, not silently passed through");
157    }
158
159    #[test]
160    fn html_and_other_pass_through_unchanged() {
161        let html = b"<html><body>hi</body></html>";
162        assert_eq!(&minify(html, ChangeType::Html).unwrap()[..], html);
163
164        let other = b"arbitrary binary-ish content";
165        assert_eq!(&minify(other, ChangeType::Other).unwrap()[..], other);
166    }
167
168    #[test]
169    fn rejects_non_utf8_input() {
170        let invalid = [0xff, 0xfe, 0xfd];
171        assert!(matches!(minify(&invalid, ChangeType::Css), Err(MinifyError::NotUtf8)));
172        assert!(matches!(minify(&invalid, ChangeType::Script), Err(MinifyError::NotUtf8)));
173    }
174
175    #[test]
176    fn detects_already_minified_filenames() {
177        assert!(is_already_minified(Path::new("app.min.js")));
178        assert!(is_already_minified(Path::new("/a/b/app.min.css")));
179        assert!(!is_already_minified(Path::new("app.js")), "plain .js is not already minified");
180        assert!(!is_already_minified(Path::new("app.css")), "plain .css is not already minified");
181        assert!(
182            !is_already_minified(Path::new("app.minified.js")),
183            "must match the exact .min.js/.min.css suffix, not a loose 'min' substring"
184        );
185    }
186}