Unverified Commit aac4ebb7 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Turbopack: Server HMR infrastructure (#88870)

This adds some basic JavaScript/TypeScript infrastructure for Next to receive and handle server-side HMR updates from Turbopack.

This:
- Renames some existing hmr code as explicitly client hmr
- Adds counterpart apis for server hmr (e.g. subscribe to server HMR events via `project.serverHmrEvents()`)
- Add `__turbopack_server_hmr_apply__` runtime function (this is a stub for now, just logs on updates)

**Alternatives considered**
A single firehose for hmr events, pushing the filtering to the JS side. I figured separate dedicated apis would be cleaner since they’d have to be filtered and switched on anyway.

**In future PRs**
- Rust: Make Turbopack send 'partial' updates for server file changes
- Node dev runtime: Implement module factory replacement in `__turbopack_server_hmr_apply__`
- add client notification to trigger re-fetch of rsc
- e2e tests
parent a9ecc09b
...@@ -166,6 +166,51 @@ pub struct DebugBuildPaths { ...@@ -166,6 +166,51 @@ pub struct DebugBuildPaths {
pub pages: Vec<RcStr>, 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. /// Pre-converted route keys from debug build paths for O(1) lookups.
struct DebugBuildPathsRouteKeys { struct DebugBuildPathsRouteKeys {
app: FxHashSet<RcStr>, app: FxHashSet<RcStr>,
...@@ -745,10 +790,10 @@ impl ProjectContainer { ...@@ -745,10 +790,10 @@ impl ProjectContainer {
self.project().entrypoints() self.project().entrypoints()
} }
/// See [Project::hmr_identifiers]. /// See [Project::hmr_chunk_names].
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn hmr_identifiers(self: Vc<Self>) -> Vc<Vec<RcStr>> { pub fn hmr_chunk_names(self: Vc<Self>, target: HmrTarget) -> Vc<Vec<RcStr>> {
self.project().hmr_identifiers() self.project().hmr_chunk_names(target)
} }
/// Gets a source map for a particular `file_path`. If `dev` mode is disabled, this will always /// Gets a source map for a particular `file_path`. If `dev` mode is disabled, this will always
...@@ -2050,19 +2095,39 @@ impl Project { ...@@ -2050,19 +2095,39 @@ impl Project {
.await .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] #[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 { 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) Ok(content)
} else { } else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
} }
} }
/// Get HMR version for the specified target.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn hmr_version(self: Vc<Self>, identifier: RcStr) -> Result<Vc<Box<dyn Version>>> { async fn hmr_version(
let content = self.hmr_content(identifier).await?; 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 { if let Some(content) = &*content {
Ok(content.version()) Ok(content.version())
} else { } else {
...@@ -2070,15 +2135,16 @@ impl Project { ...@@ -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. /// version in that session.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn hmr_version_state( pub async fn hmr_version_state(
self: Vc<Self>, self: Vc<Self>,
identifier: RcStr, chunk_name: RcStr,
target: HmrTarget,
session: TransientInstance<()>, session: TransientInstance<()>,
) -> Result<Vc<VersionState>> { ) -> 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 // The session argument is important to avoid caching this function between
// sessions. // sessions.
...@@ -2099,15 +2165,16 @@ impl Project { ...@@ -2099,15 +2165,16 @@ impl Project {
} }
/// Emits opaque HMR events whenever a change is detected in the chunk group /// 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] #[turbo_tasks::function]
pub async fn hmr_update( pub async fn hmr_update(
self: Vc<Self>, self: Vc<Self>,
identifier: RcStr, chunk_name: RcStr,
target: HmrTarget,
from: Vc<VersionState>, from: Vc<VersionState>,
) -> Result<Vc<Update>> { ) -> Result<Vc<Update>> {
let from = from.get(); 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 { if let Some(content) = *content {
Ok(content.update(from)) Ok(content.update(from))
} else { } else {
...@@ -2115,12 +2182,13 @@ impl Project { ...@@ -2115,12 +2182,13 @@ impl Project {
} }
} }
/// Gets a list of all HMR identifiers that can be subscribed to. This is /// Gets a list of all HMR chunk names that can be subscribed to for the
/// only needed for testing purposes and isn't used in real apps. /// specified target. This is only needed for testing purposes and isn't
/// used in real apps.
#[turbo_tasks::function] #[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 { 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 { } else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
} }
......
...@@ -8,7 +8,7 @@ use std::{str::FromStr, time::Instant}; ...@@ -8,7 +8,7 @@ use std::{str::FromStr, time::Instant};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use futures_util::{StreamExt, TryStreamExt}; use futures_util::{StreamExt, TryStreamExt};
use next_api::{ use next_api::{
project::{ProjectContainer, ProjectOptions}, project::{HmrTarget, ProjectContainer, ProjectOptions},
route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk}, route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk},
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
...@@ -257,7 +257,7 @@ async fn hmr( ...@@ -257,7 +257,7 @@ async fn hmr(
tracing::info!("HMR..."); tracing::info!("HMR...");
let session = TransientInstance::new(()); let session = TransientInstance::new(());
let idents = tt let idents = tt
.run(async move { project.hmr_identifiers().await }) .run(async move { project.hmr_chunk_names(HmrTarget::Client).await })
.await?; .await?;
let start = Instant::now(); let start = Instant::now();
for ident in idents { for ident in idents {
...@@ -270,8 +270,10 @@ async fn hmr( ...@@ -270,8 +270,10 @@ async fn hmr(
let session = session.clone(); let session = session.clone();
async move { async move {
let project = project.project(); let project = project.project();
let state = project.hmr_version_state(ident.clone(), session); let state = project.hmr_version_state(ident.clone(), HmrTarget::Client, session);
project.hmr_update(ident.clone(), state).await?; project
.hmr_update(ident.clone(), HmrTarget::Client, state)
.await?;
Ok(Vc::<()>::cell(())) Ok(Vc::<()>::cell(()))
} }
}); });
......
...@@ -18,7 +18,7 @@ use next_api::{ ...@@ -18,7 +18,7 @@ use next_api::{
RouteOperation, RouteOperation,
}, },
project::{ project::{
DebugBuildPaths, DefineEnv, DraftModeOptions, PartialProjectOptions, Project, DebugBuildPaths, DefineEnv, DraftModeOptions, HmrTarget, PartialProjectOptions, Project,
ProjectContainer, ProjectOptions, WatchOptions, ProjectContainer, ProjectOptions, WatchOptions,
}, },
route::Endpoint, route::Endpoint,
...@@ -1205,13 +1205,24 @@ struct HmrUpdateWithIssues { ...@@ -1205,13 +1205,24 @@ struct HmrUpdateWithIssues {
effects: Arc<Effects>, 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)] #[turbo_tasks::function(operation)]
async fn hmr_update_with_issues_operation( async fn hmr_update_with_issues_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
identifier: RcStr, chunk_name: RcStr,
state: ResolvedVc<VersionState>, state: ResolvedVc<VersionState>,
target: HmrTarget,
) -> Result<Vc<HmrUpdateWithIssues>> { ) -> 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 update = update_op.read_strongly_consistent().await?;
let issues = get_issues(update_op, NEXT_ISSUE_FILTER).await?; let issues = get_issues(update_op, NEXT_ISSUE_FILTER).await?;
let diagnostics = get_diagnostics(update_op).await?; let diagnostics = get_diagnostics(update_op).await?;
...@@ -1225,42 +1236,42 @@ async fn hmr_update_with_issues_operation( ...@@ -1225,42 +1236,42 @@ async fn hmr_update_with_issues_operation(
.cell()) .cell())
} }
#[turbo_tasks::function(operation)] #[tracing::instrument(level = "info", name = "get HMR events", skip(project, func), fields(target = %target))]
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))]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_events( pub fn project_hmr_events(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
identifier: RcStr, chunk_name: RcStr,
target: String,
func: JsFunction, func: JsFunction,
) -> napi::Result<External<RootTask>> { ) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container; let container = project.container;
let session = TransientInstance::new(()); let session = TransientInstance::new(());
subscribe( subscribe(
project.turbopack_ctx.clone(), project.turbopack_ctx.clone(),
func, func,
{ {
let outer_identifier = identifier.clone(); let outer_chunk_name = chunk_name.clone();
let session = session.clone(); let session = session.clone();
move || { move || {
let identifier: RcStr = outer_identifier.clone(); let chunk_name: RcStr = outer_chunk_name.clone();
let session = session.clone(); let session = session.clone();
async move { async move {
let project = container.project().to_resolved().await?; let project = container.project().to_resolved().await?;
let state = project let state = project
.hmr_version_state(identifier.clone(), session) .hmr_version_state(chunk_name.clone(), hmr_target, session)
.to_resolved() .to_resolved()
.await?; .await?;
let update_op = let update_op = hmr_update_with_issues_operation(
hmr_update_with_issues_operation(project, identifier.clone(), state); project,
chunk_name.clone(),
state,
hmr_target,
);
let update = update_op.read_strongly_consistent().await?; let update = update_op.read_strongly_consistent().await?;
let HmrUpdateWithIssues { let HmrUpdateWithIssues {
update, update,
...@@ -1295,7 +1306,7 @@ pub fn project_hmr_events( ...@@ -1295,7 +1306,7 @@ pub fn project_hmr_events(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let identifier = ResourceIdentifier { let identifier = ResourceIdentifier {
path: identifier.clone(), path: chunk_name.clone(),
headers: None, headers: None,
}; };
let update = match update.as_deref() { let update = match update.as_deref() {
...@@ -1320,29 +1331,38 @@ pub fn project_hmr_events( ...@@ -1320,29 +1331,38 @@ pub fn project_hmr_events(
} }
#[napi(object)] #[napi(object)]
struct HmrIdentifiers { struct HmrChunkNames {
pub identifiers: Vec<RcStr>, pub chunk_names: Vec<RcStr>,
} }
#[turbo_tasks::value(serialization = "none")] #[turbo_tasks::value(serialization = "none")]
struct HmrIdentifiersWithIssues { struct HmrChunkNamesWithIssues {
identifiers: ReadRef<Vec<RcStr>>, chunk_names: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>, issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>, diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>, effects: Arc<Effects>,
} }
#[turbo_tasks::function(operation)] #[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>, container: ResolvedVc<ProjectContainer>,
) -> Result<Vc<HmrIdentifiersWithIssues>> { target: HmrTarget,
let hmr_identifiers_op = project_container_hmr_identifiers_operation(container); ) -> Result<Vc<HmrChunkNamesWithIssues>> {
let hmr_identifiers = hmr_identifiers_op.read_strongly_consistent().await?; let hmr_chunk_names_op = project_hmr_chunk_names_operation(container, target);
let issues = get_issues(hmr_identifiers_op, NEXT_ISSUE_FILTER).await?; let hmr_chunk_names = hmr_chunk_names_op.read_strongly_consistent().await?;
let diagnostics = get_diagnostics(hmr_identifiers_op).await?; let issues = get_issues(hmr_chunk_names_op, NEXT_ISSUE_FILTER).await?;
let effects = Arc::new(get_effects(hmr_identifiers_op).await?); let diagnostics = get_diagnostics(hmr_chunk_names_op).await?;
Ok(HmrIdentifiersWithIssues { let effects = Arc::new(get_effects(hmr_chunk_names_op).await?);
identifiers: hmr_identifiers, Ok(HmrChunkNamesWithIssues {
chunk_names: hmr_chunk_names,
issues, issues,
diagnostics, diagnostics,
effects, effects,
...@@ -1350,44 +1370,42 @@ async fn get_hmr_identifiers_with_issues_operation( ...@@ -1350,44 +1370,42 @@ async fn get_hmr_identifiers_with_issues_operation(
.cell()) .cell())
} }
#[turbo_tasks::function(operation)] #[tracing::instrument(level = "info", name = "get HMR chunk names", skip(project, func), fields(target = %target))]
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)]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[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>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
target: String,
func: JsFunction, func: JsFunction,
) -> napi::Result<External<RootTask>> { ) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container; let container = project.container;
subscribe( subscribe(
project.turbopack_ctx.clone(), project.turbopack_ctx.clone(),
func, func,
move || async move { move || async move {
let hmr_identifiers_with_issues_op = let hmr_chunk_names_with_issues_op =
get_hmr_identifiers_with_issues_operation(container); get_hmr_chunk_names_with_issues_operation(container, hmr_target);
let HmrIdentifiersWithIssues { let HmrChunkNamesWithIssues {
identifiers, chunk_names,
issues, issues,
diagnostics, diagnostics,
effects, effects,
} = &*hmr_identifiers_with_issues_op } = &*hmr_chunk_names_with_issues_op
.read_strongly_consistent() .read_strongly_consistent()
.await?; .await?;
effects.apply().await?; effects.apply().await?;
Ok((identifiers.clone(), issues.clone(), diagnostics.clone())) Ok((chunk_names.clone(), issues.clone(), diagnostics.clone()))
}, },
move |ctx| { move |ctx| {
let (identifiers, issues, diagnostics) = ctx.value; let (chunk_names, issues, diagnostics) = ctx.value;
Ok(vec![TurbopackResult { Ok(vec![TurbopackResult {
result: HmrIdentifiers { result: HmrChunkNames {
identifiers: ReadRef::into_owned(identifiers), chunk_names: ReadRef::into_owned(chunk_names),
}, },
issues: issues issues: issues
.iter() .iter()
......
...@@ -314,14 +314,16 @@ export declare function projectEntrypointsSubscribe( ...@@ -314,14 +314,16 @@ export declare function projectEntrypointsSubscribe(
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export declare function projectHmrEvents( export declare function projectHmrEvents(
project: { __napiType: 'Project' }, project: { __napiType: 'Project' },
identifier: RcStr, chunkName: RcStr,
target: string,
func: (...args: any[]) => any func: (...args: any[]) => any
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export interface HmrIdentifiers { export interface HmrChunkNames {
identifiers: Array<RcStr> chunkNames: Array<RcStr>
} }
export declare function projectHmrIdentifiersSubscribe( export declare function projectHmrChunkNamesSubscribe(
project: { __napiType: 'Project' }, project: { __napiType: 'Project' },
target: string,
func: (...args: any[]) => any func: (...args: any[]) => any
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export interface NapiUpdateMessage { export interface NapiUpdateMessage {
......
...@@ -27,8 +27,9 @@ import type { ...@@ -27,8 +27,9 @@ import type {
CompilationEvent, CompilationEvent,
DefineEnv, DefineEnv,
Endpoint, Endpoint,
HmrIdentifiers, HmrChunkNames,
Lockfile, Lockfile,
NodeJsHmrUpdate,
PartialProjectOptions, PartialProjectOptions,
Project, Project,
ProjectOptions, ProjectOptions,
...@@ -43,6 +44,11 @@ import type { ...@@ -43,6 +44,11 @@ import type {
} from './types' } from './types'
import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error' import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error'
export enum HmrTarget {
Client = 'client',
Server = 'server',
}
type RawBindings = typeof import('./generated-native') type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & { type RawWasmBindings = typeof import('./generated-wasm') & {
default?(): Promise<typeof import('./generated-wasm')> default?(): Promise<typeof import('./generated-wasm')>
...@@ -735,17 +741,39 @@ function bindingToApi( ...@@ -735,17 +741,39 @@ function bindingToApi(
})() })()
} }
hmrEvents(identifier: string) { hmrEvents(
return subscribe<TurbopackResult<Update>>(true, async (callback) => chunkName: string,
binding.projectHmrEvents(this._nativeProject, identifier, callback) 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, false,
async (callback) => async (callback) =>
binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback) binding.projectHmrChunkNamesSubscribe(
this._nativeProject,
target,
callback
)
) )
} }
......
...@@ -195,8 +195,30 @@ interface PartialUpdate extends BaseUpdate { ...@@ -195,8 +195,30 @@ interface PartialUpdate extends BaseUpdate {
export type Update = IssuesUpdate | PartialUpdate 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 */ /** @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 { ...@@ -246,11 +268,18 @@ export interface Project {
TurbopackResult<RawEntrypoints | {}> TurbopackResult<RawEntrypoints | {}>
> >
hmrEvents(identifier: string): AsyncIterableIterator<TurbopackResult<Update>> hmrEvents(
identifier: string,
hmrIdentifiersSubscribe(): AsyncIterableIterator< target: import('./index').HmrTarget.Client
TurbopackResult<HmrIdentifiers> ): 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> getSourceForAsset(filePath: string): Promise<string | null>
......
import type { NodeJsPartialHmrUpdate } from '../../build/swc/types'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
export { export {
createTemporaryReferenceSet, createTemporaryReferenceSet,
...@@ -66,7 +68,11 @@ if (process.env.NODE_ENV === 'development') { ...@@ -66,7 +68,11 @@ if (process.env.NODE_ENV === 'development') {
declare global { declare global {
var __next__clear_chunk_cache__: (() => void) | null | undefined var __next__clear_chunk_cache__: (() => void) | null | undefined
var __turbopack_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__` // hot-reloader modules are not bundled so we need to inject `__next__clear_chunk_cache__`
// into globalThis from this file which is bundled. // into globalThis from this file which is bundled.
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
......
...@@ -24,8 +24,10 @@ import type { ...@@ -24,8 +24,10 @@ import type {
TurbopackResult, TurbopackResult,
Project, Project,
Entrypoints, Entrypoints,
NodeJsHmrUpdate,
NodeJsPartialHmrUpdate,
} from '../../build/swc/types' } 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 * as Log from '../../build/output/log'
import { BLOCKED_PAGES } from '../../shared/lib/constants' import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { import {
...@@ -144,6 +146,98 @@ const sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random()) ...@@ -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 __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. * Replaces turbopack:///[project] with the specified project in the `source` field.
*/ */
...@@ -194,7 +288,8 @@ export async function createHotReloaderTurbopack( ...@@ -194,7 +288,8 @@ export async function createHotReloaderTurbopack(
serverFields: ServerFields, serverFields: ServerFields,
distDir: string, distDir: string,
resetFetch: () => void, resetFetch: () => void,
lockfile: Lockfile | undefined lockfile: Lockfile | undefined,
experimentalServerFastRefresh?: boolean
): Promise<NextJsHotReloaderInterface> { ): Promise<NextJsHotReloaderInterface> {
const dev = true const dev = true
const buildId = 'development' const buildId = 'development'
...@@ -513,6 +608,10 @@ export async function createHotReloaderTurbopack( ...@@ -513,6 +608,10 @@ export async function createHotReloaderTurbopack(
} }
} }
if (experimentalServerFastRefresh) {
setupServerHmr(project)
}
let hmrEventHappened = false let hmrEventHappened = false
let hmrHash = 0 let hmrHash = 0
...@@ -606,7 +705,7 @@ export async function createHotReloaderTurbopack( ...@@ -606,7 +705,7 @@ export async function createHotReloaderTurbopack(
sendEnqueuedMessagesDebounce() sendEnqueuedMessagesDebounce()
} }
async function subscribeToChanges( async function subscribeToClientChanges(
key: EntryKey, key: EntryKey,
includeIssues: boolean, includeIssues: boolean,
endpoint: Endpoint, endpoint: Endpoint,
...@@ -648,7 +747,7 @@ export async function createHotReloaderTurbopack( ...@@ -648,7 +747,7 @@ export async function createHotReloaderTurbopack(
changeSubscriptions.delete(key) changeSubscriptions.delete(key)
} }
async function unsubscribeFromChanges(key: EntryKey) { async function unsubscribeFromClientChanges(key: EntryKey) {
const subscription = await changeSubscriptions.get(key) const subscription = await changeSubscriptions.get(key)
if (subscription) { if (subscription) {
await subscription.return?.() await subscription.return?.()
...@@ -657,7 +756,7 @@ export async function createHotReloaderTurbopack( ...@@ -657,7 +756,7 @@ export async function createHotReloaderTurbopack(
currentEntryIssues.delete(key) currentEntryIssues.delete(key)
} }
async function subscribeToHmrEvents(client: ws, id: string) { async function subscribeToClientHmrEvents(client: ws, id: string) {
const key = getEntryKey('assets', 'client', id) const key = getEntryKey('assets', 'client', id)
if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) { if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {
// maybe throw an error / force the client to reload? // maybe throw an error / force the client to reload?
...@@ -669,7 +768,7 @@ export async function createHotReloaderTurbopack( ...@@ -669,7 +768,7 @@ export async function createHotReloaderTurbopack(
return return
} }
const subscription = project!.hmrEvents(id) const subscription = project!.hmrEvents(id, HmrTarget.Client)
state.subscriptions.set(id, subscription) state.subscriptions.set(id, subscription)
// The subscription will always emit once, which is the initial // The subscription will always emit once, which is the initial
...@@ -680,7 +779,7 @@ export async function createHotReloaderTurbopack( ...@@ -680,7 +779,7 @@ export async function createHotReloaderTurbopack(
for await (const data of subscription) { for await (const data of subscription) {
processIssues(state.clientIssues, key, data, false, true) processIssues(state.clientIssues, key, data, false, true)
if (data.type !== 'issues') { if (data.type !== 'issues') {
sendTurbopackMessage(data) sendTurbopackMessage(data as TurbopackUpdate)
} }
} }
} catch (e) { } catch (e) {
...@@ -698,7 +797,7 @@ export async function createHotReloaderTurbopack( ...@@ -698,7 +797,7 @@ export async function createHotReloaderTurbopack(
} }
} }
function unsubscribeFromHmrEvents(client: ws, id: string) { function unsubscribeFromClientHmrEvents(client: ws, id: string) {
const state = clientStates.get(client) const state = clientStates.get(client)
if (!state) { if (!state) {
return return
...@@ -775,9 +874,9 @@ export async function createHotReloaderTurbopack( ...@@ -775,9 +874,9 @@ export async function createHotReloaderTurbopack(
propagateServerField: propagateServerField.bind(null, opts), propagateServerField: propagateServerField.bind(null, opts),
sendHmr, sendHmr,
startBuilding, startBuilding,
subscribeToChanges, subscribeToChanges: subscribeToClientChanges,
unsubscribeFromChanges, unsubscribeFromChanges: unsubscribeFromClientChanges,
unsubscribeFromHmrEvents, unsubscribeFromHmrEvents: unsubscribeFromClientHmrEvents,
}, },
}, },
}) })
...@@ -1132,11 +1231,11 @@ export async function createHotReloaderTurbopack( ...@@ -1132,11 +1231,11 @@ export async function createHotReloaderTurbopack(
// Turbopack messages // Turbopack messages
switch (parsedData.type) { switch (parsedData.type) {
case 'turbopack-subscribe': case 'turbopack-subscribe':
subscribeToHmrEvents(client, parsedData.path) subscribeToClientHmrEvents(client, parsedData.path)
break break
case 'turbopack-unsubscribe': case 'turbopack-unsubscribe':
unsubscribeFromHmrEvents(client, parsedData.path) unsubscribeFromClientHmrEvents(client, parsedData.path)
break break
default: default:
...@@ -1446,7 +1545,7 @@ export async function createHotReloaderTurbopack( ...@@ -1446,7 +1545,7 @@ export async function createHotReloaderTurbopack(
productionRewrites: undefined, productionRewrites: undefined,
logErrors: true, logErrors: true,
hooks: { hooks: {
subscribeToChanges, subscribeToChanges: subscribeToClientChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => { handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result) currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths) assetMapper.setPathsForKey(id, result.clientPaths)
...@@ -1514,7 +1613,7 @@ export async function createHotReloaderTurbopack( ...@@ -1514,7 +1613,7 @@ export async function createHotReloaderTurbopack(
logErrors: true, logErrors: true,
hooks: { hooks: {
subscribeToChanges, subscribeToChanges: subscribeToClientChanges,
handleWrittenEndpoint: (id, result, forceDeleteCache) => { handleWrittenEndpoint: (id, result, forceDeleteCache) => {
currentWrittenEntrypoints.set(id, result) currentWrittenEntrypoints.set(id, result)
assetMapper.setPathsForKey(id, result.clientPaths) assetMapper.setPathsForKey(id, result.clientPaths)
......
...@@ -90,6 +90,7 @@ export async function initialize(opts: { ...@@ -90,6 +90,7 @@ export async function initialize(opts: {
keepAliveTimeout?: number keepAliveTimeout?: number
customServer?: boolean customServer?: boolean
experimentalHttpsServer?: boolean experimentalHttpsServer?: boolean
experimentalServerFastRefresh?: boolean
startServerSpan?: Span startServerSpan?: Span
quiet?: boolean quiet?: boolean
}): Promise<ServerInitResult> { }): Promise<ServerInitResult> {
...@@ -178,6 +179,7 @@ export async function initialize(opts: { ...@@ -178,6 +179,7 @@ export async function initialize(opts: {
port: opts.port, port: opts.port,
onDevServerCleanup: opts.onDevServerCleanup, onDevServerCleanup: opts.onDevServerCleanup,
resetFetch, resetFetch,
experimentalServerFastRefresh: opts.experimentalServerFastRefresh,
}) })
) )
......
...@@ -115,6 +115,7 @@ export type SetupOpts = { ...@@ -115,6 +115,7 @@ export type SetupOpts = {
port: number port: number
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined
resetFetch: () => void resetFetch: () => void
experimentalServerFastRefresh?: boolean
} }
export interface DevRoutesManifest { export interface DevRoutesManifest {
...@@ -237,7 +238,8 @@ async function startWatcher( ...@@ -237,7 +238,8 @@ async function startWatcher(
serverFields, serverFields,
distDir, distDir,
resetFetch, resetFetch,
lockfile lockfile,
opts.experimentalServerFastRefresh
) )
})() })()
: await (async () => { : await (async () => {
......
...@@ -136,6 +136,7 @@ export async function getRequestHandlers({ ...@@ -136,6 +136,7 @@ export async function getRequestHandlers({
minimalMode, minimalMode,
keepAliveTimeout, keepAliveTimeout,
experimentalHttpsServer, experimentalHttpsServer,
experimentalServerFastRefresh,
quiet, quiet,
}: { }: {
dir: string dir: string
...@@ -147,6 +148,7 @@ export async function getRequestHandlers({ ...@@ -147,6 +148,7 @@ export async function getRequestHandlers({
minimalMode?: boolean minimalMode?: boolean
keepAliveTimeout?: number keepAliveTimeout?: number
experimentalHttpsServer?: boolean experimentalHttpsServer?: boolean
experimentalServerFastRefresh?: boolean
quiet?: boolean quiet?: boolean
}): ReturnType<typeof initialize> { }): ReturnType<typeof initialize> {
return initialize({ return initialize({
...@@ -159,6 +161,7 @@ export async function getRequestHandlers({ ...@@ -159,6 +161,7 @@ export async function getRequestHandlers({
server, server,
keepAliveTimeout, keepAliveTimeout,
experimentalHttpsServer, experimentalHttpsServer,
experimentalServerFastRefresh,
startServerSpan, startServerSpan,
quiet, quiet,
}) })
...@@ -179,6 +182,7 @@ export async function startServer( ...@@ -179,6 +182,7 @@ export async function startServer(
allowRetry, allowRetry,
keepAliveTimeout, keepAliveTimeout,
selfSignedCertificate, selfSignedCertificate,
experimentalServerFastRefresh,
} = serverOptions } = serverOptions
let { port } = serverOptions let { port } = serverOptions
...@@ -479,6 +483,7 @@ export async function startServer( ...@@ -479,6 +483,7 @@ export async function startServer(
minimalMode, minimalMode,
keepAliveTimeout, keepAliveTimeout,
experimentalHttpsServer: !!selfSignedCertificate, experimentalHttpsServer: !!selfSignedCertificate,
experimentalServerFastRefresh,
}) })
requestHandler = initResult.requestHandler requestHandler = initResult.requestHandler
upgradeHandler = initResult.upgradeHandler upgradeHandler = initResult.upgradeHandler
......
import { NextInstance, createNext } from 'e2e-utils' import { NextInstance, createNext } from 'e2e-utils'
import { trace } from 'next/dist/trace' import { trace } from 'next/dist/trace'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants' 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 { import type {
Diagnostics, Diagnostics,
Issue, Issue,
...@@ -667,12 +667,15 @@ describe('next.rs api', () => { ...@@ -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) expect(result.done).toBe(false)
const identifiers = result.value.identifiers const chunkNames = result.value.chunkNames
expect(identifiers).toHaveProperty('length', expect.toBePositive()) expect(chunkNames).toHaveProperty('length', expect.toBePositive())
const subscriptions = identifiers.map((identifier) =>
project.hmrEvents(identifier) const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(chunkName, HmrTarget.Client)
) )
await Promise.all( await Promise.all(
subscriptions.map(async (subscription) => { subscriptions.map(async (subscription) => {
...@@ -794,12 +797,12 @@ describe('next.rs api', () => { ...@@ -794,12 +797,12 @@ describe('next.rs api', () => {
if (route.type !== 'page') throw new Error('unknown route type') if (route.type !== 'page') throw new Error('unknown route type')
await route.htmlEndpoint.writeToDisk() await route.htmlEndpoint.writeToDisk()
const result = await project.hmrIdentifiersSubscribe().next() const result = await project.hmrChunkNamesSubscribe(HmrTarget.Client).next()
expect(result.done).toBe(false) expect(result.done).toBe(false)
const identifiers = result.value.identifiers const chunkNames = result.value.chunkNames
const subscriptions = identifiers.map((identifier) => const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(identifier) project.hmrEvents(chunkName, HmrTarget.Client)
) )
await Promise.all( await Promise.all(
subscriptions.map(async (subscription) => { subscriptions.map(async (subscription) => {
......
/**
* Type definitions for Node.js HMR updates.
*
* IMPORTANT: This is a duplicate of the types in packages/next/src/build/swc/types.ts
* to avoid importing from an ES module, which makes TypeScript treat the file as an ES module.
*
* Keep NodeJsPartialHmrUpdate in sync with the copy in packages/next/src/build/swc/types.ts.
*/
interface NodeJsPartialHmrUpdate {
type: 'partial'
instruction: {
type: 'EcmascriptMergedUpdate'
entries: Record<
string,
{ code: string; url: string; map?: string | undefined }
>
chunks?: Record<string, { type: 'partial' }>
}
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="./hmr-types.d.ts" />
/// <reference path="../shared/runtime-utils.ts" /> /// <reference path="../shared/runtime-utils.ts" />
/// <reference path="../shared-node/base-externals-utils.ts" /> /// <reference path="../shared-node/base-externals-utils.ts" />
/// <reference path="../shared-node/node-externals-utils.ts" /> /// <reference path="../shared-node/node-externals-utils.ts" />
...@@ -337,6 +338,16 @@ function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean { ...@@ -337,6 +338,16 @@ function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
return regexJsUrl.test(chunkUrlOrPath) return regexJsUrl.test(chunkUrlOrPath)
} }
function __turbopack_server_hmr_apply__(
_update: NodeJsPartialHmrUpdate
): boolean {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__
module.exports = (sourcePath: ChunkPath) => ({ module.exports = (sourcePath: ChunkPath) => ({
m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id), m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData), c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),
......
...@@ -586,7 +586,8 @@ async function instantiateWebAssemblyFromPath(path, importsObj) { ...@@ -586,7 +586,8 @@ async function instantiateWebAssemblyFromPath(path, importsObj) {
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj); const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports; return instance.exports;
} }
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime-utils.ts" /> /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./hmr-types.d.ts" />
/// <reference path="../shared/runtime-utils.ts" />
/// <reference path="../shared-node/base-externals-utils.ts" /> /// <reference path="../shared-node/base-externals-utils.ts" />
/// <reference path="../shared-node/node-externals-utils.ts" /> /// <reference path="../shared-node/node-externals-utils.ts" />
/// <reference path="../shared-node/node-wasm-utils.ts" /> /// <reference path="../shared-node/node-wasm-utils.ts" />
...@@ -814,6 +815,12 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/; ...@@ -814,6 +815,12 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
*/ function isJs(chunkUrlOrPath) { */ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath); return regexJsUrl.test(chunkUrlOrPath);
} }
function __turbopack_server_hmr_apply__(_update) {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true;
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__;
module.exports = (sourcePath)=>({ module.exports = (sourcePath)=>({
m: (id)=>getOrInstantiateRuntimeModule(sourcePath, id), m: (id)=>getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData)=>loadRuntimeChunk(sourcePath, chunkData) c: (chunkData)=>loadRuntimeChunk(sourcePath, chunkData)
......
...@@ -586,7 +586,8 @@ async function instantiateWebAssemblyFromPath(path, importsObj) { ...@@ -586,7 +586,8 @@ async function instantiateWebAssemblyFromPath(path, importsObj) {
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj); const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports; return instance.exports;
} }
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime-utils.ts" /> /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./hmr-types.d.ts" />
/// <reference path="../shared/runtime-utils.ts" />
/// <reference path="../shared-node/base-externals-utils.ts" /> /// <reference path="../shared-node/base-externals-utils.ts" />
/// <reference path="../shared-node/node-externals-utils.ts" /> /// <reference path="../shared-node/node-externals-utils.ts" />
/// <reference path="../shared-node/node-wasm-utils.ts" /> /// <reference path="../shared-node/node-wasm-utils.ts" />
...@@ -814,6 +815,12 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/; ...@@ -814,6 +815,12 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
*/ function isJs(chunkUrlOrPath) { */ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath); return regexJsUrl.test(chunkUrlOrPath);
} }
function __turbopack_server_hmr_apply__(_update) {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true;
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__;
module.exports = (sourcePath)=>({ module.exports = (sourcePath)=>({
m: (id)=>getOrInstantiateRuntimeModule(sourcePath, id), m: (id)=>getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData)=>loadRuntimeChunk(sourcePath, chunkData) c: (chunkData)=>loadRuntimeChunk(sourcePath, chunkData)
......
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