Unverified Commit 891adaa6 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Improve CSS parse error recovery and reporting (#90025)

## What?

This PR improves CSS parsing error handling in Turbopack by making parse errors recoverable instead of fatal.

1. **Extracting CSS parsing logic** into a new `parse_css_stylesheet` function that handles both parsing and CSS module validation in one place
2. **Fixing error recovery** when CSS minification fails — instead of immediately returning an unparsable result, the code now re-parses the original CSS to recover valid styles
3. **Improving error reporting** by renaming variables for clarity (`source` → `issue_source`) and ensuring errors are properly emitted before attempting recovery
4. **Adding comprehensive tests** for CSS parse error scenarios with both snapshot tests and e2e tests

The snapshot test fixture exercises several CSS features to confirm they survive error recovery:
- Basic selectors (`.before`, `.after`) — valid rules are preserved when surrounded by invalid ones
- `::highlight(highlight-test)` — CSS Custom Highlight API pseudo-element
- `scroll-marker-group`, `::scroll-marker`, `::scroll-marker:target-current` — CSS scroll marker pseudo-elements (new spec)
- `oklch()` color values — converted to `#rrggbbaa` + `lab()` fallbacks for broader browser compatibility

## Why?

Previously, when CSS minification encountered an error, the entire stylesheet would be marked as unparsable, losing any valid CSS that could have been recovered. This meant `turbopackIgnoreIssue` could not suppress the errors since the module produced no output regardless.

Now, when lightningcss recovers from parse errors (collecting them as warnings), issues are still emitted but processing continues with the recovered stylesheet. Only truly fatal parse errors (where `StyleSheet::parse` returns `Err`) remain non-recoverable.

The refactoring also consolidates CSS validation logic into a single function, reducing code duplication and making the error handling flow clearer.

## How?

- Created `parse_css_stylesheet()` function that wraps `StyleSheet::parse()` and applies CSS module validation
- Modified error handling in `process_content()` to call the new function and recover from minification errors by re-parsing
- Changed early returns to error emission followed by recovery attempts
- Added test fixtures and e2e tests to verify CSS parse error recovery works correctly
- Added snapshot tests showing expected output when CSS contains parse errors (valid rules are preserved, invalid ones are skipped)
- Skipped CSS parse error recovery e2e tests for webpack (webpack has its own CSS pipeline)

## Test Plan

- Added e2e tests in `css-parse-error-recovery.test.ts` that verify:
  - Pages with CSS parse errors still render when using `turbopackIgnoreIssue` config
  - Parse errors are properly reported in CLI output
- Added snapshot tests showing CSS output with parse errors, including modern CSS features (`::highlight`, `scroll-marker-group`, `oklch()` color conversion)
- Existing CSS tests continue to pass
parent 66bbcb58
...@@ -74,6 +74,8 @@ test/integration/typescript-app-type-declarations/next-env.strictRouteTypes.d.ts ...@@ -74,6 +74,8 @@ test/integration/typescript-app-type-declarations/next-env.strictRouteTypes.d.ts
/turbopack/crates/turbopack-tests/tests/execution/turbopack/exports/invalid-export-parse-error/input/invalid-export/broken.js /turbopack/crates/turbopack-tests/tests/execution/turbopack/exports/invalid-export-parse-error/input/invalid-export/broken.js
/turbopack/crates/turbopack-tests/tests/execution/turbopack/**/not-compiled.js /turbopack/crates/turbopack-tests/tests/execution/turbopack/**/not-compiled.js
/turbopack/crates/turbopack-tests/tests/snapshot/basic/ts-parse-error/input/other.ts /turbopack/crates/turbopack-tests/tests/snapshot/basic/ts-parse-error/input/other.ts
/turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css
/test/development/app-dir/css-parse-error-recovery/app/css-error/style.css
/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/mod.cjs /turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/mod.cjs
/turbopack/crates/turbopack-tests/tests/snapshot/source_maps/* /turbopack/crates/turbopack-tests/tests/snapshot/source_maps/*
/turbopack/crates/turbopack-tests/tests/**/output* /turbopack/crates/turbopack-tests/tests/**/output*
......
import './style.css'
export default function Page() {
return <p className="before">css error page</p>
}
.before {
color: red;
}
.invalid {
color
}
.after {
color: green;
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
// turbopack.ignoreIssue only works with Turbopack
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'css-parse-error-recovery',
() => {
describe('with turbopack.ignoreIssue config', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
nextConfig: {
turbopack: {
ignoreIssue: [
{
path: '**/css-error/**',
},
],
},
},
})
if (skipped) return
it('should render page with ignored CSS parse error', async () => {
const res = await next.fetch('/css-error')
expect(res.status).toBe(200)
const html = await res.text()
expect(html).toContain('css error page')
})
it('should suppress CSS parse error from cli output when ignored', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/css-error')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('GET /css-error')
})
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).not.toContain('Parsing CSS source code failed')
})
})
describe('without turbopack.ignoreIssue config', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) return
it('should show CSS parse error in cli output when not ignored', async () => {
const outputIndex = next.cliOutput.length
await next.fetch('/css-error')
await retry(async () => {
const output = stripAnsi(next.cliOutput.slice(outputIndex))
expect(output).toContain('Parsing CSS source code failed')
})
})
})
}
)
...@@ -402,6 +402,30 @@ pub async fn parse_css( ...@@ -402,6 +402,30 @@ pub async fn parse_css(
.await .await
} }
/// Parse a CSS stylesheet and run CSS module validation.
///
/// Does not handle parser warnings — the caller is responsible for configuring
/// the `warnings` field in `config` and processing collected warnings.
fn parse_css_stylesheet<'a, 'o>(
code: &'a str,
config: ParserOptions<'o, 'a>,
ty: CssModuleType,
source: ResolvedVc<Box<dyn Source>>,
) -> Result<StyleSheet<'a, 'o>, lightningcss::error::Error<lightningcss::error::ParserError<'a>>> {
let mut ss = StyleSheet::parse(code, config)?;
if matches!(ty, CssModuleType::Module) {
let mut validator = CssValidator { errors: Vec::new() };
ss.visit(&mut validator).unwrap();
for err in validator.errors {
err.report(source);
}
}
Ok(ss)
}
async fn process_content( async fn process_content(
content_vc: ResolvedVc<FileContent>, content_vc: ResolvedVc<FileContent>,
code: String, code: String,
...@@ -453,30 +477,23 @@ async fn process_content( ...@@ -453,30 +477,23 @@ async fn process_content(
let stylesheet = { let stylesheet = {
let warnings: Arc<RwLock<_>> = Default::default(); let warnings: Arc<RwLock<_>> = Default::default();
match StyleSheet::parse( match parse_css_stylesheet(
&code, &code,
ParserOptions { ParserOptions {
warnings: Some(warnings.clone()), warnings: Some(warnings.clone()),
..config.clone() ..config.clone()
}, },
ty,
source,
) { ) {
Ok(mut ss) => { Ok(mut ss) => {
if matches!(ty, CssModuleType::Module) {
let mut validator = CssValidator { errors: Vec::new() };
ss.visit(&mut validator).unwrap();
for err in validator.errors {
err.report(source);
}
}
for err in warnings.read().unwrap().iter() { for err in warnings.read().unwrap().iter() {
match err.kind { match err.kind {
lightningcss::error::ParserError::UnexpectedToken(_) lightningcss::error::ParserError::UnexpectedToken(_)
| lightningcss::error::ParserError::UnexpectedImportRule | lightningcss::error::ParserError::UnexpectedImportRule
| lightningcss::error::ParserError::SelectorError(..) | lightningcss::error::ParserError::SelectorError(..)
| lightningcss::error::ParserError::EndOfInput => { | lightningcss::error::ParserError::EndOfInput => {
let source = match &err.loc { let issue_source = match &err.loc {
Some(loc) => IssueSource::from_single_line_col( Some(loc) => IssueSource::from_single_line_col(
source, source,
SourcePos { SourcePos {
...@@ -491,11 +508,10 @@ async fn process_content( ...@@ -491,11 +508,10 @@ async fn process_content(
ParsingIssue { ParsingIssue {
msg: err.kind.to_string().into(), msg: err.kind.to_string().into(),
stage: IssueStage::Parse, stage: IssueStage::Parse,
source, source: issue_source,
} }
.resolved_cell() .resolved_cell()
.emit(); .emit();
return Ok(ParseCssResult::Unparsable.cell());
} }
_ => { _ => {
...@@ -519,7 +535,7 @@ async fn process_content( ...@@ -519,7 +535,7 @@ async fn process_content(
targets, targets,
..Default::default() ..Default::default()
}) { }) {
let source = match &e.loc { let issue_source = match &e.loc {
Some(loc) => IssueSource::from_single_line_col( Some(loc) => IssueSource::from_single_line_col(
source, source,
SourcePos { SourcePos {
...@@ -533,17 +549,32 @@ async fn process_content( ...@@ -533,17 +549,32 @@ async fn process_content(
ParsingIssue { ParsingIssue {
msg: e.kind.to_string().into(), msg: e.kind.to_string().into(),
stage: IssueStage::Transform, stage: IssueStage::Transform,
source, source: issue_source,
} }
.resolved_cell() .resolved_cell()
.emit(); .emit();
return Ok(ParseCssResult::Unparsable.cell()); // Re-parse to get a fresh stylesheet since minify may
// have partially modified the original.
match parse_css_stylesheet(
&code,
ParserOptions {
warnings: None,
..config.clone()
},
ty,
source,
) {
Ok(fresh) => {
stylesheet_into_static(&fresh, without_warnings(config.clone()))
}
Err(_) => return Ok(ParseCssResult::Unparsable.cell()),
}
} else {
stylesheet_into_static(&ss, without_warnings(config.clone()))
} }
stylesheet_into_static(&ss, without_warnings(config.clone()))
} }
Err(e) => { Err(e) => {
let source = match &e.loc { let issue_source = match &e.loc {
Some(loc) => IssueSource::from_single_line_col( Some(loc) => IssueSource::from_single_line_col(
source, source,
SourcePos { SourcePos {
...@@ -557,7 +588,7 @@ async fn process_content( ...@@ -557,7 +588,7 @@ async fn process_content(
ParsingIssue { ParsingIssue {
msg: e.kind.to_string().into(), msg: e.kind.to_string().into(),
stage: IssueStage::Parse, stage: IssueStage::Parse,
source, source: issue_source,
} }
.resolved_cell() .resolved_cell()
.emit(); .emit();
......
.before {
color: red;
}
.invalid {
color
}
.after {
color: green;
}
::highlight(highlight-test) {
color: white;
}
.carousel {
scroll-marker-group: after;
}
.carousel > *::scroll-marker {
content: "";
}
.carousel > *::scroll-marker:target-current {
background: oklch(0.5 0 0 / 0.6);
}
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css:13:12 Parsing CSS source code failed
9 | .after {
10 | color: green;
11 | }
12 |
+ v
13 + ::highlight(highlight-test) {
+ ^
14 | color: white;
15 | }
16 |
17 | .carousel {
'highlight' is not recognized as a valid pseudo-element. Did you mean ':highlight' (pseudo-class) or is this a typo?
Import trace:
test:
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/index.js
\ No newline at end of file
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css:25:29 Parsing CSS source code failed
21 | .carousel > *::scroll-marker {
22 | content: "";
23 | }
24 |
+ v
25 + .carousel > *::scroll-marker:target-current {
+ ^
26 | background: oklch(0.5 0 0 / 0.6);
27 | }
28 |
'target-current' is not recognized as a valid pseudo-class. Did you mean '::target-current' (pseudo-element) or is this a typo?
Import trace:
test:
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/index.js
\ No newline at end of file
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css:7:0 Parsing CSS source code failed
3 | }
4 |
5 | .invalid {
6 | color
+ v
7 + }
+ ^
8 |
9 | .after {
10 | color: green;
11 | }
Unexpected end of input
Import trace:
test:
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/index.js
\ No newline at end of file
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css:25:14 Parsing CSS source code failed
21 | .carousel > *::scroll-marker {
22 | content: "";
23 | }
24 |
+ v
25 + .carousel > *::scroll-marker:target-current {
+ ^
26 | background: oklch(0.5 0 0 / 0.6);
27 | }
28 |
'scroll-marker' is not recognized as a valid pseudo-element. Did you mean ':scroll-marker' (pseudo-class) or is this a typo?
Import trace:
test:
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/index.js
\ No newline at end of file
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css:21:14 Parsing CSS source code failed
17 | .carousel {
18 | scroll-marker-group: after;
19 | }
20 |
+ v
21 + .carousel > *::scroll-marker {
+ ^
22 | content: "";
23 | }
24 |
25 | .carousel > *::scroll-marker:target-current {
'scroll-marker' is not recognized as a valid pseudo-element. Did you mean ':scroll-marker' (pseudo-class) or is this a typo?
Import trace:
test:
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css
./turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/index.js
\ No newline at end of file
{
"minifyType": {
"Minify": {
"mangle": "optimal-size"
}
}
}
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/0teu_crates_turbopack-tests_tests_snapshot_css_css-parse-error_input_index_0y.wenm.js","[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/index.js [test] (ecmascript)",s=>{"use strict";s.s([])}]);
//# sourceMappingURL=0teu_crates_turbopack-tests_tests_snapshot_css_css-parse-error_input_index_0y.wenm.js.map
\ No newline at end of file
.before{color:red}.after{color:green}::highlight(highlight-test){color:#fff}.carousel{scroll-marker-group:after}.carousel>::scroll-marker{content:""}.carousel>::scroll-marker:target-current{background:#63636399;background:lab(42% 0 0/.6)}
/*# sourceMappingURL=0teu_crates_turbopack-tests_tests_snapshot_css_css-parse-error_input_style_0bz27vy.css.map*/
\ No newline at end of file
{"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/style.css"],"sourcesContent":[".before {\n color: red;\n}\n\n.invalid {\n color\n}\n\n.after {\n color: green;\n}\n\n::highlight(highlight-test) {\n color: white;\n}\n\n.carousel {\n scroll-marker-group: after;\n}\n\n.carousel > *::scroll-marker {\n content: \"\";\n}\n\n.carousel > *::scroll-marker:target-current {\n background: oklch(0.5 0 0 / 0.6);\n}\n"],"names":[],"mappings":"AAAA,kBAQA,mBAIA,uCAIA,oCAIA,qCAIA"}
\ No newline at end of file
(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["output/0v.~_crates_turbopack-tests_tests_snapshot_css_css-parse-error_input_index_0gmxdq5.js",{otherChunks:["output/0teu_crates_turbopack-tests_tests_snapshot_css_css-parse-error_input_style_0bz27vy.css","output/0teu_crates_turbopack-tests_tests_snapshot_css_css-parse-error_input_index_0y.wenm.js"],runtimeModuleIds:["[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/css-parse-error/input/index.js [test] (ecmascript)"]}]);
//# sourceMappingURL=0teu_crates_turbopack-tests_tests_snapshot_css_css-parse-error_input_index_0gmxdq5.js.map
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment