Unverified Commit a21f4028 authored by Sam Selikoff's avatar Sam Selikoff Committed by GitHub

Merge branch 'canary' into feat/staletime-segment-config

parents bf73658e 50d61f93
......@@ -39,6 +39,17 @@ The main Next.js framework lives in `packages/next/`. This is what gets publishe
- `packages/font/` - `next/font` implementation
- `packages/third-parties/` - Third-party script integrations
### README files
Before editing or creating files in any subdirectory (e.g., `packages/*`, `crates/*`), read all `README.md` files in the directory path from the repo root up to and including the target file's directory. This helps identify any local patterns, conventions, and documentation.
**Example:** Before editing `turbopack/crates/turbopack-ecmascript-runtime/js/src/nodejs/runtime/runtime-base.ts`, read:
- `turbopack/README.md` (if exists)
- `turbopack/crates/README.md` (if exists)
- `turbopack/crates/turbopack-ecmascript-runtime/README.md` (if exists)
- `turbopack/crates/turbopack-ecmascript-runtime/js/README.md` (if exists - closest to target file)
## Build Commands
```bash
......
......@@ -166,6 +166,51 @@ pub struct DebugBuildPaths {
pub pages: Vec<RcStr>,
}
/// Target for HMR operations - client-side (browser) or server-side (Node.js).
#[derive(
Debug,
Default,
Copy,
Clone,
TaskInput,
PartialEq,
Eq,
Hash,
TraceRawVcs,
NonLocalValue,
Encode,
Decode,
)]
pub enum HmrTarget {
#[default]
Client,
Server,
}
impl std::fmt::Display for HmrTarget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HmrTarget::Client => write!(f, "client"),
HmrTarget::Server => write!(f, "server"),
}
}
}
impl std::str::FromStr for HmrTarget {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"client" => Ok(HmrTarget::Client),
"server" => Ok(HmrTarget::Server),
_ => Err(format!(
"Invalid HMR target: '{}'. Expected 'client' or 'server'",
s
)),
}
}
}
/// Pre-converted route keys from debug build paths for O(1) lookups.
struct DebugBuildPathsRouteKeys {
app: FxHashSet<RcStr>,
......@@ -745,10 +790,10 @@ impl ProjectContainer {
self.project().entrypoints()
}
/// See [Project::hmr_identifiers].
/// See [Project::hmr_chunk_names].
#[turbo_tasks::function]
pub fn hmr_identifiers(self: Vc<Self>) -> Vc<Vec<RcStr>> {
self.project().hmr_identifiers()
pub fn hmr_chunk_names(self: Vc<Self>, target: HmrTarget) -> Vc<Vec<RcStr>> {
self.project().hmr_chunk_names(target)
}
/// Gets a source map for a particular `file_path`. If `dev` mode is disabled, this will always
......@@ -2050,19 +2095,39 @@ impl Project {
.await
}
/// Returns the root path for HMR content based on the target.
/// Client uses client_relative_path, Server uses node_root.
#[turbo_tasks::function]
async fn hmr_root_path(self: Vc<Self>, target: HmrTarget) -> Result<Vc<FileSystemPath>> {
Ok(match target {
HmrTarget::Client => self.client_relative_path(),
HmrTarget::Server => self.node_root(),
})
}
/// Get HMR content by chunk_name for the specified target.
#[turbo_tasks::function]
async fn hmr_content(self: Vc<Self>, identifier: RcStr) -> Result<Vc<OptionVersionedContent>> {
async fn hmr_content(
self: Vc<Self>,
chunk_name: RcStr,
target: HmrTarget,
) -> Result<Vc<OptionVersionedContent>> {
if let Some(map) = self.await?.versioned_content_map {
let content = map.get(self.client_relative_path().await?.join(&identifier)?);
let content = map.get(self.hmr_root_path(target).await?.join(&chunk_name)?);
Ok(content)
} else {
bail!("must be in dev mode to hmr")
}
}
/// Get HMR version for the specified target.
#[turbo_tasks::function]
async fn hmr_version(self: Vc<Self>, identifier: RcStr) -> Result<Vc<Box<dyn Version>>> {
let content = self.hmr_content(identifier).await?;
async fn hmr_version(
self: Vc<Self>,
chunk_name: RcStr,
target: HmrTarget,
) -> Result<Vc<Box<dyn Version>>> {
let content = self.hmr_content(chunk_name, target).await?;
if let Some(content) = &*content {
Ok(content.version())
} else {
......@@ -2070,15 +2135,16 @@ impl Project {
}
}
/// Get the version state for a session. Initialized with the first seen
/// Get the version state for an HMR session. Initialized with the first seen
/// version in that session.
#[turbo_tasks::function]
pub async fn hmr_version_state(
self: Vc<Self>,
identifier: RcStr,
chunk_name: RcStr,
target: HmrTarget,
session: TransientInstance<()>,
) -> Result<Vc<VersionState>> {
let version = self.hmr_version(identifier);
let version = self.hmr_version(chunk_name, target);
// The session argument is important to avoid caching this function between
// sessions.
......@@ -2099,15 +2165,16 @@ impl Project {
}
/// Emits opaque HMR events whenever a change is detected in the chunk group
/// internally known as `identifier`.
/// internally known as `chunk_name` for the specified target.
#[turbo_tasks::function]
pub async fn hmr_update(
self: Vc<Self>,
identifier: RcStr,
chunk_name: RcStr,
target: HmrTarget,
from: Vc<VersionState>,
) -> Result<Vc<Update>> {
let from = from.get();
let content = self.hmr_content(identifier).await?;
let content = self.hmr_content(chunk_name, target).await?;
if let Some(content) = *content {
Ok(content.update(from))
} else {
......@@ -2115,12 +2182,13 @@ impl Project {
}
}
/// Gets a list of all HMR identifiers that can be subscribed to. This is
/// only needed for testing purposes and isn't used in real apps.
/// Gets a list of all HMR chunk names that can be subscribed to for the
/// specified target. This is only needed for testing purposes and isn't
/// used in real apps.
#[turbo_tasks::function]
pub async fn hmr_identifiers(self: Vc<Self>) -> Result<Vc<Vec<RcStr>>> {
pub async fn hmr_chunk_names(self: Vc<Self>, target: HmrTarget) -> Result<Vc<Vec<RcStr>>> {
if let Some(map) = self.await?.versioned_content_map {
Ok(map.keys_in_path(self.client_relative_path().owned().await?))
Ok(map.keys_in_path(self.hmr_root_path(target).owned().await?))
} else {
bail!("must be in dev mode to hmr")
}
......
......@@ -8,7 +8,7 @@ use std::{str::FromStr, time::Instant};
use anyhow::{Context, Result};
use futures_util::{StreamExt, TryStreamExt};
use next_api::{
project::{ProjectContainer, ProjectOptions},
project::{HmrTarget, ProjectContainer, ProjectOptions},
route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk},
};
use turbo_rcstr::{RcStr, rcstr};
......@@ -257,7 +257,7 @@ async fn hmr(
tracing::info!("HMR...");
let session = TransientInstance::new(());
let idents = tt
.run(async move { project.hmr_identifiers().await })
.run(async move { project.hmr_chunk_names(HmrTarget::Client).await })
.await?;
let start = Instant::now();
for ident in idents {
......@@ -270,8 +270,10 @@ async fn hmr(
let session = session.clone();
async move {
let project = project.project();
let state = project.hmr_version_state(ident.clone(), session);
project.hmr_update(ident.clone(), state).await?;
let state = project.hmr_version_state(ident.clone(), HmrTarget::Client, session);
project
.hmr_update(ident.clone(), HmrTarget::Client, state)
.await?;
Ok(Vc::<()>::cell(()))
}
});
......
......@@ -18,7 +18,7 @@ use next_api::{
RouteOperation,
},
project::{
DebugBuildPaths, DefineEnv, DraftModeOptions, PartialProjectOptions, Project,
DebugBuildPaths, DefineEnv, DraftModeOptions, HmrTarget, PartialProjectOptions, Project,
ProjectContainer, ProjectOptions, WatchOptions,
},
route::Endpoint,
......@@ -82,7 +82,7 @@ use crate::{
/// Used by [`benchmark_file_io`]. This is a noisy benchmark, so set the
/// threshold high.
const SLOW_FILESYSTEM_THRESHOLD: Duration = Duration::from_millis(100);
const SLOW_FILESYSTEM_THRESHOLD: Duration = Duration::from_millis(200);
static SOURCE_MAP_PREFIX: Lazy<String> = Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///"));
static SOURCE_MAP_PREFIX_PROJECT: Lazy<String> =
Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///[{PROJECT_FILESYSTEM_NAME}]/"));
......@@ -602,8 +602,8 @@ impl CompilationEvent for SlowFilesystemEvent {
fn message(&self) -> String {
format!(
"Slow filesystem detected. The benchmark took {}ms. If {} is a network drive, \
consider moving it to a local folder. If you have an antivirus enabled, consider \
excluding your project directory.",
consider moving it to a local folder.\n\
See more: https://nextjs.org/docs/app/guides/local-development",
self.duration_ms, self.directory
)
}
......@@ -1205,13 +1205,24 @@ struct HmrUpdateWithIssues {
effects: Arc<Effects>,
}
#[turbo_tasks::function(operation)]
fn project_hmr_update_operation(
project: ResolvedVc<Project>,
chunk_name: RcStr,
target: HmrTarget,
state: ResolvedVc<VersionState>,
) -> Vc<Update> {
project.hmr_update(chunk_name, target, *state)
}
#[turbo_tasks::function(operation)]
async fn hmr_update_with_issues_operation(
project: ResolvedVc<Project>,
identifier: RcStr,
chunk_name: RcStr,
state: ResolvedVc<VersionState>,
target: HmrTarget,
) -> Result<Vc<HmrUpdateWithIssues>> {
let update_op = project_hmr_update_operation(project, identifier, state);
let update_op = project_hmr_update_operation(project, chunk_name, target, state);
let update = update_op.read_strongly_consistent().await?;
let issues = get_issues(update_op, NEXT_ISSUE_FILTER).await?;
let diagnostics = get_diagnostics(update_op).await?;
......@@ -1225,42 +1236,42 @@ async fn hmr_update_with_issues_operation(
.cell())
}
#[turbo_tasks::function(operation)]
fn project_hmr_update_operation(
project: ResolvedVc<Project>,
identifier: RcStr,
state: ResolvedVc<VersionState>,
) -> Vc<Update> {
project.hmr_update(identifier, *state)
}
#[tracing::instrument(level = "info", name = "get HMR events", skip(project, func))]
#[tracing::instrument(level = "info", name = "get HMR events", skip(project, func), fields(target = %target))]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_events(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
identifier: RcStr,
chunk_name: RcStr,
target: String,
func: JsFunction,
) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container;
let session = TransientInstance::new(());
subscribe(
project.turbopack_ctx.clone(),
func,
{
let outer_identifier = identifier.clone();
let outer_chunk_name = chunk_name.clone();
let session = session.clone();
move || {
let identifier: RcStr = outer_identifier.clone();
let chunk_name: RcStr = outer_chunk_name.clone();
let session = session.clone();
async move {
let project = container.project().to_resolved().await?;
let state = project
.hmr_version_state(identifier.clone(), session)
.hmr_version_state(chunk_name.clone(), hmr_target, session)
.to_resolved()
.await?;
let update_op =
hmr_update_with_issues_operation(project, identifier.clone(), state);
let update_op = hmr_update_with_issues_operation(
project,
chunk_name.clone(),
state,
hmr_target,
);
let update = update_op.read_strongly_consistent().await?;
let HmrUpdateWithIssues {
update,
......@@ -1295,7 +1306,7 @@ pub fn project_hmr_events(
.collect::<Vec<_>>();
let identifier = ResourceIdentifier {
path: identifier.clone(),
path: chunk_name.clone(),
headers: None,
};
let update = match update.as_deref() {
......@@ -1320,29 +1331,38 @@ pub fn project_hmr_events(
}
#[napi(object)]
struct HmrIdentifiers {
pub identifiers: Vec<RcStr>,
struct HmrChunkNames {
pub chunk_names: Vec<RcStr>,
}
#[turbo_tasks::value(serialization = "none")]
struct HmrIdentifiersWithIssues {
identifiers: ReadRef<Vec<RcStr>>,
struct HmrChunkNamesWithIssues {
chunk_names: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>,
}
#[turbo_tasks::function(operation)]
async fn get_hmr_identifiers_with_issues_operation(
fn project_hmr_chunk_names_operation(
container: ResolvedVc<ProjectContainer>,
target: HmrTarget,
) -> Vc<Vec<RcStr>> {
container.hmr_chunk_names(target)
}
#[turbo_tasks::function(operation)]
async fn get_hmr_chunk_names_with_issues_operation(
container: ResolvedVc<ProjectContainer>,
) -> Result<Vc<HmrIdentifiersWithIssues>> {
let hmr_identifiers_op = project_container_hmr_identifiers_operation(container);
let hmr_identifiers = hmr_identifiers_op.read_strongly_consistent().await?;
let issues = get_issues(hmr_identifiers_op, NEXT_ISSUE_FILTER).await?;
let diagnostics = get_diagnostics(hmr_identifiers_op).await?;
let effects = Arc::new(get_effects(hmr_identifiers_op).await?);
Ok(HmrIdentifiersWithIssues {
identifiers: hmr_identifiers,
target: HmrTarget,
) -> Result<Vc<HmrChunkNamesWithIssues>> {
let hmr_chunk_names_op = project_hmr_chunk_names_operation(container, target);
let hmr_chunk_names = hmr_chunk_names_op.read_strongly_consistent().await?;
let issues = get_issues(hmr_chunk_names_op, NEXT_ISSUE_FILTER).await?;
let diagnostics = get_diagnostics(hmr_chunk_names_op).await?;
let effects = Arc::new(get_effects(hmr_chunk_names_op).await?);
Ok(HmrChunkNamesWithIssues {
chunk_names: hmr_chunk_names,
issues,
diagnostics,
effects,
......@@ -1350,44 +1370,42 @@ async fn get_hmr_identifiers_with_issues_operation(
.cell())
}
#[turbo_tasks::function(operation)]
fn project_container_hmr_identifiers_operation(
container: ResolvedVc<ProjectContainer>,
) -> Vc<Vec<RcStr>> {
container.hmr_identifiers()
}
#[tracing::instrument(level = "info", name = "get HMR identifiers", skip_all)]
#[tracing::instrument(level = "info", name = "get HMR chunk names", skip(project, func), fields(target = %target))]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_identifiers_subscribe(
pub fn project_hmr_chunk_names_subscribe(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
target: String,
func: JsFunction,
) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container;
subscribe(
project.turbopack_ctx.clone(),
func,
move || async move {
let hmr_identifiers_with_issues_op =
get_hmr_identifiers_with_issues_operation(container);
let HmrIdentifiersWithIssues {
identifiers,
let hmr_chunk_names_with_issues_op =
get_hmr_chunk_names_with_issues_operation(container, hmr_target);
let HmrChunkNamesWithIssues {
chunk_names,
issues,
diagnostics,
effects,
} = &*hmr_identifiers_with_issues_op
} = &*hmr_chunk_names_with_issues_op
.read_strongly_consistent()
.await?;
effects.apply().await?;
Ok((identifiers.clone(), issues.clone(), diagnostics.clone()))
Ok((chunk_names.clone(), issues.clone(), diagnostics.clone()))
},
move |ctx| {
let (identifiers, issues, diagnostics) = ctx.value;
let (chunk_names, issues, diagnostics) = ctx.value;
Ok(vec![TurbopackResult {
result: HmrIdentifiers {
identifiers: ReadRef::into_owned(identifiers),
result: HmrChunkNames {
chunk_names: ReadRef::into_owned(chunk_names),
},
issues: issues
.iter()
......
......@@ -15,5 +15,5 @@
"registry": "https://registry.npmjs.org/"
}
},
"version": "16.2.0-canary.33"
"version": "16.2.0-canary.35"
}
\ No newline at end of file
{
"name": "create-next-app",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"keywords": [
"react",
"next",
......
{
"name": "eslint-config-next",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"description": "ESLint configuration used by Next.js.",
"license": "MIT",
"repository": {
......@@ -12,7 +12,7 @@
"dist"
],
"dependencies": {
"@next/eslint-plugin-next": "16.2.0-canary.33",
"@next/eslint-plugin-next": "16.2.0-canary.35",
"eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.32.0",
......
{
"name": "@next/eslint-plugin-internal",
"private": true,
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"description": "ESLint plugin for working on Next.js.",
"exports": {
".": "./src/eslint-plugin-internal.js"
......
{
"name": "@next/eslint-plugin-next",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"description": "ESLint plugin for Next.js.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
......
{
"name": "@next/font",
"private": true,
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"repository": {
"url": "vercel/next.js",
"directory": "packages/font"
......
{
"name": "@next/bundle-analyzer",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"main": "index.js",
"types": "index.d.ts",
"license": "MIT",
......
{
"name": "@next/codemod",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"license": "MIT",
"repository": {
"type": "git",
......
{
"name": "@next/env",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"keywords": [
"react",
"next",
......
{
"name": "@next/mdx",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"main": "index.js",
"license": "MIT",
"repository": {
......
{
"name": "@next/plugin-storybook",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-plugin-storybook"
......
{
"name": "@next/polyfill-module",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)",
"main": "dist/polyfill-module.js",
"license": "MIT",
......
{
"name": "@next/polyfill-nomodule",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"description": "A polyfill for non-dead, nomodule browsers.",
"main": "dist/polyfill-nomodule.js",
"license": "MIT",
......
{
"name": "@next/routing",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"keywords": [
"react",
"next",
......
{
"name": "next-rspack",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-rspack"
......
{
"name": "@next/swc",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"private": true,
"files": [
"native/"
......
{
"name": "next",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"description": "The React Framework",
"main": "./dist/server/next.js",
"license": "MIT",
......@@ -97,7 +97,7 @@
]
},
"dependencies": {
"@next/env": "16.2.0-canary.33",
"@next/env": "16.2.0-canary.35",
"@swc/helpers": "0.5.15",
"baseline-browser-mapping": "^2.9.19",
"caniuse-lite": "^1.0.30001579",
......@@ -162,11 +162,11 @@
"@modelcontextprotocol/sdk": "1.18.1",
"@mswjs/interceptors": "0.23.0",
"@napi-rs/triples": "1.2.0",
"@next/font": "16.2.0-canary.33",
"@next/polyfill-module": "16.2.0-canary.33",
"@next/polyfill-nomodule": "16.2.0-canary.33",
"@next/react-refresh-utils": "16.2.0-canary.33",
"@next/swc": "16.2.0-canary.33",
"@next/font": "16.2.0-canary.35",
"@next/polyfill-module": "16.2.0-canary.35",
"@next/polyfill-nomodule": "16.2.0-canary.35",
"@next/react-refresh-utils": "16.2.0-canary.35",
"@next/swc": "16.2.0-canary.35",
"@opentelemetry/api": "1.6.0",
"@playwright/test": "1.51.1",
"@rspack/core": "1.6.7",
......
......@@ -314,14 +314,16 @@ export declare function projectEntrypointsSubscribe(
): { __napiType: 'RootTask' }
export declare function projectHmrEvents(
project: { __napiType: 'Project' },
identifier: RcStr,
chunkName: RcStr,
target: string,
func: (...args: any[]) => any
): { __napiType: 'RootTask' }
export interface HmrIdentifiers {
identifiers: Array<RcStr>
export interface HmrChunkNames {
chunkNames: Array<RcStr>
}
export declare function projectHmrIdentifiersSubscribe(
export declare function projectHmrChunkNamesSubscribe(
project: { __napiType: 'Project' },
target: string,
func: (...args: any[]) => any
): { __napiType: 'RootTask' }
export interface NapiUpdateMessage {
......
......@@ -27,8 +27,9 @@ import type {
CompilationEvent,
DefineEnv,
Endpoint,
HmrIdentifiers,
HmrChunkNames,
Lockfile,
NodeJsHmrUpdate,
PartialProjectOptions,
Project,
ProjectOptions,
......@@ -43,6 +44,11 @@ import type {
} from './types'
import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error'
export enum HmrTarget {
Client = 'client',
Server = 'server',
}
type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & {
default?(): Promise<typeof import('./generated-wasm')>
......@@ -735,17 +741,39 @@ function bindingToApi(
})()
}
hmrEvents(identifier: string) {
return subscribe<TurbopackResult<Update>>(true, async (callback) =>
binding.projectHmrEvents(this._nativeProject, identifier, callback)
hmrEvents(
chunkName: string,
target: HmrTarget.Client
): AsyncIterableIterator<TurbopackResult<Update>>
hmrEvents(
chunkName: string,
target: HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrEvents(chunkName: string, target: HmrTarget.Client | HmrTarget.Server) {
return subscribe(true, async (callback) =>
binding.projectHmrEvents(
this._nativeProject,
chunkName,
target,
callback
)
)
}
hmrIdentifiersSubscribe() {
return subscribe<TurbopackResult<HmrIdentifiers>>(
/**
* Subscribe to the list of output chunk paths that can receive HMR updates.
* Chunk paths are output file paths like "server/chunks/ssr/..._.js" for server
* or "_next/static/chunks/app/page.js" for client.
*/
hmrChunkNamesSubscribe(target: HmrTarget) {
return subscribe<TurbopackResult<HmrChunkNames>>(
false,
async (callback) =>
binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback)
binding.projectHmrChunkNamesSubscribe(
this._nativeProject,
target,
callback
)
)
}
......
......@@ -195,8 +195,30 @@ interface PartialUpdate extends BaseUpdate {
export type Update = IssuesUpdate | PartialUpdate
export interface HmrIdentifiers {
identifiers: string[]
/**
* IMPORTANT: This type is duplicated in:
* turbopack/crates/turbopack-ecmascript-runtime/js/src/nodejs/hmr-types.d.ts
*
* The runtime file cannot import from this ES module without triggering module semantics,
* so we maintain a copy there. Please keep both definitions in sync.
*/
export interface NodeJsPartialHmrUpdate extends BaseUpdate {
type: 'partial'
instruction: {
type: 'EcmascriptMergedUpdate'
entries: Record<
string,
{ code: string; url: string; map?: string | undefined }
>
chunks?: Record<string, { type: 'partial' }>
}
}
export type NodeJsHmrUpdate = IssuesUpdate | NodeJsPartialHmrUpdate
export interface HmrChunkNames {
/** Relative paths to output chunks that can receive HMR updates (e.g., "server/chunks/ssr/..._.js") */
chunkNames: string[]
}
/** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/crates/next-napi-bindings/src/next_api/project.rs#L824-L833 */
......@@ -246,11 +268,18 @@ export interface Project {
TurbopackResult<RawEntrypoints | {}>
>
hmrEvents(identifier: string): AsyncIterableIterator<TurbopackResult<Update>>
hmrIdentifiersSubscribe(): AsyncIterableIterator<
TurbopackResult<HmrIdentifiers>
>
hmrEvents(
identifier: string,
target: import('./index').HmrTarget.Client
): AsyncIterableIterator<TurbopackResult<Update>>
hmrEvents(
identifier: string,
target: import('./index').HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrChunkNamesSubscribe(
target: import('./index').HmrTarget
): AsyncIterableIterator<TurbopackResult<HmrChunkNames>>
getSourceForAsset(filePath: string): Promise<string | null>
......
......@@ -92,7 +92,10 @@ import { createServerInsertedHTML } from './server-inserted-html'
import { getRequiredScripts } from './required-scripts'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import { makeGetServerInsertedHTML } from './make-get-server-inserted-html'
import { walkTreeWithFlightRouterState } from './walk-tree-with-flight-router-state'
import {
walkTreeWithFlightRouterState,
createFullTreeFlightDataForNavigation,
} from './walk-tree-with-flight-router-state'
import { createComponentTree, getRootParams } from './create-component-tree'
import { getAssetQueryString } from './get-asset-query-string'
import {
......@@ -533,6 +536,14 @@ async function generateDynamicRSCPayload(
if (!options?.skipPageRendering) {
const preloadCallbacks: PreloadCallbacks = []
// If we're performing instant validation, we need to render the whole tree,
// without skipping shared layouts.
const needsFullTree =
process.env.NODE_ENV === 'development' &&
ctx.renderOpts.cacheComponents &&
!options?.actionResult && // Only for navigations
(await anySegmentNeedsInstantValidation(loaderTree))
const { Viewport, Metadata, MetadataOutlet } = createMetadataComponents({
tree: loaderTree,
parsedQuery: query,
......@@ -543,38 +554,50 @@ async function generateDynamicRSCPayload(
serveStreamingMetadata,
})
const rscHead = createElement(
Fragment,
{
key: flightDataPathHeadKey,
},
createElement(NonIndex, {
createElement,
pagePath: ctx.pagePath,
statusCode: ctx.res.statusCode,
isPossibleServerAction: ctx.isPossibleServerAction,
}),
createElement(Viewport, {
key: getFlightViewportKey(requestId),
}),
createElement(Metadata, {
key: getFlightMetadataKey(requestId),
})
)
flightData = (
await walkTreeWithFlightRouterState({
ctx,
loaderTreeToFilter: loaderTree,
parentParams: {},
flightRouterState,
// For flight, render metadata inside leaf page
rscHead: createElement(
Fragment,
{
key: flightDataPathHeadKey,
},
createElement(NonIndex, {
createElement,
pagePath: ctx.pagePath,
statusCode: ctx.res.statusCode,
isPossibleServerAction: ctx.isPossibleServerAction,
}),
createElement(Viewport, {
key: getFlightViewportKey(requestId),
}),
createElement(Metadata, {
key: getFlightMetadataKey(requestId),
needsFullTree
? await createFullTreeFlightDataForNavigation({
ctx,
loaderTree,
rscHead,
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
preloadCallbacks,
MetadataOutlet,
})
: await walkTreeWithFlightRouterState({
ctx,
loaderTreeToFilter: loaderTree,
parentParams: {},
flightRouterState,
rscHead,
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
preloadCallbacks,
MetadataOutlet,
})
),
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
preloadCallbacks,
MetadataOutlet,
})
).map((path) => path.slice(1)) // remove the '' (root) segment
}
......@@ -829,7 +852,12 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
renderOpts,
requestId,
workStore,
componentMod: { createElement },
componentMod: {
createElement,
routeModule: {
userland: { loaderTree },
},
},
url,
} = ctx
......@@ -857,11 +885,13 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
onFlightDataRenderError
)
// We only validate RSC requests if it is for HMR refreshes since we know we
// will render all the layouts necessary to perform the validation.
// We validate RSC requests for HMR refreshes and client navigations when
// instant configs exist, since we render all the layouts necessary to perform
// the validation in those cases.
const shouldValidate =
!isBypassingCachesInDev(renderOpts, initialRequestStore) &&
initialRequestStore.isHmrRefresh === true
(initialRequestStore.isHmrRefresh === true ||
(await anySegmentNeedsInstantValidation(loaderTree)))
const getPayload = async (requestStore: RequestStore) => {
const payload: RSCPayload &
......
import type { NodeJsPartialHmrUpdate } from '../../build/swc/types'
// eslint-disable-next-line import/no-extraneous-dependencies
export {
createTemporaryReferenceSet,
......@@ -66,7 +68,11 @@ if (process.env.NODE_ENV === 'development') {
declare global {
var __next__clear_chunk_cache__: (() => void) | null | undefined
var __turbopack_clear_chunk_cache__: () => void | null | undefined
var __turbopack_server_hmr_apply__:
| ((update: NodeJsPartialHmrUpdate) => boolean)
| undefined
}
// hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`
// into globalThis from this file which is bundled.
if (process.env.TURBOPACK) {
......
......@@ -2,6 +2,10 @@ import { getLayoutOrPageModule } from '../../lib/app-dir-module'
import type { LoaderTree } from '../../lib/app-dir-module'
import { parseLoaderTree } from '../../../shared/lib/router/utils/parse-loader-tree'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'
import {
workAsyncStorage,
type WorkStore,
} from '../work-async-storage.external'
export async function anySegmentHasRuntimePrefetchEnabled(
tree: LoaderTree
......@@ -70,53 +74,90 @@ type FoundSegmentWithConfig = {
config: NonNullable<AppSegmentConfig['unstable_instant']>
}
export async function anySegmentNeedsInstantValidation(
rootTree: LoaderTree
): Promise<boolean> {
const segments = await findSegmentsWithInstantConfig(rootTree)
// Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`.
// (If there's only `false`, there's no need to run validation).
// If any segment has `unstable_disableValidation`, we skip validation for the whole tree.
let needsValidation = false
for (const { config } of segments) {
if (typeof config === 'object') {
if (config.unstable_disableValidation) {
return false
/**
* Checks if any segments in the loader tree have `instant` configs that need validating.
* NOTE: Client navigations call this multiple times, so we cache it.
* */
export const anySegmentNeedsInstantValidation = cacheScopedToWorkStore(
async (rootTree: LoaderTree): Promise<boolean> => {
const segments = await findSegmentsWithInstantConfig(rootTree)
// Check if there's any configs with `prefetch: 'static'` or `mode: 'instant'`.
// (If there's only `false`, there's no need to run validation).
// If any segment has `unstable_disableValidation`, we skip validation for the whole tree.
let needsValidation = false
for (const { config } of segments) {
if (typeof config === 'object') {
if (config.unstable_disableValidation) {
return false
}
// do not short-circuit, some other segment might still have `unstable_disableValidation`
needsValidation = true
}
// do not short-circuit, some other segment might still have `unstable_disableValidation`
needsValidation = true
}
return needsValidation
}
return needsValidation
}
)
export const findSegmentsWithInstantConfig = cacheScopedToWorkStore(
async (rootTree: LoaderTree): Promise<FoundSegmentWithConfig[]> => {
const results: FoundSegmentWithConfig[] = []
async function visit(tree: LoaderTree, path: string[]): Promise<void> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
if (instantConfig !== undefined) {
results.push({
path,
config: instantConfig,
})
}
export async function findSegmentsWithInstantConfig(
rootTree: LoaderTree
): Promise<FoundSegmentWithConfig[]> {
const results: FoundSegmentWithConfig[] = []
async function visit(tree: LoaderTree, path: string[]): Promise<void> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const instantConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).unstable_instant
: undefined
if (instantConfig !== undefined) {
results.push({
path,
config: instantConfig,
})
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const childTree = parallelRoutes[parallelRouteKey]
await visit(childTree, [...path, parallelRouteKey])
}
}
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const childTree = parallelRoutes[parallelRouteKey]
await visit(childTree, [...path, parallelRouteKey])
}
await visit(rootTree, [])
return results
}
)
/**
* A simple cache wrapper for 1-argument functions.
* The cache will live as long as the current WorkStore,
* i.e. it's scoped to a single request.
*/
function cacheScopedToWorkStore<TArg extends WeakKey, TRes>(
func: (arg: TArg) => TRes
): (arg: TArg) => TRes {
const resultsPerWorkStore = new WeakMap<WorkStore, WeakMap<TArg, TRes>>()
return (arg: TArg): TRes => {
const workStore = workAsyncStorage.getStore()
if (!workStore) {
// No caching.
return func(arg)
}
await visit(rootTree, [])
return results
let results = resultsPerWorkStore.get(workStore)
if (results && results.has(arg)) {
return results.get(arg)!
}
const result = func(arg)
if (!results) {
results = new WeakMap()
resultsPerWorkStore.set(workStore, results)
}
results.set(arg, result)
return result
}
}
......@@ -294,6 +294,70 @@ export async function walkTreeWithFlightRouterState({
return paths
}
/**
* A simplified version of `walkTreeWithFlightRouterState` that doesn't skip any layouts
* but returns a result of the same shape.
* Intended to be used for instant validation, where we need the complete tree.
*/
export async function createFullTreeFlightDataForNavigation({
loaderTree,
rscHead,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
ctx,
preloadCallbacks,
MetadataOutlet,
}: {
loaderTree: LoaderTree
flightRouterState?: FlightRouterState
rscHead: HeadData
injectedCSS: Set<string>
injectedJS: Set<string>
injectedFontPreloadTags: Set<string>
ctx: AppRenderContext
preloadCallbacks: PreloadCallbacks
MetadataOutlet: React.ComponentType
}): Promise<[rootSegment: FlightDataPath]> {
const {
renderOpts: { experimental },
query,
getDynamicParamFromSegment,
} = ctx
const routerState = createFlightRouterStateFromLoaderTree(
loaderTree,
getDynamicParamFromSegment,
query
)
const rootSegment = routerState[0]
const seedData = await createComponentTree({
ctx,
loaderTree,
parentParams: {},
injectedCSS,
injectedJS,
injectedFontPreloadTags,
rootLayoutIncluded: false,
preloadCallbacks,
authInterrupts: experimental.authInterrupts,
MetadataOutlet,
})
return [
[
// TODO: app-render slices this Segment off.
// why is that valid, and why are we including it in the first place?
rootSegment,
routerState,
seedData,
rscHead,
false,
] satisfies FlightDataSegment,
]
}
/*
* This function is used to determine if an existing segment can be overridden
* by the incoming segment.
......
......@@ -24,8 +24,10 @@ import type {
TurbopackResult,
Project,
Entrypoints,
NodeJsHmrUpdate,
NodeJsPartialHmrUpdate,
} from '../../build/swc/types'
import { createDefineEnv, getBindingsSync } from '../../build/swc'
import { createDefineEnv, getBindingsSync, HmrTarget } from '../../build/swc'
import * as Log from '../../build/output/log'
import { BLOCKED_PAGES } from '../../shared/lib/constants'
import {
......@@ -144,6 +146,98 @@ const sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random())
declare const __next__clear_chunk_cache__: (() => void) | null | undefined
declare const __turbopack_server_hmr_apply__:
| ((update: NodeJsPartialHmrUpdate) => boolean)
| undefined
function setupServerHmr(project: Project) {
const serverHmrSubscriptions = new Map<
string,
AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
>()
/**
* Subscribe to HMR updates for a server chunk.
* @param chunkPath - Server chunk output path (e.g., "server/chunks/ssr/..._.js")
*/
function subscribeToServerHmr(chunkPath: string) {
if (serverHmrSubscriptions.has(chunkPath)) {
return
}
const subscription = project.hmrEvents(chunkPath, HmrTarget.Server)
serverHmrSubscriptions.set(chunkPath, subscription)
// Start listening for changes in background
;(async () => {
// Skip initial state
await subscription.next()
for await (const result of subscription) {
const update = result as NodeJsHmrUpdate
// Only process partial updates with actual code changes
if (update.type !== 'partial') {
continue
}
const entries = update.instruction?.entries
if (!entries || Object.keys(entries).length === 0) {
continue
}
if (typeof __turbopack_server_hmr_apply__ === 'function') {
const applied = __turbopack_server_hmr_apply__(update as any)
if (applied) {
console.log(`[Server HMR] Applied update for ${chunkPath}`)
// TODO: Notify clients to refresh and get updated server content
// This will trigger the client to re-fetch the page with new server components
}
}
}
})().catch((err) => {
console.error('[Server HMR] Subscription error:', err)
serverHmrSubscriptions.delete(chunkPath)
})
}
// Listen to the Rust bindings update us on changing server HMR chunk paths
;(async () => {
const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(HmrTarget.Server)
// Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set(
data.chunkNames.filter((path) => path.endsWith('.js'))
)
// Clean up subscriptions for removed chunk paths (like when pages are deleted)
const chunkPathsToRemove = []
for (const chunkPath of serverHmrSubscriptions.keys()) {
if (!currentChunkPaths.has(chunkPath)) {
chunkPathsToRemove.push(chunkPath)
}
}
for (const chunkPath of chunkPathsToRemove) {
const subscription = serverHmrSubscriptions.get(chunkPath)
subscription?.return?.()
serverHmrSubscriptions.delete(chunkPath)
}
// Subscribe to HMR events for new server chunks
for (const chunkPath of currentChunkPaths) {
if (!serverHmrSubscriptions.has(chunkPath)) {
subscribeToServerHmr(chunkPath)
}
}
}
})().catch((err) => {
console.error('[Server HMR] error:', err)
})
}
/**
* Replaces turbopack:///[project] with the specified project in the `source` field.
*/
......@@ -194,7 +288,8 @@ export async function createHotReloaderTurbopack(
serverFields: ServerFields,
distDir: string,
resetFetch: () => void,
lockfile: Lockfile | undefined
lockfile: Lockfile | undefined,
experimentalServerFastRefresh?: boolean
): Promise<NextJsHotReloaderInterface> {
const dev = true
const buildId = 'development'
......@@ -292,7 +387,11 @@ export async function createHotReloaderTurbopack(
}
)
backgroundLogCompilationEvents(project, {
eventTypes: ['StartupCacheInvalidationEvent', 'TimingEvent'],
eventTypes: [
'StartupCacheInvalidationEvent',
'TimingEvent',
'SlowFilesystemEvent',
],
})
setBundlerFindSourceMapImplementation(
getSourceMapFromTurbopack.bind(null, project, projectPath)
......@@ -513,6 +612,10 @@ export async function createHotReloaderTurbopack(
}
}
if (experimentalServerFastRefresh) {
setupServerHmr(project)
}
let hmrEventHappened = false
let hmrHash = 0
......@@ -606,7 +709,7 @@ export async function createHotReloaderTurbopack(
sendEnqueuedMessagesDebounce()
}
async function subscribeToChanges(
async function subscribeToClientChanges(
key: EntryKey,
includeIssues: boolean,
endpoint: Endpoint,
......@@ -648,7 +751,7 @@ export async function createHotReloaderTurbopack(
changeSubscriptions.delete(key)
}
async function unsubscribeFromChanges(key: EntryKey) {
async function unsubscribeFromClientChanges(key: EntryKey) {
const subscription = await changeSubscriptions.get(key)
if (subscription) {
await subscription.return?.()
......@@ -657,7 +760,7 @@ export async function createHotReloaderTurbopack(
currentEntryIssues.delete(key)
}
async function subscribeToHmrEvents(client: ws, id: string) {
async function subscribeToClientHmrEvents(client: ws, id: string) {
const key = getEntryKey('assets', 'client', id)
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
// maybe throw an error / force the client to reload?
......@@ -669,7 +772,7 @@ export async function createHotReloaderTurbopack(
return
}
const subscription = project!.hmrEvents(id)
const subscription = project!.hmrEvents(id, HmrTarget.Client)
state.subscriptions.set(id, subscription)
// The subscription will always emit once, which is the initial
......@@ -680,7 +783,7 @@ export async function createHotReloaderTurbopack(
for await (const data of subscription) {
processIssues(state.clientIssues, key, data, false, true)
if (data.type !== 'issues') {
sendTurbopackMessage(data)
sendTurbopackMessage(data as TurbopackUpdate)
}
}
} catch (e) {
......@@ -698,7 +801,7 @@ export async function createHotReloaderTurbopack(
}
}
function unsubscribeFromHmrEvents(client: ws, id: string) {
function unsubscribeFromClientHmrEvents(client: ws, id: string) {
const state = clientStates.get(client)
if (!state) {
return
......@@ -775,9 +878,9 @@ export async function createHotReloaderTurbopack(
propagateServerField: propagateServerField.bind(null, opts),
sendHmr,
startBuilding,
subscribeToChanges,
unsubscribeFromChanges,
unsubscribeFromHmrEvents,
subscribeToChanges: subscribeToClientChanges,
unsubscribeFromChanges: unsubscribeFromClientChanges,
unsubscribeFromHmrEvents: unsubscribeFromClientHmrEvents,
},
},
})
......@@ -1132,11 +1235,11 @@ export async function createHotReloaderTurbopack(
// Turbopack messages
switch (parsedData.type) {
case 'turbopack-subscribe':
subscribeToHmrEvents(client, parsedData.path)
subscribeToClientHmrEvents(client, parsedData.path)
break
case 'turbopack-unsubscribe':
unsubscribeFromHmrEvents(client, parsedData.path)
unsubscribeFromClientHmrEvents(client, parsedData.path)
break
default:
......@@ -1446,7 +1549,7 @@ export async function createHotReloaderTurbopack(
productionRewrites: undefined,
logErrors: true,
hooks: {
subscribeToChanges,
subscribeToChanges: subscribeToClientChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths)
......@@ -1514,7 +1617,7 @@ export async function createHotReloaderTurbopack(
logErrors: true,
hooks: {
subscribeToChanges,
subscribeToChanges: subscribeToClientChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths)
......
......@@ -8,6 +8,7 @@ import type { UrlWithParsedQuery } from 'url'
import type { MiddlewareRoutingItem } from '../base-server'
import type { RouteDefinition } from '../route-definitions/route-definition'
import type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'
import {
addRequestMeta,
getRequestMeta,
......@@ -39,7 +40,12 @@ import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-pat
import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'
import { Telemetry } from '../../telemetry/storage'
import { type Span, setGlobal, trace } from '../../trace'
import {
type Span,
hrtimeToEpochNanoseconds,
setGlobal,
trace,
} from '../../trace'
import { traceGlobals } from '../../trace/shared'
import { findPageFile } from '../lib/find-page-file'
import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'
......@@ -532,6 +538,20 @@ export default class DevServer extends Server {
getRequestMeta(req, 'devRequestTimingInternalsEnd'),
getRequestMeta(req, 'devGenerateStaticParamsDuration')
)
// Create trace span for render phase
const devRequestTimingInternalsEnd = getRequestMeta(
req,
'devRequestTimingInternalsEnd'
)
if (devRequestTimingInternalsEnd) {
this.startServerSpan.manualTraceChild(
'render-path',
hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),
hrtimeToEpochNanoseconds(requestEnd),
{ path: req.url || '' }
)
}
})
}
}
......
......@@ -90,6 +90,7 @@ export async function initialize(opts: {
keepAliveTimeout?: number
customServer?: boolean
experimentalHttpsServer?: boolean
experimentalServerFastRefresh?: boolean
startServerSpan?: Span
quiet?: boolean
}): Promise<ServerInitResult> {
......@@ -178,6 +179,7 @@ export async function initialize(opts: {
port: opts.port,
onDevServerCleanup: opts.onDevServerCleanup,
resetFetch,
experimentalServerFastRefresh: opts.experimentalServerFastRefresh,
})
)
......
......@@ -115,6 +115,7 @@ export type SetupOpts = {
port: number
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined
resetFetch: () => void
experimentalServerFastRefresh?: boolean
}
export interface DevRoutesManifest {
......@@ -237,7 +238,8 @@ async function startWatcher(
serverFields,
distDir,
resetFetch,
lockfile
lockfile,
opts.experimentalServerFastRefresh
)
})()
: await (async () => {
......
......@@ -136,6 +136,7 @@ export async function getRequestHandlers({
minimalMode,
keepAliveTimeout,
experimentalHttpsServer,
experimentalServerFastRefresh,
quiet,
}: {
dir: string
......@@ -147,6 +148,7 @@ export async function getRequestHandlers({
minimalMode?: boolean
keepAliveTimeout?: number
experimentalHttpsServer?: boolean
experimentalServerFastRefresh?: boolean
quiet?: boolean
}): ReturnType<typeof initialize> {
return initialize({
......@@ -159,6 +161,7 @@ export async function getRequestHandlers({
server,
keepAliveTimeout,
experimentalHttpsServer,
experimentalServerFastRefresh,
startServerSpan,
quiet,
})
......@@ -179,6 +182,7 @@ export async function startServer(
allowRetry,
keepAliveTimeout,
selfSignedCertificate,
experimentalServerFastRefresh,
} = serverOptions
let { port } = serverOptions
......@@ -414,6 +418,9 @@ export async function startServer(
cleanupListeners?.runAll().catch(console.error),
])
// Flush any remaining traces to the trace file on shutdown
await flushAllTraces()
// Flush telemetry if this is a dev server
if (isDev) {
try {
......@@ -476,6 +483,7 @@ export async function startServer(
minimalMode,
keepAliveTimeout,
experimentalHttpsServer: !!selfSignedCertificate,
experimentalServerFastRefresh,
})
requestHandler = initResult.requestHandler
upgradeHandler = initResult.upgradeHandler
......
......@@ -7,6 +7,7 @@ import {
recordTraceEvents,
Span,
SpanStatus,
hrtimeToEpochNanoseconds,
} from './trace'
import { setGlobal } from './shared'
import type { SpanId, TraceEvent, TraceState } from './types'
......@@ -16,6 +17,7 @@ export {
exportTraceState,
flushAllTraces,
getTraceEvents,
hrtimeToEpochNanoseconds,
initializeTraceState,
recordTraceEvents,
Span,
......
......@@ -15,6 +15,7 @@ const COMMON_ALLOWED_EVENTS = ['memory-usage']
const DEV_ALLOWED_EVENTS = new Set([
...COMMON_ALLOWED_EVENTS,
'client-hmr-latency',
'render-path',
'hot-reloader',
'webpack-invalid-client',
'webpack-invalidated-server',
......
......@@ -3,6 +3,7 @@ import type { SpanId, TraceEvent, TraceState } from './types'
const NUM_OF_MICROSEC_IN_NANOSEC = BigInt('1000')
const NUM_OF_MILLISEC_IN_NANOSEC = BigInt('1000000')
let count = 0
const getId = () => {
count++
......@@ -188,3 +189,18 @@ export function recordTraceEvents(events: TraceEvent[]) {
}
export const clearTraceEvents = () => (savedTraceEvents = [])
/**
* Converts hrtime (process.hrtime.bigint()) to epoch-based nanoseconds.
*
* hrtime values are relative to an arbitrary point in the past, while
* epoch-based times are nanoseconds since Unix epoch (Jan 1, 1970).
*
* This is useful when passing hrtime values to APIs that expect epoch-based times,
* such as Span.manualTraceChild().
*/
export function hrtimeToEpochNanoseconds(hrtimeValue: bigint): bigint {
const offset =
BigInt(Date.now()) * NUM_OF_MILLISEC_IN_NANOSEC - process.hrtime.bigint()
return hrtimeValue + offset
}
{
"name": "@next/react-refresh-utils",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"description": "An experimental package providing utilities for React Refresh.",
"repository": {
"url": "vercel/next.js",
......
{
"name": "@next/third-parties",
"version": "16.2.0-canary.33",
"version": "16.2.0-canary.35",
"repository": {
"url": "vercel/next.js",
"directory": "packages/third-parties"
......@@ -26,7 +26,7 @@
"third-party-capital": "1.0.20"
},
"devDependencies": {
"next": "16.2.0-canary.33",
"next": "16.2.0-canary.35",
"outdent": "0.8.0",
"prettier": "2.5.1",
"typescript": "5.9.2"
......
......@@ -1011,7 +1011,7 @@ importers:
packages/eslint-config-next:
dependencies:
'@next/eslint-plugin-next':
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../eslint-plugin-next
eslint:
specifier: '>=9.0.0'
......@@ -1088,7 +1088,7 @@ importers:
packages/next:
dependencies:
'@next/env':
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../next-env
'@swc/helpers':
specifier: 0.5.15
......@@ -1216,19 +1216,19 @@ importers:
specifier: 1.2.0
version: 1.2.0
'@next/font':
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../font
'@next/polyfill-module':
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../next-polyfill-module
'@next/polyfill-nomodule':
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../next-polyfill-nomodule
'@next/react-refresh-utils':
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../react-refresh-utils
'@next/swc':
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../next-swc
'@opentelemetry/api':
specifier: 1.6.0
......@@ -1943,7 +1943,7 @@ importers:
version: 1.0.20
devDependencies:
next:
specifier: 16.2.0-canary.33
specifier: 16.2.0-canary.35
version: link:../next
outdent:
specifier: 0.8.0
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 { join } from 'path'
import { existsSync, readFileSync } from 'fs'
type SpanId = number
type TraceEvent = {
traceId?: string
parentId?: SpanId
name: string
id: SpanId
timestamp: number
duration: number
tags?: Record<string, unknown>
startTime?: number
}
interface TraceStructure {
events: TraceEvent[]
eventsByName: Map<string, TraceEvent[]>
eventsById: Map<string, TraceEvent>
}
function parseTraceFile(tracePath: string): TraceStructure {
const traceContent = readFileSync(tracePath, 'utf8')
const traceLines = traceContent
.trim()
.split('\n')
.filter((line) => line.trim())
const allEvents: TraceEvent[] = []
for (const line of traceLines) {
const events = JSON.parse(line) as TraceEvent[]
allEvents.push(...events)
}
const eventsByName = new Map<string, TraceEvent[]>()
const eventsById = new Map<string, TraceEvent>()
// Index all events
for (const event of allEvents) {
if (!eventsByName.has(event.name)) {
eventsByName.set(event.name, [])
}
eventsByName.get(event.name)!.push(event)
eventsById.set(event.id.toString(), event)
}
return {
events: allEvents,
eventsByName,
eventsById,
}
}
describe('render-path tracing', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (!isNextDev) {
it('should be skipped in production', () => {})
return
}
it('should record render-path events for page requests', async () => {
const tracePath = join(next.testDir, '.next/dev/trace')
// Trigger page request if trace doesn't exist yet
if (!existsSync(tracePath)) {
const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('hello world')
await browser.close()
await next.stop('SIGTERM')
await new Promise((resolve) => setTimeout(resolve, 500))
}
const traceStructure = parseTraceFile(tracePath)
// Check for render-path events
const renderPathEvents = traceStructure.eventsByName.get('render-path')
expect(renderPathEvents).toBeDefined()
expect(renderPathEvents!.length).toBeGreaterThan(0)
// Verify the first render-path event has expected attributes
const renderEvent = renderPathEvents![0]
expect(renderEvent.tags).toBeDefined()
const renderTags = renderEvent.tags as any
expect(renderTags.path).toBeDefined()
expect(typeof renderTags.path).toBe('string')
// Verify render event has valid duration
expect(renderEvent.duration).toBeGreaterThan(0)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { NextInstance, createNext } from 'e2e-utils'
import { trace } from 'next/dist/trace'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { createDefineEnv, loadBindings } from 'next/dist/build/swc'
import { createDefineEnv, loadBindings, HmrTarget } from 'next/dist/build/swc'
import type {
Diagnostics,
Issue,
......@@ -667,12 +667,15 @@ describe('next.rs api', () => {
}
}
const result = await project.hmrIdentifiersSubscribe().next()
const result = await project
.hmrChunkNamesSubscribe(HmrTarget.Client)
.next()
expect(result.done).toBe(false)
const identifiers = result.value.identifiers
expect(identifiers).toHaveProperty('length', expect.toBePositive())
const subscriptions = identifiers.map((identifier) =>
project.hmrEvents(identifier)
const chunkNames = result.value.chunkNames
expect(chunkNames).toHaveProperty('length', expect.toBePositive())
const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(chunkName, HmrTarget.Client)
)
await Promise.all(
subscriptions.map(async (subscription) => {
......@@ -794,12 +797,12 @@ describe('next.rs api', () => {
if (route.type !== 'page') throw new Error('unknown route type')
await route.htmlEndpoint.writeToDisk()
const result = await project.hmrIdentifiersSubscribe().next()
const result = await project.hmrChunkNamesSubscribe(HmrTarget.Client).next()
expect(result.done).toBe(false)
const identifiers = result.value.identifiers
const chunkNames = result.value.chunkNames
const subscriptions = identifiers.map((identifier) =>
project.hmrEvents(identifier)
const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(chunkName, HmrTarget.Client)
)
await Promise.all(
subscriptions.map(async (subscription) => {
......
......@@ -3,18 +3,7 @@ import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
<body style={{ fontFamily: 'monospace' }}>{children}</body>
</html>
)
}
function Header() {
return (
<header>
<a href="/">Home</a>
</header>
)
}
import Link from 'next/link'
export default function IndexPage() {
return (
<main>
<h1>Instant Validation Test</h1>
<ul>
<li>
<Link href="/default">Default (plain root layout)</Link>
</li>
<li>
<Link href="/suspense-in-root">Suspense in Root</Link>
</li>
</ul>
</main>
)
}
import { ReactNode } from 'react'
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
<hr />
{children}
</body>
</html>
......@@ -14,7 +16,17 @@ export default function RootLayout({ children }: { children: ReactNode }) {
function Header() {
return (
<header>
<a href="/">Home</a>
<a href="/">Home</a>{' '}
<Suspense fallback="...">
<div id="root-layout-timestamp">
<Now />
</div>
</Suspense>
</header>
)
}
async function Now() {
await connection()
return Date.now()
}
import { cacheLife } from 'next/cache'
import { DebugLinks } from '../shared'
export default async function Page() {
'use cache'
cacheLife('minutes')
return (
<main>
<h2>Static</h2>
<ul>
<li>
<DebugLinks href="/default/static/valid-blocked-children" />
</li>
<li>
<DebugLinks href="/default/static/valid-blocking-inside-static" />
</li>
</ul>
</main>
)
}
import { cacheLife } from 'next/cache'
import Link from 'next/link'
import { setTimeout } from 'timers/promises'
export function DebugLinks({ href }: { href: string }) {
return (
<span>
<span>{href}</span>{' '}
<Link data-link-type="soft" href={href}>
[SPA]
</Link>{' '}
<a data-link-type="hard" href={href}>
[MPA]
</a>
</span>
)
}
export async function uncachedIO() {
await setTimeout(0)
}
......
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
......@@ -9,6 +10,7 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
<hr />
{children}
</body>
</html>
......@@ -19,7 +21,17 @@ export default function RootLayout({ children }: { children: ReactNode }) {
function Header() {
return (
<header>
<a href="/">Home</a>
<a href="/">Home</a>{' '}
<Suspense fallback="...">
<div id="root-layout-timestamp">
<Now />
</div>
</Suspense>
</header>
)
}
async function Now() {
await connection()
return Date.now()
}
import { DebugLinkMPA } from '../../components/debug-link'
import { cacheLife } from 'next/cache'
import { DebugLinks } from '../shared'
export default async function Page() {
'use cache'
......@@ -9,90 +9,84 @@ export default async function Page() {
<h2>Runtime</h2>
<ul>
<li>
<DebugLinkMPA href="/runtime/suspense-around-dynamic" />
<DebugLinks href="/suspense-in-root/runtime/suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/runtime/no-suspense-around-params/123" />
<DebugLinks href="/suspense-in-root/runtime/no-suspense-around-params/123" />
</li>
<li>
<DebugLinkMPA href="/runtime/missing-suspense-around-dynamic" />
<DebugLinks href="/suspense-in-root/runtime/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/runtime/missing-suspense-around-dynamic-layout" />
<DebugLinks href="/suspense-in-root/runtime/missing-suspense-around-dynamic-layout" />
</li>
<li>
<DebugLinkMPA href="/runtime/suspense-too-high" />
<DebugLinks href="/suspense-in-root/runtime/suspense-too-high" />
</li>
<li>
<DebugLinkMPA href="/runtime/invalid-blocking-inside-runtime" />
<DebugLinks href="/suspense-in-root/static/invalid-blocking-inside-static" />
</li>
<li>
<DebugLinkMPA href="/runtime/invalid-sync-io" />
<DebugLinks href="/suspense-in-root/runtime/invalid-blocking-inside-runtime" />
</li>
<li>
<DebugLinkMPA href="/runtime/valid-blocking-inside-runtime" />
<DebugLinks href="/suspense-in-root/runtime/invalid-sync-io" />
</li>
<li>
<DebugLinks href="/suspense-in-root/runtime/valid-blocking-inside-runtime" />
</li>
</ul>
<h2>Static</h2>
<ul>
<li>
<DebugLinkMPA href="/static/suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-params/123" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-dynamic-layout" />
<DebugLinks href="/suspense-in-root/static/suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/suspense-too-high" />
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/blocking-layout" />
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-params/123" />
</li>
<li>
<DebugLinkMPA href="/static/blocking-layout/missing-suspense-around-dynamic" />
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-dynamic-layout" />
</li>
<li>
<DebugLinkMPA href="/static/invalid-only-loading-around-dynamic" />
<DebugLinks href="/suspense-in-root/static/suspense-too-high" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-around-runtime" />
<DebugLinks href="/suspense-in-root/static/blocking-layout" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route" />
<DebugLinks href="/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route/foo" />
<DebugLinks href="/suspense-in-root/static/invalid-only-loading-around-dynamic" />
</li>
<li>
<DebugLinkMPA href="/static/missing-suspense-in-parallel-route/bar" />
<DebugLinks href="/suspense-in-root/static/missing-suspense-around-runtime" />
</li>
<li>
<DebugLinkMPA href="/static/invalid-blocking-inside-static" />
<DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route" />
</li>
<li>
<DebugLinkMPA href="/static/valid-blocked-children" />
<DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route/foo" />
</li>
<li>
<DebugLinkMPA href="/static/valid-blocking-inside-static" />
<DebugLinks href="/suspense-in-root/static/missing-suspense-in-parallel-route/bar" />
</li>
</ul>
<h2>Disable Validation</h2>
<ul>
<li>
<DebugLinkMPA href="/disable-validation/in-layout" />
<DebugLinks href="/suspense-in-root/disable-validation/in-layout" />
</li>
<li>
<DebugLinkMPA href="/disable-validation/in-page" />
<DebugLinks href="/suspense-in-root/disable-validation/in-page" />
</li>
<li>
<DebugLinkMPA href="/disable-validation/in-page-with-outer" />
<DebugLinks href="/suspense-in-root/disable-validation/in-page-with-outer" />
</li>
</ul>
</main>
......
import Link from 'next/link'
export const unstable_instant = { prefetch: 'static' }
export default async function Page() {
return (
<main>
<p>This is a static page below a blocking layout</p>
<div>
<Link href="/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic">
/suspense-in-root/static/blocking-layout/missing-suspense-around-dynamic
</Link>
</div>
</main>
)
}
......@@ -6,7 +6,9 @@ export default async function Page() {
return (
<main>
<p>This is a static page</p>
<Link href="./missing-suspense-in-parallel-route/foo">./foo</Link>
<Link href="/suspense-in-root/static/missing-suspense-in-parallel-route/foo">
./foo
</Link>
</main>
)
}
'use client'
import Link from 'next/link'
import { ComponentProps } from 'react'
export function DebugLink({
href,
...props
}: Omit<ComponentProps<typeof Link>, 'children' | 'href'> & { href: string }) {
return (
<Link href={href} {...props}>
{href}
</Link>
)
}
export function DebugLinkMPA({
href,
...props
......
import { nextTestSetup } from 'e2e-utils'
describe('not-found-with-pages', () => {
const { next, isNextStart } = nextTestSetup({
const isAdapterTest = Boolean(process.env.NEXT_ENABLE_ADAPTER)
describe('not-found-with-pages-i18n', () => {
const { next, isNextStart, isNextDeploy } = nextTestSetup({
files: __dirname,
})
......@@ -17,15 +19,32 @@ describe('not-found-with-pages', () => {
})
}
it('should prefer the app router 404 over the pages router 404 when both are present', async () => {
const browser = await next.browser('/app-dir/foo')
expect(await browser.elementByCss('h1').text()).toBe(
'APP ROUTER - 404 PAGE'
)
// When using the builder, pages router is incorrectly preferred. This is already fixed when using the adapter
const SKIP_TEST_FOR_BUILDER = isNextDeploy ? !isAdapterTest : false
if (!SKIP_TEST_FOR_BUILDER) {
it.each(['/app-dir/foo', '/foo'])(
'should prefer the app router 404 over the pages router 404 when both are present - browser %s',
async (s) => {
const browser = await next.browser(s)
expect(await browser.elementByCss('h1').text()).toBe(
'APP ROUTER - 404 PAGE'
)
await browser.loadPage(next.url)
expect(await browser.elementByCss('h1').text()).toBe(
'APP ROUTER - 404 PAGE'
await browser.loadPage(next.url)
expect(await browser.elementByCss('h1').text()).toBe(
'APP ROUTER - 404 PAGE'
)
}
)
})
}
it.each(SKIP_TEST_FOR_BUILDER ? ['/app-dir/foo'] : ['/app-dir/foo', '/foo'])(
'should prefer the app router 404 over the pages router 404 when both are present - SSR %s',
async (s) => {
const ssr = await next.fetch(s)
expect(ssr.status).toEqual(404)
expect(await ssr.text()).toContain('APP ROUTER - 404 PAGE')
}
)
})
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
import { setTimeout } from 'node:timers/promises'
import { retry } from 'next-test-utils'
describe('parallel-routes-root-param-dynamic-child', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
async function createBrowserActor(url: string, errorPage: boolean = false) {
async function createBrowserActor(
url: string,
{
errorPage = false,
waitForPrefetch = false,
}: {
errorPage?: boolean
waitForPrefetch?: boolean
} = {}
) {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser(url, {
beforePageLoad(page) {
......@@ -22,29 +32,39 @@ describe('parallel-routes-root-param-dynamic-child', () => {
return { act, browser }
}
// The page has navigation links that will be automatically prefetched.
// Some routes will 404 (like /es which isn't in generateStaticParams),
// so we allow 404 status codes. Let's reveal the navigation links and let
// the prefetching occur.
await act(
async () => {
await browser.elementByCss('#reveal').click()
// Ensure the navigation is visible
await browser.elementByCss('#nav')
// Wait for 500ms to ensure all links are visible
await setTimeout(500)
// Scroll to bottom to ensure all links enter viewport and trigger prefetches
await browser.eval('window.scrollTo(0, document.body.scrollHeight)')
// Wait for 500ms to ensure all links are visible
await setTimeout(500)
},
// If we're in development, we don't have any prefetching to wait for.
isNextDev ? 'no-requests' : undefined
)
if (waitForPrefetch) {
// The page has navigation links that will be automatically prefetched.
// Some routes will 404 (like /es which isn't in generateStaticParams),
// so we allow 404 status codes. Let's reveal the navigation links and let
// the prefetching occur.
await act(
async () => {
await browser.elementByCss('#reveal').click()
// Ensure the navigation is visible
await browser.elementByCss('#nav')
// Wait for 500ms to ensure all links are visible
await setTimeout(500)
// Scroll to bottom to ensure all links enter viewport and trigger prefetches
await browser.eval('window.scrollTo(0, document.body.scrollHeight)')
// Wait for 500ms to ensure all links are visible
await setTimeout(500)
},
// If we're in development, we don't have any prefetching to wait for.
isNextDev ? 'no-requests' : undefined
)
} else {
// Most assertions only need the nav revealed, and should not block on
// background prefetch request completion.
await browser.elementByCss('#reveal').click()
await browser.elementByCss('#nav')
await setTimeout(500)
await browser.eval('window.scrollTo(0, document.body.scrollHeight)')
await setTimeout(500)
}
return { act, browser }
}
......@@ -52,7 +72,7 @@ describe('parallel-routes-root-param-dynamic-child', () => {
if (!isNextDev) {
describe('Prefetching', () => {
it('prefetches the 404 pages correctly', async () => {
await createBrowserActor('/en')
await createBrowserActor('/en', { waitForPrefetch: true })
// If we got here without errors, the prefetch responses completed successfully
// without problematic redirects (like 307). Those will throw because
......@@ -67,14 +87,16 @@ describe('parallel-routes-root-param-dynamic-child', () => {
async (locale) => {
const { browser } = await createBrowserActor(`/${locale}`)
expect(await browser.elementByCss('#locale-page').text()).toBe(
`Locale: ${locale}`
)
await retry(async () => {
expect(await browser.elementByCss('#locale-page').text()).toBe(
`Locale: ${locale}`
)
})
}
)
it('should render a 404 for /es (not in generateStaticParams)', async () => {
const { browser } = await createBrowserActor('/es', true)
const { browser } = await createBrowserActor('/es', { errorPage: true })
expect(await browser.elementByCss('.next-error-h1').text()).toBe('404')
})
......@@ -92,12 +114,14 @@ describe('parallel-routes-root-param-dynamic-child', () => {
.click()
})
expect(await browser.elementByCss('#story-locale').text()).toBe(
`Locale: ${locale}`
)
expect(await browser.elementByCss('#story-slug').text()).toBe(
'Story: dynamic-123'
)
await retry(async () => {
expect(await browser.elementByCss('#story-locale').text()).toBe(
`Locale: ${locale}`
)
expect(await browser.elementByCss('#story-slug').text()).toBe(
'Story: dynamic-123'
)
})
}
)
......@@ -130,12 +154,14 @@ describe('parallel-routes-root-param-dynamic-child', () => {
.click()
})
expect(await browser.elementByCss('#story-locale').text()).toBe(
`Locale: ${locale}`
)
expect(await browser.elementByCss('#story-slug').text()).toBe(
'Story: static-123'
)
await retry(async () => {
expect(await browser.elementByCss('#story-locale').text()).toBe(
`Locale: ${locale}`
)
expect(await browser.elementByCss('#story-slug').text()).toBe(
'Story: static-123'
)
})
}
)
......@@ -157,9 +183,11 @@ describe('parallel-routes-root-param-dynamic-child', () => {
.click()
})
expect(await browser.elementByCss('.next-error-h1').text()).toBe(
'404'
)
await retry(async () => {
expect(await browser.elementByCss('.next-error-h1').text()).toBe(
'404'
)
})
}
)
......
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
import { retry } from 'next-test-utils'
describe('navigating without a prefetch', () => {
const { next } = nextTestSetup({
......@@ -7,23 +7,18 @@ describe('navigating without a prefetch', () => {
})
it('can show a loading boundary from the dynamic response', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
const browser = await next.browser('/')
// Navigate to a dynamic page with a `loading.tsx` without a prefetch.
await act(async () => {
await browser.elementByCss('a[href="/with-loading"]').click()
})
await browser.elementByCss('a[href="/with-loading"]').click()
// The page suspends on the client, so we should display the `loading` that we got from the dynamic response.
expect(
await browser
.elementByCss('#loading-component', { state: 'visible' })
.text()
).toContain('Loading...')
await retry(async () => {
expect(
await browser
.elementByCss('#loading-component', { state: 'visible' })
.text()
).toContain('Loading...')
})
})
})
This diff is collapsed.
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