Unverified Commit ce14ca88 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Reimplement code frame rendering in native code (#85592)

## What

Replaces the `@babel/code-frame` dependency with a new Rust-based implementation (`next-code-[frame](https://github.com/arthurprs/qfilter/pull/20#issuecomment-3986882055)` crate) for rendering code frames in error messages.

### Why

- **Crash fix**: `@babel/code-frame` uses the `js-tokens` library for syntax highlighting, which has [known issues](https://github.com/lydell/js-tokens?tab=readme-ov-file#known-failures) with large string literals and long lines. This can cause Next.js to throw RangeErrors when rendering errors, hiding the original issue!
- **Long line support**: The old implementation had no concept of terminal width, dumping entire lines into the output. The new implementation uses "horizontal scrolling" — truncating lines and centering the error location in the visible window.
- **Performance**: The Rust implementation only processes the visible line range (typically ~6 lines), not the entire file. Syntax highlighting uses a skip-scan heuristic to start tokenizing near the visible window rather than from byte 0.
- **Dependency reduction**: Drops the semi-unmaintained `@babel/code-frame` bundled dependency in favor of code we control.

### Benchmarks

In-process benchmarks comparing `render_code_frame()` (Rust, via criterion) against `codeFrameColumns()` (Babel, via hrtime with DCE prevention). Both have syntax highlighting and color output enabled. No process startup or file I/O is included in the measurement.

| Scenario | `next-code-frame` (Rust) | `@babel/code-frame` | Speedup |
|---|---|---|---|
| Small file (~490 lines TSX) | **5.4 µs** | 507 µs | **~94x** |
| Large file (~39k lines JS) | **143 µs** | 82.9 ms | **~580x** |
| Large file minified | **51 µs** | - | **-** |

The gap widens with file size because Babel's `highlight()` runs a regex tokenizer over the **entire source** before slicing to the visible window, while the Rust implementation uses a windowed line index and skip-scan heuristic — only processing the visible window regardless of file size.  However, for minified files we do end up tokenizing the whole thing so we end up being only 8x faster

### How

- New `crates/next-code-frame/` Rust crate with:
  - Frame rendering with terminal-width-aware horizontal scrolling
  - Regex-based syntax highlighting (matching Babel's color scheme)
  - Skip-scan heuristic for O(1)-ish highlighting regardless of file size
  - Windowed line index that only scans/stores offsets for the visible region
  - Comprehensive test suite (800+ lines)
- Exposed via both NAPI (native) and WASM bindings
- JS wrappers in `packages/next/src/shared/lib/errors/`:
  - `code-frame.ts` — primary wrapper using native bindings
  - `optional-code-frame.ts` — graceful fallback returning `undefined` if bindings are unavailable
- All existing callsites (`diagnosticFormatter`, `parseScss`, dev overlay, turbopack utils) updated
- for `patch-error-inspect.ts` i adopted an `injection` style approach to avoid coupling to the native dependency

### Concerns / review focus areas

- **Reliability**: The regex-based tokenizer is best-effort and language-agnostic — it should never crash on invalid syntax, but highlighting accuracy may differ from Babel's `js-tokens` in edge cases.
- **Native dependency**: This moves code frame rendering into the native binary. Performance should be better, but worth verifying there are no regressions in environments where native bindings behave differently (e.g. WASM fallback path).
- **Regressions**: The output format and color scheme closely match Babel's, but there may be subtle differences. The horizontal scrolling behavior is new.

Fixes #85357
Closes PACK-5754
parent ac86a613
......@@ -3448,16 +3448,16 @@ dependencies = [
[[package]]
name = "insta"
version = "1.41.1"
version = "1.46.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e9ffc4d4892617c50a928c52b2961cb5174b6fc6ebf252b2fac9d21955c48b8"
checksum = "e82db8c87c7f1ccecb34ce0c24399b8a73081427f3c7c50a5d597925356115e4"
dependencies = [
"console",
"lazy_static",
"linked-hash-map",
"once_cell",
"regex",
"serde",
"similar",
"tempfile",
]
[[package]]
......@@ -4512,6 +4512,22 @@ dependencies = [
"turbopack-trace-utils",
]
[[package]]
name = "next-code-frame"
version = "0.0.1"
dependencies = [
"anyhow",
"clap",
"codspeed-criterion-compat",
"insta",
"memchr",
"phf",
"regex",
"regex-automata",
"serde",
"unicode-width 0.2.1",
]
[[package]]
name = "next-core"
version = "0.1.0"
......@@ -4626,6 +4642,7 @@ dependencies = [
"napi-derive",
"next-api",
"next-build",
"next-code-frame",
"next-core",
"next-custom-transforms",
"next-taskless",
......@@ -10987,6 +11004,7 @@ dependencies = [
"getrandom 0.3.3",
"js-sys",
"mdxjs",
"next-code-frame",
"next-custom-transforms",
"next-taskless",
"rustc-hash 2.1.1",
......
......@@ -8,6 +8,7 @@ members = [
"crates/next-api",
"crates/next-build-test",
"crates/next-build",
"crates/next-code-frame",
"crates/next-core",
"crates/next-custom-transforms",
"crates/next-taskless",
......@@ -284,6 +285,7 @@ debug = true
# Workspace crates
next-api = { path = "crates/next-api" }
next-build = { path = "crates/next-build" }
next-code-frame = { path = "crates/next-code-frame" }
next-core = { path = "crates/next-core" }
next-custom-transforms = { path = "crates/next-custom-transforms", default-features = false }
next-taskless = { path = "crates/next-taskless" }
......@@ -410,6 +412,7 @@ lightningcss-napi = { version = "0.4.6", default-features = false, features = [
] }
lzzzz = "2.0.0"
markdown = "1.0.0-alpha.18"
memchr = "2.7.4"
mime = "0.3.16"
napi = { version = "2", default-features = false, features = [
"napi3",
......
[package]
name = "next-code-frame"
version = "0.0.1"
description = "Fast, scalable code frame rendering for Next.js error reporting"
license = "MIT"
edition = "2024"
[lib]
bench = false
[[bin]]
name = "code_frame"
path = "src/bin/code_frame.rs"
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
clap = { workspace = true }
memchr = { workspace = true }
phf = { version = "0.11", features = ["macros"] }
regex = { workspace = true }
regex-automata = "0.4"
serde = { workspace = true }
unicode-width = "0.2"
[dev-dependencies]
criterion = { workspace = true }
insta = { version = "1.43.1", features = ["yaml"] }
[[bench]]
name = "code_frame_bench"
harness = false
# next-code-frame
Fast, scalable code frame rendering for Next.js error reporting, written in Rust.
This crate provides functionality similar to `@babel/code-frame` but with several improvements:
- **Scalability**: Handles arbitrarily large files efficiently
- **Long line handling**: Gracefully scrolls long lines to keep error positions visible and avoid overwhelming the terminal with long lines
- **Syntax highlighting**: Uses a language-agnostic regex tokenizer for best-effort syntax highlighting
## Design
Following the `next-taskless` pattern, this crate:
- Has no dependency on turbo-tasks, allowing use in webpack/rspack codepaths
- Is compilable to WASM for environments without native bindings
- Follows "sans-io" patterns - the library accepts file content as arguments rather than performing IO
## CLI
A `code_frame` binary is included for quick testing. Pass a filename and start/end positions (1-indexed `line:column`):
```bash
# Highlight a single position
cargo run -p next-code-frame --bin code_frame -- src/app.tsx 10:5
# Highlight a range
cargo run -p next-code-frame --bin code_frame -- src/app.tsx 10:5 10:20
# With an error message
cargo run -p next-code-frame --bin code_frame -- -m "Unexpected token" src/app.tsx 10:5 10:20
```
## Syntax highlighting
The highlighter uses a single compiled regex pass over the visible content to
tokenize strings, comments, numbers, regex literals, and identifiers. Keywords
are identified via a compile-time perfect hash set (`phf`).
### Skip-scan heuristic
For large files, scanning from byte 0 is expensive — the regex tokenizer
dominates runtime. To avoid this, `extract_highlights()` walks backwards from
the visible window looking for a **blank line** and starts the scan there.
A blank line is a safe restart point for single-line constructs (strings,
line comments, regex literals) because they cannot span blank lines.
**Known limitation:** The heuristic can produce incorrect highlighting when a
multi-line construct (block comment or template literal) contains a blank line
that falls between the scan start and the visible window. In this case the
scanner misses the opening delimiter and the closing delimiter / trailing code
may lose its expected coloring. For example:
```js
/** sneaky
*/
const after = 1; // `*/` may lose comment highlighting
```
This is a deliberate tradeoff — blank lines inside block comments or template
literals that span the window boundary are vanishingly rare in practice, and
the consequence is only slightly wrong highlighting, never a failure or missing output.
### Byte-level skip for long lines
When the visible window starts far into a long line (>200 bytes from the
line-level scan start), the heuristic additionally scans backwards from the
visible start for a `;` and restarts the tokenizer there. This is critical for
minified files where the entire source may be a single line — without it the
scanner would tokenize hundreds of kilobytes of invisible content.
**Known limitation:** The `;` can land inside a string literal, causing an
unbalanced quote that cascades incorrect highlighting across the visible window.
In practice minified code has frequent `;` between statements so this rarely
triggers, and the consequence is only incorrect highlighting, never a failure.
## Features
- Caller-provided output width (no terminal detection — sans-io)
- Syntax highlighting for JS, TS, JSX, TSX
- Graceful degradation for non-JS files or parsing errors
- ANSI color support matching babel-code-frame aesthetics
- Support for single-line and multi-line error ranges
use criterion::{Criterion, black_box, criterion_group, criterion_main};
use next_code_frame::{CodeFrameLocation, CodeFrameOptions, Language, Location, render_code_frame};
/// Generate a realistic small TypeScript/React file (~300 lines).
fn generate_small_file() -> String {
let mut lines = Vec::with_capacity(300);
lines.push("import React, { useState, useEffect, useCallback, useMemo } from 'react'");
lines.push("import { useRouter } from 'next/router'");
lines.push("import Link from 'next/link'");
lines.push("");
lines.push("interface User {");
lines.push(" id: string");
lines.push(" name: string");
lines.push(" email: string");
lines.push(" avatar?: string");
lines.push(" role: 'admin' | 'user' | 'moderator'");
lines.push(" createdAt: Date");
lines.push("}");
lines.push("");
// Pad with realistic component code
for i in 0..40 {
lines.push("function ComponentPart() {");
// Use a leaked string so we get &'static str
let s: &'static str =
Box::leak(format!(" const [state{i}, setState{i}] = useState(null)").into_boxed_str());
lines.push(s);
lines.push(" useEffect(() => {");
let s: &'static str = Box::leak(
format!(" fetch('/api/data/{i}').then(r => r.json()).then(setState{i})")
.into_boxed_str(),
);
lines.push(s);
lines.push(" }, [])");
lines.push(" return (");
lines.push(" <div className=\"flex items-center justify-center p-4\">");
let s: &'static str =
Box::leak(format!(" <span>{{state{i}?.name}}</span>").into_boxed_str());
lines.push(s);
lines.push(" </div>");
lines.push(" )");
lines.push("}");
lines.push("");
}
lines.join("\n")
}
/// Generate a large bundled JS file (~30k lines) mimicking react-dom.development.js.
fn generate_large_file(minified: bool) -> String {
let mut lines = Vec::with_capacity(30_000);
lines.push("/**");
lines.push(" * @license React");
lines.push(" * react-dom.development.js");
lines.push(" *");
lines.push(" * Copyright (c) Meta Platforms, Inc. and affiliates.");
lines.push(" */");
lines.push("'use strict';");
lines.push("");
lines.push("(function (global, factory) {");
lines.push(
" typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, \
require('react')) :",
);
lines.push(
" typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :",
);
lines.push(" (global = global || self, factory(global.ReactDOM = {}, global.React));");
lines.push("}(this, (function (exports, React) { 'use strict';");
lines.push("");
// Generate ~30k lines of realistic bundled code
for i in 0..3000 {
lines.push(
"function reconcileChildFibers(returnFiber, currentFirstChild, newChild, lanes) {",
);
// Leaked strings for &'static str
let s: &'static str = Box::leak(
format!(
" var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== \
null && newChild.type === REACT_FRAGMENT_TYPE_{i} && newChild.key === null;"
)
.into_boxed_str(),
);
lines.push(s);
lines.push(" if (isUnkeyedTopLevelFragment) {");
lines.push(" newChild = newChild.props.children;");
lines.push(" }");
lines.push(" if (typeof newChild === 'object' && newChild !== null) {");
lines.push(" switch (newChild.$$typeof) {");
lines.push(" case REACT_ELEMENT_TYPE:");
lines.push(
" return placeSingleChild(reconcileSingleElement(returnFiber, \
currentFirstChild, newChild, lanes));",
);
lines.push(" }");
lines.push(" }");
lines.push("}");
lines.push("");
}
lines.push("})));");
lines.join(if minified { " " } else { "\n" })
}
fn bench_small_file(c: &mut Criterion) {
let source = generate_small_file();
let line_count = source.lines().count();
let mid = line_count / 2;
let location = CodeFrameLocation {
start: Location {
line: mid,
column: Some(10),
},
end: None,
};
let options = CodeFrameOptions {
highlight_code: true,
color: true,
max_width: 100,
language: Language::JavaScript,
..Default::default()
};
c.bench_function(&format!("rust: small file ({line_count} lines)"), |b| {
b.iter(|| {
let result = render_code_frame(black_box(&source), black_box(&location), &options);
black_box(result).unwrap();
});
});
}
fn bench_large_file(c: &mut Criterion) {
let source = generate_large_file(false);
let line_count = source.lines().count();
let mid = line_count / 2;
let location = CodeFrameLocation {
start: Location {
line: mid,
column: Some(10),
},
end: None,
};
let options = CodeFrameOptions {
highlight_code: true,
color: true,
max_width: 100,
language: Language::JavaScript,
..Default::default()
};
c.bench_function(&format!("rust: large file ({line_count} lines)"), |b| {
b.iter(|| {
let result = render_code_frame(black_box(&source), black_box(&location), &options);
black_box(result).unwrap();
});
});
}
fn bench_minified_file(c: &mut Criterion) {
// Take the large file and collapse lines by stripping whitespace after `;`
// to simulate a minified bundle with very long lines.
let source = generate_large_file(true);
let line_count = source.lines().count();
// Point at a column somewhere in the middle of the long line
let mid_col = source.lines().next().map_or(100, |l| l.len() / 2);
let location = CodeFrameLocation {
start: Location {
line: 1,
column: Some(mid_col),
},
end: None,
};
let options = CodeFrameOptions {
highlight_code: true,
color: true,
max_width: 100,
language: Language::JavaScript,
..Default::default()
};
c.bench_function(
&format!("rust: minified file ({line_count} lines, ~{mid_col} col)"),
|b| {
b.iter(|| {
let result = render_code_frame(black_box(&source), black_box(&location), &options);
black_box(result).unwrap();
});
},
);
}
criterion_group!(
benches,
bench_small_file,
bench_large_file,
bench_minified_file
);
criterion_main!(benches);
use std::{fs, process::ExitCode};
use clap::Parser;
use next_code_frame::{CodeFrameLocation, CodeFrameOptions, Location, render_code_frame};
/// Render a code frame for the given file and position.
///
/// Lines and columns are 1-indexed.
#[derive(Parser)]
#[command(name = "code_frame")]
struct Args {
/// Source file to render
file: String,
/// Start position (line:column, 1-indexed)
start: String,
/// End position (line:column, 1-indexed)
end: Option<String>,
/// Message to display with the error
#[arg(short, long)]
message: Option<String>,
/// Maximum output width in columns
#[arg(short = 'w', long, default_value_t = 100)]
max_width: usize,
}
fn parse_position(s: &str) -> Option<Location> {
let (line, col) = s.split_once(':')?;
Some(Location {
line: line.parse().ok()?,
column: Some(col.parse().ok()?),
})
}
fn main() -> ExitCode {
let args = Args::parse();
let source = match fs::read_to_string(&args.file) {
Ok(s) => s,
Err(e) => {
eprintln!("Error reading {}: {e}", args.file);
return ExitCode::FAILURE;
}
};
let start = match parse_position(&args.start) {
Some(loc) => loc,
None => {
eprintln!("Invalid start position: {}", args.start);
return ExitCode::FAILURE;
}
};
let end = match args.end.as_deref().map(parse_position) {
Some(Some(loc)) => Some(loc),
Some(None) => {
eprintln!("Invalid end position: {}", args.end.unwrap());
return ExitCode::FAILURE;
}
None => None,
};
let location = CodeFrameLocation { start, end };
let options = CodeFrameOptions {
message: args.message,
max_width: args.max_width,
..Default::default()
};
match render_code_frame(&source, &location, &options) {
Ok(Some(frame)) => {
println!("{frame}");
ExitCode::SUCCESS
}
Ok(None) => {
// Location is out of range (e.g., empty file or line past EOF)
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("Error rendering code frame: {e}");
ExitCode::FAILURE
}
}
}
This diff is collapsed.
This diff is collapsed.
#![doc = include_str!("../README.md")]
mod frame;
mod highlight;
pub use frame::{CodeFrameLocation, CodeFrameOptions, Location, render_code_frame};
pub use highlight::Language;
#[cfg(test)]
mod tests;
This diff is collapsed.
......@@ -65,6 +65,7 @@ futures-util = { workspace = true }
owo-colors = { workspace = true }
napi = { workspace = true }
napi-derive = { workspace = true }
next-code-frame = { workspace = true }
next-custom-transforms = { workspace = true }
next-taskless = { workspace = true }
rand = { workspace = true }
......
use napi::bindgen_prelude::*;
use napi_derive::napi;
use next_code_frame::{CodeFrameLocation, CodeFrameOptions, Language, Location, render_code_frame};
/// Default max width when the caller doesn't provide one (e.g., no terminal).
const DEFAULT_MAX_WIDTH: u32 = 100;
#[napi(object)]
pub struct NapiLocation {
pub line: u32,
pub column: Option<u32>,
}
impl From<NapiLocation> for Location {
fn from(loc: NapiLocation) -> Self {
Location {
line: loc.line as usize,
column: loc.column.map(|c| c as usize),
}
}
}
#[napi(object)]
pub struct NapiCodeFrameLocation {
pub start: NapiLocation,
pub end: Option<NapiLocation>,
}
impl From<NapiCodeFrameLocation> for CodeFrameLocation {
fn from(loc: NapiCodeFrameLocation) -> Self {
CodeFrameLocation {
start: loc.start.into(),
end: loc.end.map(Into::into),
}
}
}
#[napi(object)]
#[derive(Default)]
pub struct NapiCodeFrameOptions {
/// Number of lines to show above the error (default: 2)
pub lines_above: Option<u32>,
/// Number of lines to show below the error (default: 3)
pub lines_below: Option<u32>,
/// Maximum width of the output in columns (default: 100)
pub max_width: Option<u32>,
/// Whether to use ANSI colors (default: false)
pub color: Option<bool>,
/// Whether to highlight code syntax (default: follows color)
///
/// This might be useful if syntax highlighting is very expensive or known to be useless for
/// this file. The current syntax rules are optimized for javascript but should work well with
/// other C-like languages.
pub highlight_code: Option<bool>,
/// Optional message to display with the code frame
pub message: Option<String>,
/// Language hint for keyword highlighting: "javascript" (default) or "css"
pub language: Option<String>,
}
fn parse_language(s: &Option<String>) -> Language {
match s.as_deref() {
Some("css") => Language::Css,
_ => Language::JavaScript,
}
}
impl From<NapiCodeFrameOptions> for CodeFrameOptions {
fn from(opts: NapiCodeFrameOptions) -> Self {
CodeFrameOptions {
lines_above: opts.lines_above.unwrap_or(2) as usize,
lines_below: opts.lines_below.unwrap_or(3) as usize,
max_width: opts.max_width.unwrap_or(DEFAULT_MAX_WIDTH) as usize,
color: opts.color.unwrap_or(false),
highlight_code: opts.highlight_code.unwrap_or(opts.color.unwrap_or(false)),
message: opts.message,
language: parse_language(&opts.language),
}
}
}
/// Renders a code frame showing the location of an error in source code
///
/// This is a Rust implementation that replaces Babel's code-frame for better:
/// - Performance on large files
/// - Handling of long lines
/// - Memory efficiency
///
/// # Arguments
/// * `source` - The source code to render
/// * `location` - The location to highlight (line and column numbers are 1-indexed)
/// * `options` - Optional configuration
///
/// # Returns
/// The formatted code frame string, or `undefined` if the location is out of
/// range (e.g., empty source or line number past end of file).
#[napi]
pub fn code_frame_columns(
source: String,
location: NapiCodeFrameLocation,
options: Option<NapiCodeFrameOptions>,
) -> Result<Option<String>> {
let code_frame_location: CodeFrameLocation = location.into();
let code_frame_options: CodeFrameOptions = options.unwrap_or_default().into();
render_code_frame(&source, &code_frame_location, &code_frame_options)
.map_err(|e| Error::from_reason(format!("Failed to render code frame: {e:?}")))
}
......@@ -42,6 +42,7 @@ use swc_core::{
common::{FilePathMapping, SourceMap},
};
pub mod code_frame;
#[cfg(not(target_arch = "wasm32"))]
pub mod css;
pub mod lockfile;
......
......@@ -24,6 +24,7 @@ getrandom3 = { package="getrandom", version = "0.3", default-features = false, f
js-sys = "0.3.59"
next-custom-transforms = { workspace = true }
next-taskless = { workspace = true }
next-code-frame = { workspace = true }
rustc-hash = { workspace = true }
serde-wasm-bindgen = "0.4.3"
serde_json = "1"
......
......@@ -225,3 +225,22 @@ pub fn expand_next_js_template(
)
.map_err(convert_err)
}
#[wasm_bindgen(js_name = "codeFrameColumns")]
pub fn code_frame_columns(
source: Box<[u8]>,
location: JsValue,
options: JsValue,
) -> Result<Option<String>, JsError> {
console_error_panic_hook::set_once();
let location: next_code_frame::CodeFrameLocation = serde_wasm_bindgen::from_value(location)?;
let options: next_code_frame::CodeFrameOptions = serde_wasm_bindgen::from_value(options)?;
next_code_frame::render_code_frame(
str::from_utf8(&source)
.map_err(|e| JsError::new(&format!("Failed to render code frame: {e}")))?,
&location,
&options,
)
.map_err(|e| JsError::new(&format!("Failed to render code frame: {e}")))
}
use js_sys::JsString;
use mdxjs::{Options, compile};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::future_to_promise;
#[wasm_bindgen(js_name = "mdxCompileSync")]
pub fn mdx_compile_sync(value: JsString, opts: JsValue) -> Result<JsValue, JsValue> {
let value: String = value.into();
let option: Options = serde_wasm_bindgen::from_value(opts)?;
let option: mdxjs::Options = serde_wasm_bindgen::from_value(opts)?;
compile(value.as_str(), &option)
mdxjs::compile(value.as_str(), &option)
.map(|v| serde_wasm_bindgen::to_value(&v).expect("Should able to convert to JsValue"))
.map_err(|v| {
serde_wasm_bindgen::to_value(&v.to_string()).expect("Should able to convert to JsValue")
......
......@@ -1084,5 +1084,6 @@
"1083": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route",
"1084": "Route \"%s\": Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route",
"1085": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata",
"1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport"
"1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport",
"1087": "Failed to parse \"%s\":\\n%s%s"
}
......@@ -130,7 +130,6 @@
"sharp": "^0.34.5"
},
"devDependencies": {
"@babel/code-frame": "7.26.2",
"@babel/core": "7.26.10",
"@babel/eslint-parser": "7.24.6",
"@babel/generator": "7.27.0",
......
......@@ -1002,6 +1002,11 @@ export default async function build(
// Install the native bindings early so we can have synchronous access later.
await installBindings(config.experimental?.useWasmBinary)
// Set up code frame renderer for error formatting
const { installCodeFrameSupport } =
require('../server/lib/install-code-frame') as typeof import('../server/lib/install-code-frame')
installCodeFrameSupport()
process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
NextBuildContext.config = config
......
......@@ -6,6 +6,7 @@ import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfi
import { readFileSync } from 'fs'
import isError from '../lib/is-error'
import { hasNecessaryDependencies } from '../lib/has-necessary-dependencies'
import { codeFrameColumns } from '../shared/lib/errors/code-frame'
let TSCONFIG_WARNED = false
......@@ -23,19 +24,21 @@ export function parseJsonFile(filePath: string) {
return JSON5.parse(contents)
} catch (err) {
if (!isError(err)) throw err
const { codeFrameColumns } =
require('next/dist/compiled/babel/code-frame') as typeof import('next/dist/compiled/babel/code-frame')
const codeFrame = codeFrameColumns(
String(contents),
{
start: {
line: (err as Error & { lineNumber?: number }).lineNumber || 0,
column: (err as Error & { columnNumber?: number }).columnNumber || 0,
line: (err as Error & { lineNumber?: number }).lineNumber || 1,
column:
(err as Error & { columnNumber?: number }).columnNumber ||
undefined,
},
},
{ message: err.message, highlightCode: true }
{ message: err.message, color: true }
)
throw new Error(
`Failed to parse "${filePath}":\n${codeFrame ?? err.message}`
)
throw new Error(`Failed to parse "${filePath}":\n${codeFrame}`)
}
}
......
......@@ -58,6 +58,58 @@ export declare function recvTaskMessageInWorker(
workerId: number
): Promise<NapiTaskMessage>
export declare function sendTaskMessage(message: NapiTaskMessage): Promise<void>
export interface NapiLocation {
line: number
column?: number
}
export interface NapiCodeFrameLocation {
start: NapiLocation
end?: NapiLocation
}
export interface NapiCodeFrameOptions {
/** Number of lines to show above the error (default: 2) */
linesAbove?: number
/** Number of lines to show below the error (default: 3) */
linesBelow?: number
/** Maximum width of the output in columns (default: 100) */
maxWidth?: number
/** Whether to use ANSI colors (default: false) */
color?: boolean
/**
* Whether to highlight code syntax (default: follows color)
*
* This might be useful if syntax highlighting is very expensive or known to be useless for
* this file. The current syntax rules are optimized for javascript but should work well with
* other C-like languages.
*/
highlightCode?: boolean
/** Optional message to display with the code frame */
message?: string
/** Language hint for keyword highlighting: "javascript" (default) or "css" */
language?: string
}
/**
* Renders a code frame showing the location of an error in source code
*
* This is a Rust implementation that replaces Babel's code-frame for better:
* - Performance on large files
* - Handling of long lines
* - Memory efficiency
*
* # Arguments
* * `source` - The source code to render
* * `location` - The location to highlight (line and column numbers are 1-indexed)
* * `options` - Optional configuration
*
* # Returns
* The formatted code frame string, or `undefined` if the location is out of
* range (e.g., empty source or line number past end of file).
*/
export declare function codeFrameColumns(
source: string,
location: NapiCodeFrameLocation,
options?: NapiCodeFrameOptions | undefined | null
): string | null
export declare function lockfileTryAcquireSync(
path: string,
content?: string | undefined | null
......
......@@ -3,14 +3,7 @@
/* tslint:disable */
/* eslint-disable */
export function mdxCompileSync(value: string, opts: any): any
export function mdxCompile(value: string, opts: any): Promise<any>
export function minifySync(s: string, opts: any): any
export function minify(s: string, opts: any): Promise<any>
export function transformSync(s: any, opts: any): any
export function transform(s: any, opts: any): Promise<any>
export function parseSync(s: string, opts: any): any
export function parse(s: string, opts: any): Promise<any>
export function expandNextJsTemplate(
content: Uint8Array,
template_path: string,
......@@ -19,3 +12,15 @@ export function expandNextJsTemplate(
injections: any,
imports: any
): string
export function codeFrameColumns(
source: Uint8Array,
location: any,
options: any
): string | undefined
export function minifySync(s: string, opts: any): any
export function parseSync(s: string, opts: any): any
export function transformSync(s: any, opts: any): any
export function parse(s: string, opts: any): Promise<any>
export function minify(s: string, opts: any): Promise<any>
export function mdxCompile(value: string, opts: any): Promise<any>
export function mdxCompileSync(value: string, opts: any): any
......@@ -16,6 +16,8 @@ import type {
NapiPartialProjectOptions,
NapiProjectOptions,
NapiSourceDiagnostic,
NapiCodeFrameLocation,
NapiCodeFrameOptions,
} from './generated-native'
import type {
Binding,
......@@ -388,7 +390,7 @@ async function tryLoadWasmWithFallback(
}
}
function loadBindingsSync() {
function loadBindingsSync(): Binding {
let attempts: any[] = []
try {
return loadNative()
......@@ -1438,6 +1440,17 @@ async function loadWasm(importPath = '') {
imports
)
},
codeFrameColumns(
source: string,
location: NapiCodeFrameLocation,
options?: NapiCodeFrameOptions
): string | undefined {
return rawBindings.codeFrameColumns(
Buffer.from(source),
location,
options
)
},
lockfileTryAcquire(_filePath: string, _content?: string | null) {
throw new Error(
'`lockfileTryAcquire` is not supported by the wasm bindings.'
......@@ -1464,7 +1477,7 @@ async function loadWasm(importPath = '') {
* Loads the native (non-wasm) bindings. Prefer `loadBindings` over this API, as that includes a
* wasm fallback.
*/
function loadNative(importPath?: string) {
function loadNative(importPath?: string): Binding {
if (loadedBindings) {
return loadedBindings
}
......@@ -1687,8 +1700,13 @@ function loadNative(importPath?: string) {
lockfileUnlockSync(lockfile: Lockfile) {
return bindings.lockfileUnlockSync(lockfile)
},
codeFrameColumns(source, location, options) {
// napi-rs translates Option::None as null but wasm-bindgen translates it to `null`
// convert here for consistency
return bindings.codeFrameColumns(source, location, options) ?? undefined
},
}
return loadedBindings
return loadedBindings!
}
throw attempts
......
......@@ -7,6 +7,8 @@ import type {
NapiSourceDiagnostic,
NapiProjectOptions,
NapiPartialProjectOptions,
NapiCodeFrameOptions,
NapiCodeFrameLocation,
} from './generated-native'
export type { NapiTurboEngineOptions as TurboEngineOptions }
......@@ -80,6 +82,11 @@ export interface Binding {
lockfileTryAcquireSync(path: string, content?: string | null): Lockfile | null
lockfileUnlock(lockfile: Lockfile): Promise<void>
lockfileUnlockSync(lockfile: Lockfile): void
codeFrameColumns(
source: string,
location: NapiCodeFrameLocation,
options?: NapiCodeFrameOptions
): string | undefined
}
export type StyledString =
......
import { bold, cyan, red, yellow } from '../../../../lib/picocolors'
import { SimpleWebpackError } from './simpleWebpackError'
import { codeFrameColumns } from '../../../../shared/lib/errors/code-frame'
const regexScssError =
/SassError: (.+)\n\s+on line (\d+) [\s\S]*?>> (.+)\n\s*(-+)\^$/m
......@@ -22,13 +23,11 @@ export function getScssError(
let frame: string | undefined
if (fileContent) {
try {
const { codeFrameColumns } =
require('next/dist/compiled/babel/code-frame') as typeof import('next/dist/compiled/babel/code-frame')
frame = codeFrameColumns(
fileContent,
{ start: { line: lineNumber, column } },
{ forceColor: true }
) as string
{ color: true, language: 'css' }
)
} catch {}
}
......@@ -36,7 +35,7 @@ export function getScssError(
`${cyan(fileName)}:${yellow(lineNumber.toString())}:${yellow(
column.toString()
)}`,
red(bold('Syntax error')).concat(`: ${reason}\n\n${frame ?? backupFrame}`)
red(bold('Syntax error')).concat(`: ${reason}\n\n${frame || backupFrame}`)
)
}
......
/* eslint-disable import/no-extraneous-dependencies */
module.exports = require('@babel/code-frame')
module.exports = require('next/dist/compiled/babel-code-frame')
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This diff is collapsed.
{"name":"@babel/code-frame","main":"index.js","author":"The Babel Team (https://babel.dev/team)","license":"MIT"}
module.exports = require('next/dist/compiled/babel-code-frame')
......@@ -11,6 +11,8 @@ import type { AppPageModule } from '../server/route-modules/app-page/module'
import type { PagesModule } from '../server/route-modules/pages/module.compiled'
import '../server/node-environment'
import { installBindings } from '../build/swc/install-bindings'
import { installCodeFrameSupport } from '../server/lib/install-code-frame'
process.env.NEXT_IS_EXPORT_WORKER = 'true'
......@@ -336,6 +338,11 @@ async function exportPageImpl(
export async function exportPages(
input: ExportPagesInput
): Promise<ExportPagesResult> {
// Load native bindings in the worker process so that code frame rendering
// (which uses the native codeFrameColumns function) works during prerendering.
await installBindings()
installCodeFrameSupport()
const {
exportPaths,
dir,
......
import { codeFrameColumns } from '../../shared/lib/errors/code-frame'
import { bold, cyan, red, yellow } from '../picocolors'
import path from 'path'
......@@ -352,8 +353,6 @@ export function getFormattedDiagnostic(
message += reason + '\n'
if (!isLayoutOrPageError && diagnostic.file) {
const { codeFrameColumns } =
require('next/dist/compiled/babel/code-frame') as typeof import('next/dist/compiled/babel/code-frame')
const pos = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!)
const line = pos.line + 1
const character = pos.character + 1
......@@ -374,15 +373,16 @@ export function getFormattedDiagnostic(
'\n' +
message
message +=
'\n' +
codeFrameColumns(
diagnostic.file.getFullText(diagnostic.file.getSourceFile()),
{
start: { line: line, column: character },
},
{ forceColor: true }
)
const codeFrame = codeFrameColumns(
diagnostic.file.getFullText(diagnostic.file.getSourceFile()),
{
start: { line: line, column: character },
},
{ color: true }
)
if (codeFrame) {
message += '\n' + codeFrame
}
} else if (isLayoutOrPageError && appPath) {
message = cyan(appPath) + '\n' + message
}
......
......@@ -220,6 +220,10 @@ export async function verifyAndRunTypeScript({
if (shouldRunTypeCheck) {
const { runTypeCheck } =
require('./typescript/runTypeCheck') as typeof import('./typescript/runTypeCheck')
// Install native bindings so that code frame rendering works in the worker
const { installBindings } =
require('../build/swc/install-bindings') as typeof import('../build/swc/install-bindings')
await installBindings()
const tsPath = deps.resolved.get('typescript')!
const typescript = (await Promise.resolve(
......
:host {
/*
/*
* CAUTION: THIS IS A WORKAROUND!
* For now, we use @babel/code-frame to parse the code frame which does not support option to change the color.
* x-ref: https://github.com/babel/babel/blob/efa52324ff835b794c48080f14877b6caf32cd15/packages/babel-code-frame/src/defs.ts#L40-L54
* So, we do a workaround mapping to change the color matching the theme.
* The code frame renderer (next-code-frame) uses hardcoded ANSI colors that don't match
* our theme colors. We do a workaround mapping to change the ANSI color matching the theme.
*
* For example, in @babel/code-frame, the "keyword" is mapped to ANSI "cyan".
* We want the "keyword" to use the "syntax-keyword" color in the theme.
* So, we map the "cyan" to the "syntax-keyword" in the theme.
* next-code-frame color scheme:
* cyan (36m): keywords (const, function, return, etc.)
* yellow (33m): capitalized identifiers (Component names, types)
* magenta (35m): numbers, regex literals
* green (32m): strings
* gray (90m): comments, gutter
*/
/* cyan: keyword */
--color-ansi-cyan: var(--color-syntax-keyword);
/* yellow: capitalized, jsxIdentifier, punctuation */
/* yellow: capitalized identifiers */
--color-ansi-yellow: var(--color-syntax-function);
/* magenta: number, regex */
--color-ansi-magenta: var(--color-syntax-keyword);
......
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
import { codeFrameColumns } from '../../shared/lib/errors/code-frame'
import type { StackFrame } from '../../server/lib/parse-stack'
import { ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric } from '../../server/lib/source-maps'
......@@ -67,20 +67,20 @@ export function getOriginalCodeFrame(
source: string | null,
colors: boolean = process.stdout.isTTY
): string | null {
if (!source) {
if (!source || frame.line1 == null) {
return null
}
return codeFrameColumns(
source,
{
start: {
// 1-based, but -1 means start line without highlighting
line: frame.line1 ?? -1,
// 1-based, but 0 means whole line without column highlighting
column: frame.column1 ?? 0,
return (
codeFrameColumns(
source,
{
start: {
line: frame.line1,
column: frame.column1 ?? undefined,
},
},
},
{ forceColor: colors }
{ color: colors }
) ?? null
)
}
......@@ -429,6 +429,12 @@ export async function createHotReloaderTurbopack(
setBundlerFindSourceMapImplementation(
getSourceMapFromTurbopack.bind(null, project, projectPath)
)
// Set up code frame renderer using native bindings
const { installCodeFrameSupport } =
require('../lib/install-code-frame') as typeof import('../lib/install-code-frame')
installCodeFrameSupport()
opts.onDevServerCleanup?.(async () => {
setBundlerFindSourceMapImplementation(() => undefined)
await project.onExit()
......
/**
* Installs code frame rendering support by injecting the renderer into patch-error-inspect.
* This uses dependency injection to avoid hard dependencies on native bindings in runtime code.
*
* Should be called early in dev/build initialization, after native bindings are loaded.
*/
export function installCodeFrameSupport(): void {
const { setCodeFrameRenderer } =
require('../patch-error-inspect') as typeof import('../patch-error-inspect')
const { getOriginalCodeFrame } =
require('../../next-devtools/server/shared') as typeof import('../../next-devtools/server/shared')
setCodeFrameRenderer(getOriginalCodeFrame)
}
......@@ -1293,6 +1293,12 @@ export async function setupDevBundler(opts: SetupOpts) {
.relative(opts.dir, opts.pagesDir || opts.appDir || '')
.startsWith('src')
await installBindings(opts.nextConfig.experimental?.useWasmBinary)
// Set up code frame renderer for error formatting
const { installCodeFrameSupport } =
require('../install-code-frame') as typeof import('../install-code-frame')
installCodeFrameSupport()
const result = await startWatcher({
...opts,
isSrcDir,
......
......@@ -11,7 +11,7 @@ import {
sourceMapIgnoreListsEverything,
} from './lib/source-maps'
import { parseStack, type StackFrame } from './lib/parse-stack'
import { getOriginalCodeFrame } from '../next-devtools/server/shared'
import type { IgnorableStackFrame } from '../next-devtools/server/shared'
import { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'
import { dim, italic } from '../lib/picocolors'
......@@ -30,8 +30,29 @@ export function setBundlerFindSourceMapImplementation(
bundlerFindSourceMapPayload = findSourceMapImplementation
}
interface IgnorableStackFrame extends StackFrame {
ignored: boolean
// Code frame renderer - injected by dev/build to avoid hard dependency on native bindings
type CodeFrameRenderer = (
frame: IgnorableStackFrame,
source: string | null,
colors: boolean
) => string | null
let codeFrameRenderer: CodeFrameRenderer | undefined
export function setCodeFrameRenderer(renderer: CodeFrameRenderer): void {
codeFrameRenderer = renderer
}
function getOriginalCodeFrame(
frame: IgnorableStackFrame,
source: string | null,
colors: boolean = process.stdout.isTTY
): string | null {
if (!codeFrameRenderer) {
// No renderer available - gracefully degrade
return null
}
return codeFrameRenderer(frame, source, colors)
}
type SourceMapCache = Map<
......
import { getBindingsSync } from '../../../build/swc'
import type {
NapiCodeFrameLocation,
NapiCodeFrameOptions,
} from '../../../build/swc/generated-native'
/**
* Renders a code frame showing the location of an error in source code.
* Requires native bindings to be installed — throws otherwise.
*/
export function codeFrameColumns(
file: string,
location: NapiCodeFrameLocation,
options: NapiCodeFrameOptions = {}
): string | undefined {
// Default to the terminal width
if (options.maxWidth === undefined) {
options.maxWidth = process.stdout.columns
}
return getBindingsSync().codeFrameColumns(file, location, options)
}
export type { NapiCodeFrameLocation, NapiCodeFrameOptions }
......@@ -11,6 +11,7 @@ import { deobfuscateText } from '../magic-identifier'
import type { EntryKey } from './entry-key'
import * as Log from '../../../build/output/log'
import type { NextConfigComplete } from '../../../server/config-shared'
import { codeFrameColumns } from '../errors/code-frame'
type IssueKey = `${Issue['severity']}-${Issue['filePath']}-${string}-${string}`
export type IssuesMap = Map<IssueKey, Issue>
......@@ -134,24 +135,25 @@ export function formatIssue(issue: Issue) {
!isInternal(filePath)
) {
const { start, end } = source.range
const { codeFrameColumns } =
require('next/dist/compiled/babel/code-frame') as typeof import('next/dist/compiled/babel/code-frame')
message +=
codeFrameColumns(
source.source.content,
{
start: {
line: start.line + 1,
column: start.column + 1,
},
end: {
line: end.line + 1,
column: end.column + 1,
},
// TODO(lukesandberg): move codeFrame formatting into turbopack, it would be more efficient than passing the source back and forth
const frame = codeFrameColumns(
source.source.content,
{
start: {
line: start.line + 1,
column: start.column + 1,
},
end: {
line: end.line + 1,
column: end.column + 1,
},
{ forceColor: true }
).trim() + '\n\n'
},
{ color: true }
)
if (frame) {
message += frame.trimEnd() + '\n\n'
}
}
if (description) {
......
......@@ -990,7 +990,6 @@ export async function ncc_postcss_plugin_stub_for_cssnano_simple(task, opts) {
}
const babelCorePackages = {
'code-frame': 'next/dist/compiled/babel/code-frame',
'@babel/generator': 'next/dist/compiled/babel/generator',
'@babel/traverse': 'next/dist/compiled/babel/traverse',
'@babel/types': 'next/dist/compiled/babel/types',
......@@ -1006,12 +1005,6 @@ const babelCorePackages = {
'@babel/core/lib/transformation/plugin-pass':
'next/dist/compiled/babel/core-lib-plugin-pass',
}
externals['next/dist/compiled/babel/code-frame'] =
'next/dist/compiled/babel/code-frame'
externals['next/dist/compiled/babel-code-frame'] =
'next/dist/compiled/babel-code-frame'
Object.assign(externals, babelCorePackages)
export async function ncc_babel_bundle(task, opts) {
......@@ -1032,21 +1025,6 @@ export async function ncc_babel_bundle(task, opts) {
.target('src/compiled/babel')
}
export async function ncc_babel_code_frame(task, opts) {
const bundleExternals = {
...externals,
'next/dist/compiled/babel-packages': 'next/dist/compiled/babel-packages',
}
await task
.source('src/bundles/babel-code-frame/index.js')
.ncc({
packageName: '@babel/code-frame',
bundleName: 'babel-code-frame',
externals: bundleExternals,
})
.target('src/compiled/babel-code-frame')
}
export async function ncc_babel_bundle_packages(task, opts) {
const eslintParseFile = join(
dirname(require.resolve('@babel/eslint-parser')),
......@@ -2250,7 +2228,6 @@ export async function ncc(task, opts) {
'ncc_tty_browserify',
'ncc_vm_browserify',
'ncc_babel_bundle',
'ncc_babel_code_frame',
'ncc_bytes',
'ncc_ci_info',
'ncc_cli_select',
......
......@@ -528,10 +528,6 @@ declare module 'next/dist/compiled/async-sema' {
export = m
}
declare module 'next/dist/compiled/babel/code-frame' {
export * from '@babel/code-frame'
}
declare module 'next/dist/compiled/@next/font/dist/google' {
export * from '@next/font/google'
}
......
......@@ -1119,9 +1119,6 @@ importers:
specifier: ^0.34.5
version: 0.34.5
devDependencies:
'@babel/code-frame':
specifier: 7.26.2
version: 7.26.2
'@babel/core':
specifier: 7.26.10
version: 7.26.10
......@@ -1207,7 +1207,7 @@ describe('Cache Components Errors', () => {
TypeError: <module-function>().get is not a function
at CookiesReadingComponent (app/sync-cookies/page.tsx:18:36)
16 | async function CookiesReadingComponent() {
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync...
> 18 | const token = (cookies() as any).get('token')
| ^
19 |
......@@ -1225,7 +1225,7 @@ describe('Cache Components Errors', () => {
TypeError: <module-function>().get is not a function
at CookiesReadingComponent (webpack:///app/sync-cookies/page.tsx:18:36)
16 | async function CookiesReadingComponent() {
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync...
> 18 | const token = (cookies() as any).get('token')
| ^
19 |
......@@ -1246,7 +1246,7 @@ describe('Cache Components Errors', () => {
at a (app/sync-cookies/page.tsx:18:36)
at b (<anonymous>)
16 | async function CookiesReadingComponent() {
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync...
> 18 | const token = (cookies() as any).get('token')
| ^
19 |
......@@ -1541,7 +1541,7 @@ describe('Cache Components Errors', () => {
TypeError: <module-function>().get is not a function
at HeadersReadingComponent (app/sync-headers/page.tsx:18:40)
16 | async function HeadersReadingComponent() {
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync...
> 18 | const userAgent = (headers() as any).get('user-agent')
| ^
19 | return (
......@@ -1559,7 +1559,7 @@ describe('Cache Components Errors', () => {
TypeError: <module-function>().get is not a function
at HeadersReadingComponent (webpack:///app/sync-headers/page.tsx:18:40)
16 | async function HeadersReadingComponent() {
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync...
> 18 | const userAgent = (headers() as any).get('user-agent')
| ^
19 | return (
......@@ -1580,7 +1580,7 @@ describe('Cache Components Errors', () => {
at a (app/sync-headers/page.tsx:18:40)
at b (<anonymous>)
16 | async function HeadersReadingComponent() {
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync access
17 | // Cast to any as we removed UnsafeUnwrapped types, but still need to test with the sync...
> 18 | const userAgent = (headers() as any).get('user-agent')
| ^
19 | return (
......
......@@ -849,7 +849,9 @@ describe('app-dir - server source maps', () => {
"description": "ignore-listed frames",
"environmentLabel": null,
"label": "Console Error",
"source": "internal-pkg/sourcemapped.ts (9:13) @ runSetOfSets",
"source": "app/ssr-anonymous-stack-frame-sandwich/page.js (7:29) @ Page
> 7 | runHiddenSetOfSetsInternal('ssr-anonymous-stack-frame-sandwich: internal')
| ^",
"stack": [
"<unknown> internal-pkg/sourcemapped.ts (18:43)",
"<unknown> internal-pkg/sourcemapped.ts (11:7)",
......
......@@ -175,8 +175,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/compiled/@opentelemetry/api/index.js",
"/node_modules/next/dist/compiled/async-retry/index.js",
"/node_modules/next/dist/compiled/async-sema/index.js",
"/node_modules/next/dist/compiled/babel-code-frame/index.js",
"/node_modules/next/dist/compiled/babel/code-frame.js",
"/node_modules/next/dist/compiled/busboy/index.js",
"/node_modules/next/dist/compiled/bytes/index.js",
"/node_modules/next/dist/compiled/ci-info/index.js",
......@@ -354,7 +352,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/wait.js",
"/node_modules/next/dist/lib/with-promise-cache.js",
"/node_modules/next/dist/lib/worker.js",
"/node_modules/next/dist/next-devtools/server/shared.js",
"/node_modules/next/dist/server/*",
"/node_modules/next/dist/shared/*",
"/node_modules/next/dist/telemetry/anonymous-meta.js",
......@@ -451,8 +448,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/client-only/index.js",
"/node_modules/next/dist/client/components/app-router-headers.js",
"/node_modules/next/dist/compiled/@opentelemetry/api/index.js",
"/node_modules/next/dist/compiled/babel-code-frame/index.js",
"/node_modules/next/dist/compiled/babel/code-frame.js",
"/node_modules/next/dist/compiled/next-server/server.runtime.prod.js",
"/node_modules/next/dist/compiled/source-map/source-map.js",
"/node_modules/next/dist/compiled/stacktrace-parser/stack-trace-parser.cjs.js",
......
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