Unverified Commit 014b9987 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: implement module.hot.accept(deps, cb) and module.hot.decline(deps) (#90443)

### What?

Implements dependency-level HMR accept and decline for Turbopack,
covering both ESM (`import.meta.turbopackHot`) and CJS (`module.hot`)
modules.

Previously Turbopack only supported self-accept (`module.hot.accept()`
with no arguments) and self-decline. This PR adds the full
dependency-targeted API:

- `module.hot.accept(dep, cb)` / `import.meta.turbopackHot.accept(dep,
cb)` — single dep
- `module.hot.accept([depA, depB], cb)` /
`import.meta.turbopackHot.accept([depA, depB], cb)` — array of deps
- `module.hot.decline(dep)` / `import.meta.turbopackHot.decline(dep)` —
single dep
- `module.hot.decline([depA, depB])` /
`import.meta.turbopackHot.decline([depA, depB])` — array of deps

### Why?

Libraries like `react-refresh` and user code often need to accept
updates for specific dependencies rather than self-accepting the entire
module. Without this, those HMR patterns fall back to full page reloads
in Turbopack.

### How?

**Runtime** (`turbopack-ecmascript-runtime`):
- Extended `HotState` with `acceptedDependencies`,
`acceptedErrorHandlers`, and `declinedDependencies` maps (keyed by
`ModuleId`)
- Updated `hot.accept()` and `hot.decline()` to handle string and array
signatures
- Updated `getAffectedModuleEffects` to check accepted/declined
dependencies when propagating updates through the module graph
- Added `'declined'` effect type that throws an `UpdateApplyError`
- Track `outdatedDependencies` (map of parent → set of updated deps)
alongside `outdatedModules`
- In the apply phase, invoke per-dependency accept callbacks with the
correct outdated deps
- Use `Set` for `outdatedDependencies` dedup (O(1) vs O(n) lookups)

**Compiler** (`turbopack-ecmascript`):
- Added `ModuleHotReferenceAssetReference` — a single asset reference
type for both accept and decline deps, with shared resolve logic for ESM
(`esm_resolve`) and CJS (`cjs_resolve`)
- Added `ModuleHotReferenceCodeGen` — generates code that replaces dep
string literals with resolved module IDs at compile time
- ESM binding auto-update: when an ESM module accepts a dependency that
it also `import`s, the compiler wraps the accept callback to re-import
the namespace variable (`__TURBOPACK__imported__module__<id> =
__turbopack_import__(<id>)`) before the user callback runs, so ESM
bindings reflect updated values without needing `require()`
- Added `import.meta.turbopackHot` as the ESM equivalent of
`module.hot`, with TypeScript type declarations in
`packages/next/types/global.d.ts`
- Static analysis extracts dep strings from
`module.hot.accept`/`decline` calls; non-analyzable deps emit a warning
with distinct error codes (`TP1204` for accept, `TP1205` for decline)

**HMR gating** (`CompileTimeInfo`):
- Added `hot_module_replacement_enabled` flag to `CompileTimeInfo` to
gate recognition of `module.hot` and `import.meta.turbopackHot` as
well-known objects
- Without this flag, production builds would recognize
`module.hot.accept(...)` and generate HMR-specific code, leading to
runtime errors
- Flag set to `true` for dev servers and `false` for production builds
across Next.js and turbopack-cli entry points
- `import.meta.turbopackHot` getter is only emitted when HMR is enabled

**Server HMR** (`next-api`, `next-core`):
- Server-side `compile_time_info` now also sets
`hot_module_replacement_enabled` so that `module.hot` /
`import.meta.turbopackHot` are recognized during analysis of server
modules
- Server HMR requires the `--experimental-server-fast-refresh` CLI flag;
the flag is passed through `ProjectOptions` to the Rust side so
`server_compile_time_info` only enables HMR when appropriate

**Tests** (`test/development/app-dir/hmr-dep-accept/`):
- ESM single dep accept — verifies parent module is not re-evaluated,
accept callback fires, ESM bindings auto-update
- ESM array dep accept — same as above with `accept(['./dep-a',
'./dep-b'], cb)`
- CJS `module.hot.accept` — pure CJS dep observer pattern with `.cjs`
files
- Single dep decline — verifies full page reload occurs
- Array dep decline — verifies full page reload with
`decline(['./dep-a', './dep-b'])`
parent 6a733742
...@@ -367,6 +367,9 @@ pub struct ProjectOptions { ...@@ -367,6 +367,9 @@ pub struct ProjectOptions {
/// The version of Next.js that is running. /// The version of Next.js that is running.
pub next_version: RcStr, pub next_version: RcStr,
/// Whether server-side HMR is enabled (--experimental-server-fast-refresh).
pub server_hmr: bool,
} }
#[derive(Default)] #[derive(Default)]
...@@ -797,6 +800,7 @@ impl ProjectContainer { ...@@ -797,6 +800,7 @@ impl ProjectContainer {
let debug_build_paths; let debug_build_paths;
let deferred_entries; let deferred_entries;
let is_persistent_caching_enabled; let is_persistent_caching_enabled;
let server_hmr;
{ {
let options = self.options_state.get(); let options = self.options_state.get();
let options = options let options = options
...@@ -824,6 +828,7 @@ impl ProjectContainer { ...@@ -824,6 +828,7 @@ impl ProjectContainer {
debug_build_paths = options.debug_build_paths.clone(); debug_build_paths = options.debug_build_paths.clone();
deferred_entries = options.deferred_entries.clone().unwrap_or_default(); deferred_entries = options.deferred_entries.clone().unwrap_or_default();
is_persistent_caching_enabled = options.is_persistent_caching_enabled; is_persistent_caching_enabled = options.is_persistent_caching_enabled;
server_hmr = options.server_hmr;
} }
let dist_dir = next_config.dist_dir().owned().await?; let dist_dir = next_config.dist_dir().owned().await?;
...@@ -853,6 +858,7 @@ impl ProjectContainer { ...@@ -853,6 +858,7 @@ impl ProjectContainer {
debug_build_paths, debug_build_paths,
deferred_entries, deferred_entries,
is_persistent_caching_enabled, is_persistent_caching_enabled,
server_hmr,
} }
.cell()) .cell())
} }
...@@ -953,6 +959,9 @@ pub struct Project { ...@@ -953,6 +959,9 @@ pub struct Project {
/// Whether to enable persistent caching /// Whether to enable persistent caching
is_persistent_caching_enabled: bool, is_persistent_caching_enabled: bool,
/// Whether server-side HMR is enabled (--experimental-server-fast-refresh).
server_hmr: bool,
} }
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -1258,12 +1267,14 @@ impl Project { ...@@ -1258,12 +1267,14 @@ impl Project {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub(super) fn client_compile_time_info(&self) -> Vc<CompileTimeInfo> { pub(super) async fn client_compile_time_info(&self) -> Result<Vc<CompileTimeInfo>> {
get_client_compile_time_info( let next_mode = self.mode.await?;
Ok(get_client_compile_time_info(
self.browserslist_query.clone(), self.browserslist_query.clone(),
self.define_env.client(), self.define_env.client(),
self.next_config.report_system_env_inlining(), self.next_config.report_system_env_inlining(),
) next_mode.is_development(),
))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -1515,6 +1526,7 @@ impl Project { ...@@ -1515,6 +1526,7 @@ impl Project {
this.define_env.nodejs(), this.define_env.nodejs(),
self.current_node_js_version(), self.current_node_js_version(),
this.next_config.report_system_env_inlining(), this.next_config.report_system_env_inlining(),
this.server_hmr,
)) ))
} }
......
...@@ -188,6 +188,7 @@ fn main() { ...@@ -188,6 +188,7 @@ fn main() {
deferred_entries: None, deferred_entries: None,
is_persistent_caching_enabled: false, is_persistent_caching_enabled: false,
next_version: rcstr!("0.0.0"), next_version: rcstr!("0.0.0"),
server_hmr: false,
}; };
let json = serde_json::to_string_pretty(&options).unwrap(); let json = serde_json::to_string_pretty(&options).unwrap();
......
...@@ -106,6 +106,7 @@ pub async fn get_client_compile_time_info( ...@@ -106,6 +106,7 @@ pub async fn get_client_compile_time_info(
browserslist_query: RcStr, browserslist_query: RcStr,
define_env: Vc<OptionEnvMap>, define_env: Vc<OptionEnvMap>,
report_system_env_inlining: Vc<IssueSeverity>, report_system_env_inlining: Vc<IssueSeverity>,
hot_module_replacement_enabled: bool,
) -> Result<Vc<CompileTimeInfo>> { ) -> Result<Vc<CompileTimeInfo>> {
CompileTimeInfo::builder( CompileTimeInfo::builder(
Environment::new(ExecutionEnvironment::Browser( Environment::new(ExecutionEnvironment::Browser(
...@@ -126,6 +127,7 @@ pub async fn get_client_compile_time_info( ...@@ -126,6 +127,7 @@ pub async fn get_client_compile_time_info(
.to_resolved() .to_resolved()
.await?, .await?,
) )
.hot_module_replacement_enabled(hot_module_replacement_enabled)
.cell() .cell()
.await .await
} }
......
...@@ -339,6 +339,7 @@ pub async fn get_server_compile_time_info( ...@@ -339,6 +339,7 @@ pub async fn get_server_compile_time_info(
define_env: Vc<OptionEnvMap>, define_env: Vc<OptionEnvMap>,
node_version: ResolvedVc<NodeJsVersion>, node_version: ResolvedVc<NodeJsVersion>,
report_system_env_inlining: Vc<IssueSeverity>, report_system_env_inlining: Vc<IssueSeverity>,
hot_module_replacement_enabled: bool,
) -> Result<Vc<CompileTimeInfo>> { ) -> Result<Vc<CompileTimeInfo>> {
CompileTimeInfo::builder( CompileTimeInfo::builder(
Environment::new(ExecutionEnvironment::NodeJsLambda( Environment::new(ExecutionEnvironment::NodeJsLambda(
...@@ -358,6 +359,7 @@ pub async fn get_server_compile_time_info( ...@@ -358,6 +359,7 @@ pub async fn get_server_compile_time_info(
.to_resolved() .to_resolved()
.await?, .await?,
) )
.hot_module_replacement_enabled(hot_module_replacement_enabled)
.cell() .cell()
.await .await
} }
......
...@@ -211,6 +211,9 @@ pub struct NapiProjectOptions { ...@@ -211,6 +211,9 @@ pub struct NapiProjectOptions {
/// The version of Next.js that is running. /// The version of Next.js that is running.
pub next_version: RcStr, pub next_version: RcStr,
/// Whether server-side HMR is enabled (--experimental-server-fast-refresh).
pub server_hmr: Option<bool>,
} }
/// [NapiProjectOptions] with all fields optional. /// [NapiProjectOptions] with all fields optional.
...@@ -318,6 +321,7 @@ impl From<NapiProjectOptions> for ProjectOptions { ...@@ -318,6 +321,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
deferred_entries, deferred_entries,
is_persistent_caching_enabled, is_persistent_caching_enabled,
next_version, next_version,
server_hmr,
} = val; } = val;
ProjectOptions { ProjectOptions {
root_path, root_path,
...@@ -341,6 +345,7 @@ impl From<NapiProjectOptions> for ProjectOptions { ...@@ -341,6 +345,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
deferred_entries, deferred_entries,
is_persistent_caching_enabled, is_persistent_caching_enabled,
next_version, next_version,
server_hmr: server_hmr.unwrap_or(false),
} }
} }
} }
......
...@@ -247,6 +247,8 @@ export interface NapiProjectOptions { ...@@ -247,6 +247,8 @@ export interface NapiProjectOptions {
isPersistentCachingEnabled: boolean isPersistentCachingEnabled: boolean
/** The version of Next.js that is running. */ /** The version of Next.js that is running. */
nextVersion: RcStr nextVersion: RcStr
/** Whether server-side HMR is enabled (requires --experimental-server-fast-refresh). */
serverHmr?: boolean
} }
/** [NapiProjectOptions] with all fields optional. */ /** [NapiProjectOptions] with all fields optional. */
export interface NapiPartialProjectOptions { export interface NapiPartialProjectOptions {
...@@ -291,6 +293,8 @@ export interface NapiPartialProjectOptions { ...@@ -291,6 +293,8 @@ export interface NapiPartialProjectOptions {
* debugging/profiling purposes. * debugging/profiling purposes.
*/ */
noMangling?: boolean noMangling?: boolean
/** Whether server-side HMR is enabled (requires --experimental-server-fast-refresh). */
serverHmr?: boolean
} }
export interface NapiDefineEnv { export interface NapiDefineEnv {
client: Array<NapiOptionEnvVar> client: Array<NapiOptionEnvVar>
......
...@@ -413,6 +413,7 @@ export async function createHotReloaderTurbopack( ...@@ -413,6 +413,7 @@ export async function createHotReloaderTurbopack(
opts.nextConfig opts.nextConfig
), ),
nextVersion: process.env.__NEXT_VERSION as string, nextVersion: process.env.__NEXT_VERSION as string,
serverHmr: experimentalServerFastRefresh,
}, },
{ {
memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit, memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,
......
...@@ -70,6 +70,26 @@ declare module 'client-only' { ...@@ -70,6 +70,26 @@ declare module 'client-only' {
*/ */
} }
interface TurbopackHotApi {
accept(): void
accept(cb: () => void): void
accept(dep: string | string[], cb?: () => void): void
decline(): void
decline(dep: string | string[]): void
dispose(cb: (data: Record<string, unknown>) => void): void
invalidate(): void
readonly data: Record<string, unknown>
}
interface ImportMeta {
/**
* The HMR API for ESM modules when using Turbopack.
* Equivalent to `module.hot` in CommonJS modules.
* Only available in development mode.
*/
turbopackHot?: TurbopackHotApi
}
interface Window { interface Window {
MSInputMethodContext?: unknown MSInputMethodContext?: unknown
/** @internal */ /** @internal */
......
'use client'
import { useEffect, useState, useRef } from 'react'
import { valueA } from './dep-a'
import { valueB } from './dep-b'
const evaluatedAt = Date.now()
export default function DepAcceptArrayPage() {
const [depAValue, setDepAValue] = useState(valueA)
const [depBValue, setDepBValue] = useState(valueB)
const [acceptCallCount, setAcceptCallCount] = useState(0)
const [evalTime, setEvalTime] = useState<number | null>(null)
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
setEvalTime(evaluatedAt)
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
if (import.meta.turbopackHot) {
import.meta.turbopackHot.accept(['./dep-a', './dep-b'], () => {
// ESM bindings are automatically re-imported before this callback runs,
// so `valueA` and `valueB` already reflect the updated modules.
if (mountedRef.current) {
setDepAValue(valueA)
setDepBValue(valueB)
setAcceptCallCount((c) => c + 1)
}
})
}
}, [])
return (
<div>
<p id="dep-a-value">{depAValue}</p>
<p id="dep-b-value">{depBValue}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
<p id="accept-call-count">Accept Calls: {acceptCallCount}</p>
</div>
)
}
let dep = require('./dep.cjs')
let currentValue = dep.value
let acceptCallCount = 0
const listeners = new Set()
if (module.hot) {
module.hot.accept('./dep.cjs', () => {
dep = require('./dep.cjs')
currentValue = dep.value
acceptCallCount++
listeners.forEach((fn) => fn(currentValue, acceptCallCount))
})
}
module.exports = {
getValue() {
return currentValue
},
getAcceptCallCount() {
return acceptCallCount
},
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
},
}
'use client'
import { useEffect, useState } from 'react'
import { getValue, getAcceptCallCount, subscribe } from './dep-observer.cjs'
// Track when this module was evaluated (should NOT change on dep update)
const evaluatedAt = Date.now()
export default function DepAcceptCjsPage() {
const [depValue, setDepValue] = useState(getValue())
const [acceptCallCount, setAcceptCallCount] = useState(getAcceptCallCount())
const [evalTime, setEvalTime] = useState<number | null>(null)
useEffect(() => {
setEvalTime(evaluatedAt)
// dep-observer.cjs registers module.hot.accept('./dep', cb) in CJS context.
// When dep.ts changes, the CJS module handles it and notifies subscribers.
return subscribe((newValue: string, newCount: number) => {
setDepValue(newValue)
setAcceptCallCount(newCount)
})
}, [])
return (
<div>
<p id="dep-value">{depValue}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
<p id="accept-call-count">Accept Calls: {acceptCallCount}</p>
</div>
)
}
// This module exports a value and does NOT self-accept.
// The parent page will accept updates for this module.
export const value = 'initial'
'use client'
import { useEffect, useState, useRef } from 'react'
import { value } from './dep'
// Track when this module was evaluated (should NOT change on dep update)
const evaluatedAt = Date.now()
export default function DepAcceptPage() {
const [depValue, setDepValue] = useState(value)
const [acceptCallCount, setAcceptCallCount] = useState(0)
const [evalTime, setEvalTime] = useState<number | null>(null)
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
// Set eval time on client only to avoid hydration mismatch
setEvalTime(evaluatedAt)
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
// import.meta.turbopackHot is the ESM equivalent of module.hot
if (import.meta.turbopackHot) {
import.meta.turbopackHot.accept('./dep', () => {
// ESM bindings are automatically re-imported before this callback runs,
// so `value` already reflects the updated module.
if (mountedRef.current) {
setDepValue(value)
setAcceptCallCount((c) => c + 1)
}
})
}
}, [])
return (
<div>
<p id="dep-value">{depValue}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
<p id="accept-call-count">Accept Calls: {acceptCallCount}</p>
</div>
)
}
'use client'
import { useEffect, useState } from 'react'
import { valueA } from './dep-a'
import { valueB } from './dep-b'
// Track when this module was evaluated
const evaluatedAt = Date.now()
export default function DepDeclineArrayPage() {
const [evalTime, setEvalTime] = useState<number | null>(null)
useEffect(() => {
setEvalTime(evaluatedAt)
}, [])
useEffect(() => {
if (import.meta.turbopackHot) {
// Decline updates for both dependencies — should trigger full reload
import.meta.turbopackHot.decline(['./dep-a', './dep-b'])
}
}, [])
return (
<div>
<p id="dep-a-value">{valueA}</p>
<p id="dep-b-value">{valueB}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
</div>
)
}
// This module exports a value and does NOT self-accept.
// The parent page will decline updates for this module.
export const value = 'initial'
'use client'
import { useEffect, useState } from 'react'
import { value } from './dep'
// Track when this module was evaluated
const evaluatedAt = Date.now()
export default function DepDeclinePage() {
const [evalTime, setEvalTime] = useState<number | null>(null)
useEffect(() => {
setEvalTime(evaluatedAt)
}, [])
useEffect(() => {
if (import.meta.turbopackHot) {
// Decline updates for this dependency — should trigger full reload
import.meta.turbopackHot.decline('./dep')
}
}, [])
return (
<div>
<p id="dep-value">{value}</p>
{evalTime !== null && (
<p id="parent-eval-time">Parent Evaluated At: {evalTime}</p>
)}
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('hmr-dep-accept', () => {
const { next, isTurbopack, isNextDev } = nextTestSetup({
files: __dirname,
})
// Dependency accept/decline requires Turbopack dev mode
const itTurbopackDev = isTurbopack && isNextDev ? it : it.skip
describe('dependency accept', () => {
itTurbopackDev(
'parent accepts child dependency update without re-evaluating',
async () => {
const browser = await next.browser('/dep-accept')
// Wait for initial render and hydration (eval time only appears after useEffect)
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('initial')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
// Capture the parent evaluation timestamp
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Verify initial accept call count
const initialCallCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(initialCallCount).toBe('Accept Calls: 0')
// Patch the dependency to change its exported value
await next.patchFile('app/dep-accept/dep.ts', (content) =>
content.replace("'initial'", "'updated'")
)
// Wait for the accept callback to fire and update the UI
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('updated')
})
// The accept callback should have been called
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 1')
})
// The parent module should NOT have been re-evaluated
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).toBe(parentEvalTime)
}
)
})
describe('dependency accept with array', () => {
itTurbopackDev(
'parent accepts multiple child dependencies via array',
async () => {
const browser = await next.browser('/dep-accept-array')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('initial-a')
})
await retry(async () => {
const text = await browser.elementByCss('#dep-b-value').text()
expect(text).toBe('initial-b')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Patch dep-a
await next.patchFile('app/dep-accept-array/dep-a.ts', (content) =>
content.replace("'initial-a'", "'updated-a'")
)
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('updated-a')
})
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 1')
})
// Parent should NOT have been re-evaluated
const evalTimeAfterA = await browser
.elementByCss('#parent-eval-time')
.text()
expect(evalTimeAfterA).toBe(parentEvalTime)
// Patch dep-b
await next.patchFile('app/dep-accept-array/dep-b.ts', (content) =>
content.replace("'initial-b'", "'updated-b'")
)
await retry(async () => {
const text = await browser.elementByCss('#dep-b-value').text()
expect(text).toBe('updated-b')
})
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 2')
})
// Parent should still NOT have been re-evaluated
const evalTimeAfterB = await browser
.elementByCss('#parent-eval-time')
.text()
expect(evalTimeAfterB).toBe(parentEvalTime)
}
)
})
describe('dependency accept via module.hot (CJS)', () => {
itTurbopackDev(
'CJS module registers module.hot.accept and receives dep updates',
async () => {
const browser = await next.browser('/dep-accept-cjs')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('initial')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(await browser.elementByCss('#accept-call-count').text()).toBe(
'Accept Calls: 0'
)
// Patch the dependency
await next.patchFile('app/dep-accept-cjs/dep.cjs', (content) =>
content.replace("'initial'", "'updated'")
)
// dep-observer.cjs handles the update via module.hot.accept
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('updated')
})
await retry(async () => {
const callCount = await browser
.elementByCss('#accept-call-count')
.text()
expect(callCount).toBe('Accept Calls: 1')
})
// page.tsx should NOT have been re-evaluated (no full reload)
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).toBe(parentEvalTime)
}
)
})
describe('dependency decline', () => {
itTurbopackDev(
'declining a dependency triggers full reload on update',
async () => {
const browser = await next.browser('/dep-decline')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('initial')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Patch the declined dependency
await next.patchFile('app/dep-decline/dep.ts', (content) =>
content.replace("'initial'", "'updated'")
)
// Since the dep is declined, the update should cause a full page reload.
// After reload, the page re-evaluates with the new dep value.
await retry(async () => {
const text = await browser.elementByCss('#dep-value').text()
expect(text).toBe('updated')
})
// The parent module SHOULD have been re-evaluated (full reload)
await retry(async () => {
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).not.toBe(parentEvalTime)
})
}
)
})
describe('dependency decline with array', () => {
itTurbopackDev(
'declining multiple dependencies via array triggers full reload',
async () => {
const browser = await next.browser('/dep-decline-array')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('initial-a')
})
await retry(async () => {
const text = await browser.elementByCss('#dep-b-value').text()
expect(text).toBe('initial-b')
})
await retry(async () => {
const text = await browser.elementByCss('#parent-eval-time').text()
expect(text).toMatch(/Parent Evaluated At: \d+/)
})
const parentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
// Patch dep-a (declined) — should trigger full reload
await next.patchFile('app/dep-decline-array/dep-a.ts', (content) =>
content.replace("'initial-a'", "'updated-a'")
)
await retry(async () => {
const text = await browser.elementByCss('#dep-a-value').text()
expect(text).toBe('updated-a')
})
// The parent module SHOULD have been re-evaluated (full reload)
await retry(async () => {
const newParentEvalTime = await browser
.elementByCss('#parent-eval-time')
.text()
expect(newParentEvalTime).not.toBe(parentEvalTime)
})
}
)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -224,7 +224,8 @@ async fn build_internal( ...@@ -224,7 +224,8 @@ async fn build_internal(
NodeEnv::Production => RuntimeType::Production, NodeEnv::Production => RuntimeType::Production,
}; };
let compile_time_info = get_client_compile_time_info(browserslist_query.clone(), node_env); let compile_time_info =
get_client_compile_time_info(browserslist_query.clone(), node_env, false);
let node_backend = child_process_backend(); let node_backend = child_process_backend();
let execution_context = ExecutionContext::new( let execution_context = ExecutionContext::new(
root_path.clone(), root_path.clone(),
......
...@@ -197,6 +197,7 @@ fn client_defines(node_env: &NodeEnv) -> CompileTimeDefines { ...@@ -197,6 +197,7 @@ fn client_defines(node_env: &NodeEnv) -> CompileTimeDefines {
pub async fn get_client_compile_time_info( pub async fn get_client_compile_time_info(
browserslist_query: RcStr, browserslist_query: RcStr,
node_env: Vc<NodeEnv>, node_env: Vc<NodeEnv>,
hot_module_replacement_enabled: bool,
) -> Result<Vc<CompileTimeInfo>> { ) -> Result<Vc<CompileTimeInfo>> {
let node_env = node_env.await?; let node_env = node_env.await?;
CompileTimeInfo::builder( CompileTimeInfo::builder(
...@@ -216,6 +217,7 @@ pub async fn get_client_compile_time_info( ...@@ -216,6 +217,7 @@ pub async fn get_client_compile_time_info(
.free_var_references( .free_var_references(
free_var_references!(..client_defines(&node_env).into_iter()).resolved_cell(), free_var_references!(..client_defines(&node_env).into_iter()).resolved_cell(),
) )
.hot_module_replacement_enabled(hot_module_replacement_enabled)
.cell() .cell()
.await .await
} }
...@@ -113,7 +113,7 @@ pub async fn create_web_entry_source( ...@@ -113,7 +113,7 @@ pub async fn create_web_entry_source(
source_maps_type: SourceMapsType, source_maps_type: SourceMapsType,
browserslist_query: RcStr, browserslist_query: RcStr,
) -> Result<Vc<Box<dyn ContentSource>>> { ) -> Result<Vc<Box<dyn ContentSource>>> {
let compile_time_info = get_client_compile_time_info(browserslist_query, node_env); let compile_time_info = get_client_compile_time_info(browserslist_query, node_env, true);
let asset_context = get_client_asset_context( let asset_context = get_client_asset_context(
root_path.clone(), root_path.clone(),
execution_context, execution_context,
......
...@@ -455,6 +455,7 @@ pub struct CompileTimeInfo { ...@@ -455,6 +455,7 @@ pub struct CompileTimeInfo {
pub environment: ResolvedVc<Environment>, pub environment: ResolvedVc<Environment>,
pub defines: ResolvedVc<CompileTimeDefines>, pub defines: ResolvedVc<CompileTimeDefines>,
pub free_var_references: ResolvedVc<FreeVarReferences>, pub free_var_references: ResolvedVc<FreeVarReferences>,
pub hot_module_replacement_enabled: bool,
} }
impl CompileTimeInfo { impl CompileTimeInfo {
...@@ -463,6 +464,7 @@ impl CompileTimeInfo { ...@@ -463,6 +464,7 @@ impl CompileTimeInfo {
environment, environment,
defines: None, defines: None,
free_var_references: None, free_var_references: None,
hot_module_replacement_enabled: false,
} }
} }
} }
...@@ -475,6 +477,7 @@ impl CompileTimeInfo { ...@@ -475,6 +477,7 @@ impl CompileTimeInfo {
environment, environment,
defines: CompileTimeDefines::empty().to_resolved().await?, defines: CompileTimeDefines::empty().to_resolved().await?,
free_var_references: FreeVarReferences::empty().to_resolved().await?, free_var_references: FreeVarReferences::empty().to_resolved().await?,
hot_module_replacement_enabled: false,
} }
.cell()) .cell())
} }
...@@ -489,6 +492,7 @@ pub struct CompileTimeInfoBuilder { ...@@ -489,6 +492,7 @@ pub struct CompileTimeInfoBuilder {
environment: ResolvedVc<Environment>, environment: ResolvedVc<Environment>,
defines: Option<ResolvedVc<CompileTimeDefines>>, defines: Option<ResolvedVc<CompileTimeDefines>>,
free_var_references: Option<ResolvedVc<FreeVarReferences>>, free_var_references: Option<ResolvedVc<FreeVarReferences>>,
hot_module_replacement_enabled: bool,
} }
impl CompileTimeInfoBuilder { impl CompileTimeInfoBuilder {
...@@ -505,6 +509,11 @@ impl CompileTimeInfoBuilder { ...@@ -505,6 +509,11 @@ impl CompileTimeInfoBuilder {
self self
} }
pub fn hot_module_replacement_enabled(mut self, enabled: bool) -> Self {
self.hot_module_replacement_enabled = enabled;
self
}
pub async fn build(self) -> Result<CompileTimeInfo> { pub async fn build(self) -> Result<CompileTimeInfo> {
Ok(CompileTimeInfo { Ok(CompileTimeInfo {
environment: self.environment, environment: self.environment,
...@@ -516,6 +525,7 @@ impl CompileTimeInfoBuilder { ...@@ -516,6 +525,7 @@ impl CompileTimeInfoBuilder {
Some(free_var_references) => free_var_references, Some(free_var_references) => free_var_references,
None => FreeVarReferences::empty().to_resolved().await?, None => FreeVarReferences::empty().to_resolved().await?,
}, },
hot_module_replacement_enabled: self.hot_module_replacement_enabled,
}) })
} }
......
...@@ -22,13 +22,16 @@ interface HotState { ...@@ -22,13 +22,16 @@ interface HotState {
selfDeclined: boolean selfDeclined: boolean
selfInvalidated: boolean selfInvalidated: boolean
disposeHandlers: ((data: object) => void)[] disposeHandlers: ((data: object) => void)[]
acceptedDependencies: Record<ModuleId, AcceptCallback | (() => void)>
acceptedErrorHandlers: Record<ModuleId, AcceptErrorHandler | undefined>
declinedDependencies: Record<ModuleId, true>
} }
type AcceptErrorHandler = ( type AcceptErrorHandler = (
err: Error, err: Error,
context: { moduleId: ModuleId; dependencyId: string | number } context: { moduleId: ModuleId; dependencyId: ModuleId }
) => void ) => void
type AcceptCallback = (outdatedDependencies: string[]) => void type AcceptCallback = (outdatedDependencies: ModuleId[]) => void
interface AcceptFunction { interface AcceptFunction {
// accept updates for self // accept updates for self
......
...@@ -1741,6 +1741,10 @@ impl JsValue { ...@@ -1741,6 +1741,10 @@ impl JsValue {
"import.meta", "import.meta",
"The import.meta object" "The import.meta object"
), ),
WellKnownObjectKind::ModuleHot => (
"module.hot",
"The module.hot HMR API"
),
}; };
if depth > 0 { if depth > 0 {
let i = hints.len(); let i = hints.len();
...@@ -1879,6 +1883,14 @@ impl JsValue { ...@@ -1879,6 +1883,14 @@ impl JsValue {
"URL".to_string(), "URL".to_string(),
"The standard URL constructor: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL" "The standard URL constructor: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL"
), ),
WellKnownFunctionKind::ModuleHotAccept => (
"module.hot.accept".to_string(),
"The module.hot.accept HMR API: https://webpack.js.org/api/hot-module-replacement/#accept"
),
WellKnownFunctionKind::ModuleHotDecline => (
"module.hot.decline".to_string(),
"The module.hot.decline HMR API: https://webpack.js.org/api/hot-module-replacement/#decline"
),
}; };
if depth > 0 { if depth > 0 {
let i = hints.len(); let i = hints.len();
...@@ -3328,6 +3340,8 @@ pub enum WellKnownObjectKind { ...@@ -3328,6 +3340,8 @@ pub enum WellKnownObjectKind {
ImportMeta, ImportMeta,
/// An iterator object, used to model generator return values. /// An iterator object, used to model generator return values.
Generator, Generator,
/// The `module.hot` object providing HMR API.
ModuleHot,
} }
impl WellKnownObjectKind { impl WellKnownObjectKind {
...@@ -3473,6 +3487,10 @@ pub enum WellKnownFunctionKind { ...@@ -3473,6 +3487,10 @@ pub enum WellKnownFunctionKind {
// The worker_threads Worker class // The worker_threads Worker class
NodeWorkerConstructor, NodeWorkerConstructor,
URLConstructor, URLConstructor,
/// `module.hot.accept(deps, callback, errorHandler)` — accept HMR updates for dependencies.
ModuleHotAccept,
/// `module.hot.decline(deps)` — decline HMR updates for dependencies.
ModuleHotDecline,
} }
impl WellKnownFunctionKind { impl WellKnownFunctionKind {
......
...@@ -60,6 +60,17 @@ pub async fn replace_well_known( ...@@ -60,6 +60,17 @@ pub async fn replace_well_known(
), ),
_ => (value, false), _ => (value, false),
}, },
// module.hot → WellKnownObject(ModuleHot) (only when HMR is enabled)
JsValue::Member(_, box JsValue::FreeVar(ref name), box ref prop)
if &**name == "module"
&& prop.as_str() == Some("hot")
&& compile_time_info.await?.hot_module_replacement_enabled =>
{
(
JsValue::WellKnownObject(WellKnownObjectKind::ModuleHot),
true,
)
}
_ => (value, false), _ => (value, false),
}) })
} }
...@@ -624,6 +635,32 @@ async fn well_known_object_member( ...@@ -624,6 +635,32 @@ async fn well_known_object_member(
WellKnownObjectKind::NodePreGyp => node_pre_gyp(prop), WellKnownObjectKind::NodePreGyp => node_pre_gyp(prop),
WellKnownObjectKind::NodeExpressApp => express(prop), WellKnownObjectKind::NodeExpressApp => express(prop),
WellKnownObjectKind::NodeProtobufLoader => protobuf_loader(prop), WellKnownObjectKind::NodeProtobufLoader => protobuf_loader(prop),
WellKnownObjectKind::ImportMeta => match prop.as_str() {
// import.meta.turbopackHot is the ESM equivalent of module.hot for HMR
Some("turbopackHot") if compile_time_info.await?.hot_module_replacement_enabled => {
JsValue::WellKnownObject(WellKnownObjectKind::ModuleHot)
}
_ => {
return Ok((
JsValue::member(Box::new(JsValue::WellKnownObject(kind)), Box::new(prop)),
false,
));
}
},
WellKnownObjectKind::ModuleHot => match prop.as_str() {
Some("accept") => JsValue::WellKnownFunction(WellKnownFunctionKind::ModuleHotAccept),
Some("decline") => JsValue::WellKnownFunction(WellKnownFunctionKind::ModuleHotDecline),
_ => {
return Ok((
JsValue::unknown(
JsValue::member(Box::new(JsValue::WellKnownObject(kind)), Box::new(prop)),
true,
"unsupported property on module.hot",
),
true,
));
}
},
#[allow(unreachable_patterns)] #[allow(unreachable_patterns)]
_ => { _ => {
return Ok(( return Ok((
......
...@@ -33,6 +33,7 @@ use crate::{ ...@@ -33,6 +33,7 @@ use crate::{
url::UrlAssetReferenceCodeGen, url::UrlAssetReferenceCodeGen,
}, },
exports_info::{ExportsInfoBinding, ExportsInfoRef}, exports_info::{ExportsInfoBinding, ExportsInfoRef},
hot_module::ModuleHotReferenceCodeGen,
ident::IdentReplacement, ident::IdentReplacement,
member::MemberReplacement, member::MemberReplacement,
require_context::RequireContextAssetReferenceCodeGen, require_context::RequireContextAssetReferenceCodeGen,
...@@ -199,6 +200,7 @@ pub enum CodeGen { ...@@ -199,6 +200,7 @@ pub enum CodeGen {
RequireContextAssetReferenceCodeGen(RequireContextAssetReferenceCodeGen), RequireContextAssetReferenceCodeGen(RequireContextAssetReferenceCodeGen),
UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen), UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen),
WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen), WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen),
ModuleHotReferenceCodeGen(ModuleHotReferenceCodeGen),
} }
impl CodeGen { impl CodeGen {
...@@ -231,6 +233,9 @@ impl CodeGen { ...@@ -231,6 +233,9 @@ impl CodeGen {
Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::UrlAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::UrlAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::ModuleHotReferenceCodeGen(v) => {
v.code_generation(ctx, scope_hoisting_context).await
}
} }
} }
} }
......
...@@ -17,5 +17,7 @@ pub mod failed_to_analyze { ...@@ -17,5 +17,7 @@ pub mod failed_to_analyze {
pub const NEW_URL_IMPORT_META: &str = "TP1201"; pub const NEW_URL_IMPORT_META: &str = "TP1201";
pub const FREE_VAR_REFERENCE: &str = "TP1202"; pub const FREE_VAR_REFERENCE: &str = "TP1202";
pub const NEW_WORKER: &str = "TP1203"; pub const NEW_WORKER: &str = "TP1203";
pub const MODULE_HOT_ACCEPT: &str = "TP1204";
pub const MODULE_HOT_DECLINE: &str = "TP1205";
} }
} }
...@@ -16,7 +16,7 @@ use crate::{ ...@@ -16,7 +16,7 @@ use crate::{
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, magic_identifier, create_visitor, magic_identifier,
references::AstPath, references::AstPath,
runtime_functions::TURBOPACK_RESOLVE_ABSOLUTE_PATH, runtime_functions::{TURBOPACK_MODULE, TURBOPACK_RESOLVE_ABSOLUTE_PATH},
}; };
/// Responsible for initializing the `import.meta` object binding, so that it /// Responsible for initializing the `import.meta` object binding, so that it
...@@ -63,16 +63,28 @@ impl ImportMetaBinding { ...@@ -63,16 +63,28 @@ impl ImportMetaBinding {
}, },
); );
Ok(CodeGeneration::hoisted_stmt( let hmr_enabled = *chunking_context.is_hot_module_replacement_enabled().await?;
rcstr!("import.meta"),
// [NOTE] url property is lazy-evaluated, as it should be computed once // [NOTE] url property is lazy-evaluated, as it should be computed once
// turbopack_runtime injects a function to calculate an absolute path. // turbopack_runtime injects a function to calculate an absolute path.
let stmt = if hmr_enabled {
// turbopackHot exposes the HMR API (equivalent to module.hot in CJS).
let turbopack_module: Expr = TURBOPACK_MODULE.into();
quote!(
"const $name = { get url() { return $path }, get turbopackHot() { return $m.hot } };" as Stmt,
name = meta_ident(),
path: Expr = path,
m: Expr = turbopack_module,
)
} else {
quote!( quote!(
"const $name = { get url() { return $path } };" as Stmt, "const $name = { get url() { return $path } };" as Stmt,
name = meta_ident(), name = meta_ident(),
path: Expr = path.clone(), path: Expr = path,
), )
)) };
Ok(CodeGeneration::hoisted_stmt(rcstr!("import.meta"), stmt))
} }
} }
......
...@@ -7,6 +7,7 @@ pub mod dynamic_expression; ...@@ -7,6 +7,7 @@ pub mod dynamic_expression;
pub mod esm; pub mod esm;
pub mod exports_info; pub mod exports_info;
pub mod external_module; pub mod external_module;
pub mod hot_module;
pub mod ident; pub mod ident;
pub mod member; pub mod member;
pub mod node; pub mod node;
...@@ -107,7 +108,7 @@ use crate::{ ...@@ -107,7 +108,7 @@ use crate::{
graph::{ graph::{
ConditionalKind, DeclUsage, Effect, EffectArg, EvalContext, VarGraph, create_graph, ConditionalKind, DeclUsage, Effect, EffectArg, EvalContext, VarGraph, create_graph,
}, },
imports::{ImportAnnotations, ImportAttributes, ImportedSymbol, Reexport}, imports::{ImportAnnotations, ImportAttributes, ImportMap, ImportedSymbol, Reexport},
linker::link, linker::link,
parse_require_context, side_effects, parse_require_context, side_effects,
top_level_await::has_top_level_await, top_level_await::has_top_level_await,
...@@ -136,6 +137,7 @@ use crate::{ ...@@ -136,6 +137,7 @@ use crate::{
base::EsmAssetReferences, export::EsmExport, module_id::EsmModuleIdAssetReference, base::EsmAssetReferences, export::EsmExport, module_id::EsmModuleIdAssetReference,
}, },
exports_info::{ExportsInfoBinding, ExportsInfoRef}, exports_info::{ExportsInfoBinding, ExportsInfoRef},
hot_module::{ModuleHotReferenceAssetReference, ModuleHotReferenceCodeGen},
ident::IdentReplacement, ident::IdentReplacement,
member::MemberReplacement, member::MemberReplacement,
node::PackageJsonReference, node::PackageJsonReference,
...@@ -482,6 +484,12 @@ struct AnalysisState<'a> { ...@@ -482,6 +484,12 @@ struct AnalysisState<'a> {
// Whether we are only tracing dependencies (no code generation). When true, synthetic // Whether we are only tracing dependencies (no code generation). When true, synthetic
// wrapper modules like WorkerLoaderModule should not be created. // wrapper modules like WorkerLoaderModule should not be created.
tracing_only: bool, tracing_only: bool,
// Whether the module is an ESM module (affects resolution for hot module dependencies).
is_esm: bool,
// ESM import references (indexed to match eval_context.imports.references()).
import_references: &'a [ResolvedVc<EsmAssetReference>],
// The import map from the eval context, used to match dep strings to import references.
imports: &'a ImportMap,
} }
impl AnalysisState<'_> { impl AnalysisState<'_> {
...@@ -1091,6 +1099,9 @@ async fn analyze_ecmascript_module_internal( ...@@ -1091,6 +1099,9 @@ async fn analyze_ecmascript_module_internal(
url_rewrite_behavior: options.url_rewrite_behavior, url_rewrite_behavior: options.url_rewrite_behavior,
collect_affecting_sources: options.analyze_mode.is_tracing_assets(), collect_affecting_sources: options.analyze_mode.is_tracing_assets(),
tracing_only: !options.analyze_mode.is_code_gen(), tracing_only: !options.analyze_mode.is_code_gen(),
is_esm,
import_references: &import_references,
imports: &eval_context.imports,
}; };
enum Action { enum Action {
...@@ -1717,6 +1728,7 @@ async fn compile_time_info_for_module_options( ...@@ -1717,6 +1728,7 @@ async fn compile_time_info_for_module_options(
environment: compile_time_info.environment, environment: compile_time_info.environment,
defines: CompileTimeDefines(defines).resolved_cell(), defines: CompileTimeDefines(defines).resolved_cell(),
free_var_references: FreeVarReferences(free_var_references).resolved_cell(), free_var_references: FreeVarReferences(free_var_references).resolved_cell(),
hot_module_replacement_enabled: compile_time_info.hot_module_replacement_enabled,
} }
.cell()) .cell())
} }
...@@ -2912,10 +2924,89 @@ where ...@@ -2912,10 +2924,89 @@ where
), ),
) )
} }
kind @ (WellKnownFunctionKind::ModuleHotAccept
| WellKnownFunctionKind::ModuleHotDecline) => {
let is_accept = matches!(kind, WellKnownFunctionKind::ModuleHotAccept);
let args = linked_args().await?;
if let Some(first_arg) = args.first() {
if let Some(dep_strings) = extract_hot_dep_strings(first_arg) {
let mut references = Vec::new();
let mut esm_references = Vec::new();
for dep_str in &dep_strings {
let request = Request::parse_string(dep_str.clone()).to_resolved().await?;
let reference = ModuleHotReferenceAssetReference::new(
*origin,
*request,
issue_source(source, span),
error_mode,
state.is_esm,
)
.to_resolved()
.await?;
analysis.add_reference(reference);
references.push(reference);
// For accept, find a matching ESM import so we can
// re-assign the namespace binding after the update.
let esm_ref = if is_accept {
state
.imports
.references()
.enumerate()
.find(|(_, r)| r.module_path.to_string_lossy() == dep_str.as_str())
.and_then(|(idx, _)| state.import_references.get(idx).copied())
} else {
None
};
esm_references.push(esm_ref);
}
analysis.add_code_gen(ModuleHotReferenceCodeGen::new(
references,
esm_references,
ast_path.to_vec().into(),
));
} else if first_arg.is_unknown() {
let (args_str, hints) = explain_args(args);
let method = if is_accept { "accept" } else { "decline" };
let error_code = if is_accept {
errors::failed_to_analyze::ecmascript::MODULE_HOT_ACCEPT
} else {
errors::failed_to_analyze::ecmascript::MODULE_HOT_DECLINE
};
handler.span_warn_with_code(
span,
&format!(
"module.hot.{method}({args_str}) is not statically analyzable{hints}",
),
DiagnosticId::Error(error_code.to_string()),
)
}
}
}
_ => {} _ => {}
}; };
Ok(()) Ok(())
} }
/// Extracts dependency strings from the first argument of module.hot.accept/decline.
/// Returns None if the argument is not a string or array of strings (e.g., it's a function
/// for self-accept).
fn extract_hot_dep_strings(arg: &JsValue) -> Option<Vec<RcStr>> {
// Single string: module.hot.accept('./dep', cb)
if let Some(s) = arg.as_str() {
return Some(vec![s.into()]);
}
// Array of strings: module.hot.accept(['./dep-a', './dep-b'], cb)
if let JsValue::Array { items, .. } = arg {
let mut deps = Vec::new();
for item in items {
deps.push(item.as_str()?.into());
}
return Some(deps);
}
None
}
async fn handle_member( async fn handle_member(
ast_path: &[AstParentKind], ast_path: &[AstParentKind],
link_obj: impl Future<Output = Result<JsValue>> + Send + Sync, link_obj: impl Future<Output = Result<JsValue>> + Send + Sync,
......
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