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

fix(server-hmr): metadata routes overwrite page runtime HMR handler (#92273)

### What?

Fix server HMR becoming unresponsive after a metadata route is loaded in
the same Node.js process as an app page.

### Why?

Turbopack loads separate runtime chunks for app pages and metadata
routes (`robots.ts`, `sitemap.ts`, `manifest.ts`, `icon.tsx`, etc.) in
the same Node.js process. Each runtime chunk embeds `dev-nodejs.ts` and
produces a distinct `__turbopack_server_hmr_apply__` closure bound to
its own `moduleFactories` and `devModuleCache`.

Previously each runtime simply overwrote
`globalThis.__turbopack_server_hmr_apply__`, so the last chunk to load
silently won. Navigating to `/robots.txt` before an HMR update caused
the metadata route runtime to overwrite the page runtime's handler.
Subsequent HMR updates were dispatched only to the metadata route
runtime, which has no knowledge of the page module — the page appeared
frozen and stopped reflecting file changes.

### How?

Replace the bare assignment with a multicast registry:

1. Each runtime appends its own `__turbopack_server_hmr_apply__` handler
to `globalThis.__turbopack_server_hmr_handlers__[]`.
2. The first runtime to register installs a shared dispatcher as
`globalThis.__turbopack_server_hmr_apply__` that iterates all registered
handlers at call time (not install time), so newly loaded runtimes are
always included.
3. On full cache reset, `hot-reloader-turbopack.ts` resets
`__turbopack_server_hmr_handlers__` to `[]` so stale handlers from
evicted chunks don't accumulate into the next generation.

Because `dev-nodejs.ts` is embedded into the Turbopack binary via
`include_dir!`, this fix requires rebuilding the native binary.

### Tests

`test/development/app-dir/server-hmr/server-hmr.test.ts` — extended with
`metadata route hmr` tests that load a metadata route before patching a
page file, verifying HMR updates still reach the page runtime after a
second runtime chunk is loaded.

---------
Co-authored-by: 's avatarWill Binns-Smith <wbinnssmith@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 0dc354b8
......@@ -1856,6 +1856,11 @@ export async function createHotReloaderTurbopack(
__next__clear_chunk_cache__()
}
// Reset the server HMR handler registry. All server runtime chunks are
// cleared from require.cache above; when they're next required they'll
// re-register into this Map and reinstall the routing dispatcher.
;(globalThis as any).__turbopack_server_hmr_handlers__ = new Map()
// Clear all edge contexts
await clearAllModuleContexts()
......
......@@ -157,6 +157,43 @@ describe('server-hmr', () => {
})
describe('metadata route hmr', () => {
itTurbopackDev(
'does not prevent page hmr when metadata route has been loaded',
async () => {
// Load the manifest route first. This causes the manifest runtime to
// register its __turbopack_server_hmr_apply__ on globalThis, which
// would overwrite the page's handler if the multi-cast registry is
// broken.
await next.fetch('/manifest.webmanifest')
const browser = await next.browser('/module-preservation')
// Patch the page to a known unique string regardless of prior test state
await next.patchFile('app/module-preservation/page.tsx', (content) =>
content.replace(/<p id="greeting">.*?<\/p>/, () => {
return '<p id="greeting">metadata-hmr-test-initial</p>'
})
)
await retry(async () => {
const text = await browser.elementByCss('#greeting').text()
expect(text).toBe('metadata-hmr-test-initial')
})
await next.patchFile('app/module-preservation/page.tsx', (content) =>
content.replace(
'metadata-hmr-test-initial',
'metadata-hmr-test-updated'
)
)
await retry(async () => {
const text = await browser.elementByCss('#greeting').text()
expect(text).toBe('metadata-hmr-test-updated')
})
}
)
it('reflects manifest.ts changes on fetch/refresh', async () => {
const initial = await next
.fetch('/manifest.webmanifest')
......
......@@ -33,4 +33,65 @@ function __turbopack_server_hmr_apply__(update: NodeJsHmrPayload): boolean {
}
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__
// Turbopack produces one server runtime per chunking context (e.g.
// server/chunks/ssr/ for pages, server/chunks/ for route handlers), each with
// its own moduleFactories. We keep a globalThis Map from __filename to handler
// so updates are routed only to runtimes whose chunkPrefix matches the update's
// chunk paths, skipping unnecessary eval() calls. Map.set() naturally replaces
// stale entries when a runtime file is re-evaluated after require.cache eviction.
type HmrHandlerEntry = {
handler: (update: NodeJsHmrPayload) => boolean
/** Output directory relative to RUNTIME_ROOT, e.g. "server/chunks/ssr". */
chunkPrefix: string
}
const handlers: Map<string, HmrHandlerEntry> =
globalThis.__turbopack_server_hmr_handlers__ ?? new Map()
const chunkPrefix = path.relative(RUNTIME_ROOT, path.dirname(__filename))
if (handlers.size === 0) {
// First registration in this generation: install the routing dispatcher.
globalThis.__turbopack_server_hmr_apply__ = (
update: NodeJsHmrPayload
): boolean => {
const registry: Map<string, HmrHandlerEntry> =
globalThis.__turbopack_server_hmr_handlers__ ?? new Map()
const updateChunkPaths = Object.keys(update.instruction?.chunks ?? {})
const toCall: HmrHandlerEntry[] = []
if (updateChunkPaths.length === 0) {
for (const entry of registry.values()) toCall.push(entry)
} else {
const seen = new Set<string>()
for (const chunkPath of updateChunkPaths) {
const dir = path.dirname(chunkPath)
for (const [key, entry] of registry) {
if (dir === entry.chunkPrefix && !seen.has(key)) {
seen.add(key)
toCall.push(entry)
}
}
}
}
let applied = false
for (const { handler } of toCall) {
try {
if (handler(update)) applied = true
} catch (err) {
console.error('[Server HMR] Handler error:', err)
}
}
return applied
}
}
globalThis.__turbopack_server_hmr_handlers__ = handlers
handlers.set(__filename, {
handler: __turbopack_server_hmr_apply__,
chunkPrefix,
})
......@@ -9,6 +9,18 @@ declare global {
var __turbopack_module_factories__: ModuleFactories
var __turbopack_module_cache__: Record<ModuleId, any>
var __turbopack_runtime_modules__: Set<ModuleId>
/**
* Shared registry of per-runtime server HMR handler entries, keyed by the
* runtime file's __filename. Map.set() naturally replaces stale entries when
* a runtime file is re-evaluated. Reset to undefined by the hot-reloader on
* full cache reset.
*/
// NodeJsHmrPayload is only in scope inside the concatenated runtime chunk, not
// in this .d.ts file, so the handler parameter must use any here.
var __turbopack_server_hmr_handlers__:
| Map<string, { handler: (update: any) => boolean; chunkPrefix: string }>
| undefined
}
export {}
......@@ -1696,7 +1696,44 @@ function __turbopack_server_hmr_apply__(update) {
return false;
}
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__;
const handlers = globalThis.__turbopack_server_hmr_handlers__ ?? new Map();
const chunkPrefix = path.relative(RUNTIME_ROOT, path.dirname(__filename));
if (handlers.size === 0) {
// First registration in this generation: install the routing dispatcher.
globalThis.__turbopack_server_hmr_apply__ = (update)=>{
const registry = globalThis.__turbopack_server_hmr_handlers__ ?? new Map();
const updateChunkPaths = Object.keys(update.instruction?.chunks ?? {});
const toCall = [];
if (updateChunkPaths.length === 0) {
for (const entry of registry.values())toCall.push(entry);
} else {
const seen = new Set();
for (const chunkPath of updateChunkPaths){
const dir = path.dirname(chunkPath);
for (const [key, entry] of registry){
if (dir === entry.chunkPrefix && !seen.has(key)) {
seen.add(key);
toCall.push(entry);
}
}
}
}
let applied = false;
for (const { handler } of toCall){
try {
if (handler(update)) applied = true;
} catch (err) {
console.error('[Server HMR] Handler error:', err);
}
}
return applied;
};
}
globalThis.__turbopack_server_hmr_handlers__ = handlers;
handlers.set(__filename, {
handler: __turbopack_server_hmr_apply__,
chunkPrefix
});
//# sourceMappingURL=%5Bturbopack%5D_runtime.js.map
\ No newline at end of file
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