swc-project/swc · error
invalid utf8 character detected
Error message
invalid utf8 character detected
What it means
In swc_compiler_base's print function, the emitted JavaScript output buffer contained invalid UTF-8 when converted with String::from_utf8 after printing. JavaScript strings are UTF-16, so codegen can produce byte sequences (e.g. from lone surrogates in string literals) that are valid JS source but not valid UTF-8; this fires when the host demands a Rust String and such bytes are present.
Source
Thrown at crates/swc_compiler_base/src/lib.rs:238
w.preamble(preamble).unwrap();
let mut wr = Box::new(w) as Box<dyn WriteJs>;
if codegen_config.minify {
wr = Box::new(swc_ecma_codegen::text_writer::omit_trailing_semi(wr));
}
let mut emitter = Emitter {
cfg: codegen_config,
comments,
cm: cm.clone(),
wr,
};
node.emit_with(&mut emitter)
.context("failed to emit module")?;
}
// Invalid utf8 is valid in javascript world.
String::from_utf8(buf).expect("invalid utf8 character detected")
};
if cfg!(debug_assertions)
&& !src_map_buf.is_empty()
&& src_map_buf.iter().all(|(bp, _)| bp.is_dummy())
&& src.lines().count() >= 3
&& option_env!("SWC_DEBUG") == Some("1")
{
panic!("The module contains only dummy spans\n{src}");
}
let additional_scope_names = scope_buf
.as_deref()
.map(source_map_scopes::collect_additional_names)
.unwrap_or_default();
let mut map = if source_map.enabled() {
Some(cm.build_source_map(View on GitHub (pinned to 5176682b65)
Solutions
- Avoid lone surrogates (\uD800-\uDFFF unpaired) in source string literals
- Sanitize or replace unpaired surrogates in input data before compilation
- If the output crosses a UTF-16 boundary (e.g. JS host), use lossy conversion or byte-level output APIs
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at crates/swc_compiler_base/src/lib.rs:238 when the library encounters an invalid state.
Common situations: See trigger scenarios.
Understand the failure class
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
AI-assisted analysis of swc-project/swc@5176682b65 (2026-08-17).
Data as JSON: /api/errors/7152b0f31f3a0432.
Report an issue: GitHub.