Unverified Commit 0720326b authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Fix Turbopack client manifests across branch switches

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent fea76de6
import type { Socket } from 'net' import type { Socket } from 'net'
import { mkdir, writeFile } from 'fs/promises' import { mkdir, writeFile } from 'fs/promises'
import { realpathSync } from 'fs' import { readFileSync, realpathSync } from 'fs'
import { execFileSync } from 'node:child_process'
import * as inspector from 'inspector' import * as inspector from 'inspector'
import { join, extname, relative, isAbsolute, sep } from 'path' import {
join,
extname,
relative,
isAbsolute,
resolve as resolvePath,
sep,
} from 'path'
import { fileURLToPath, pathToFileURL } from 'url' import { fileURLToPath, pathToFileURL } from 'url'
import ws from 'next/dist/compiled/ws' import ws from 'next/dist/compiled/ws'
...@@ -328,6 +336,12 @@ function setupServerHmr( ...@@ -328,6 +336,12 @@ function setupServerHmr(
return applyPromise return applyPromise
} }
function reEvaluate(): Promise<void> {
const reEvaluation = pending.then(recover, recover)
pending = reEvaluation
return reEvaluation
}
function reset(): Promise<void> { function reset(): Promise<void> {
const resetState = () => { const resetState = () => {
versions.clear() versions.clear()
...@@ -338,7 +352,7 @@ function setupServerHmr( ...@@ -338,7 +352,7 @@ function setupServerHmr(
return resetPromise return resetPromise
} }
return { apply, reset } return { apply, reset, reEvaluate }
} }
function getSourceMapFromTurbopack( function getSourceMapFromTurbopack(
...@@ -412,6 +426,44 @@ export async function createHotReloaderTurbopack( ...@@ -412,6 +426,44 @@ export async function createHotReloaderTurbopack(
const { nextConfig, dir: projectPath } = opts const { nextConfig, dir: projectPath } = opts
const lazyDynamicImports = nextConfig.experimental.turbopackLazyDynamicImports const lazyDynamicImports = nextConfig.experimental.turbopackLazyDynamicImports
// A branch checkout can replace an entire module graph before the file watcher
// has emitted all of its changes. Server HMR diffs are not safe to apply across
// that boundary, so fall back to loading the newly written chunks from disk.
let headPath: string | undefined
let previousHead: string | undefined
if (serverFastRefresh) {
try {
headPath = resolvePath(
projectPath,
execFileSync('git', ['rev-parse', '--git-path', 'HEAD'], {
cwd: projectPath,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
timeout: 2000,
}).trim()
)
previousHead = readFileSync(headPath, 'utf8')
} catch {
headPath = undefined
}
}
let branchReEvaluation: Promise<void> | undefined
async function reEvaluateOnBranchChange() {
if (!headPath) return
let head: string
try {
head = readFileSync(headPath, 'utf8')
} catch {
return
}
if (head !== previousHead) {
previousHead = head
branchReEvaluation = serverHmr?.reEvaluate()
}
await branchReEvaluation
}
const bindings = getBindingsSync() const bindings = getBindingsSync()
// Turbopack requires native bindings and cannot run with WASM bindings. // Turbopack requires native bindings and cannot run with WASM bindings.
...@@ -1984,6 +2036,7 @@ export async function createHotReloaderTurbopack( ...@@ -1984,6 +2036,7 @@ export async function createHotReloaderTurbopack(
} }
await currentEntriesHandling await currentEntriesHandling
await reEvaluateOnBranchChange()
// TODO We shouldn't look into the filesystem again. This should use the information from entrypoints // TODO We shouldn't look into the filesystem again. This should use the information from entrypoints
let routeDef: Pick< let routeDef: Pick<
......
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
export default function LegacyClient() {
return <button id="client-result">OLD CLIENT</button>
}
import LegacyClient from './legacy-client'
export default function Page() {
return (
<main>
<h1>First route</h1>
<LegacyClient />
</main>
)
}
import LegacyClient from '../legacy-client'
export default function SecondPage() {
return (
<main>
<h1>Second route</h1>
<LegacyClient />
</main>
)
}
import { execFileSync } from 'node:child_process'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// This test switches the disposable app's Git branches, not the Next.js checkout.
// @force-gate dev && turbopack
describe('client manifest after a branch switch', () => {
const { next } = nextTestSetup({ files: __dirname, skipStart: true })
function git(...args: string[]) {
execFileSync('git', args, { cwd: next.testDir, stdio: 'pipe' })
}
async function assertSettled(branch: 'old-client' | 'replacement') {
const current = branch === 'old-client' ? 'OLD CLIENT' : 'NEW CLIENT'
const currentFile =
branch === 'old-client' ? 'legacy-client.tsx' : 'replacement-client.tsx'
const removedFile =
branch === 'old-client' ? 'replacement-client.tsx' : 'legacy-client.tsx'
await retry(async () => {
for (const route of ['/', '/second']) {
const response = await next.fetch(route)
expect(response.status).toBe(200)
expect(await response.text()).toContain(current)
}
for (const page of ['page', 'second/page']) {
const manifest = await next.readFile(
`.next/dev/server/app/${page}_client-reference-manifest.js`
)
expect(manifest).toContain(currentFile)
expect(manifest).not.toContain(removedFile)
}
}, 15_000)
}
it("does not mix a route module with the other branch's Client Manifest", async () => {
git('init', '-q', '-b', 'old-client')
git('add', 'app')
git(
'-c',
'user.name=Test',
'-c',
'user.email=test@example.invalid',
'commit',
'-qm',
'old client'
)
git('switch', '-qc', 'replacement')
await next.patchFile(
'app/replacement-client.tsx',
`'use client'
export default function ReplacementClient() {
return <button id="client-result">NEW CLIENT</button>
}`
)
await next.deleteFile('app/legacy-client.tsx')
await next.patchFile(
'app/page.tsx',
`import ReplacementClient from './replacement-client'
export default function Page() {
return <main><h1>First route</h1><ReplacementClient /></main>
}`
)
await next.patchFile(
'app/second/page.tsx',
`import ReplacementClient from '../replacement-client'
export default function SecondPage() {
return <main><h1>Second route</h1><ReplacementClient /></main>
}`
)
git('add', 'app')
git(
'-c',
'user.name=Test',
'-c',
'user.email=test@example.invalid',
'commit',
'-qm',
'replacement client'
)
git('switch', '-q', 'old-client')
await next.start()
await assertSettled('old-client')
// Check the first requests too: a stale successful page is acceptable
// while the watcher catches up, but a mixed manifest must not throw.
for (let cycle = 0; cycle < 20; cycle++) {
for (const branch of ['replacement', 'old-client'] as const) {
git('switch', '-q', branch)
for (const route of ['/second', '/']) {
const response = await next.fetch(route)
const html = await response.text()
if (response.status !== 200) {
throw new Error(
`cycle ${cycle}, ${branch} ${route}: HTTP ${response.status}; ${html.slice(0, 500)}`
)
}
expect(html).not.toContain('Could not find the module')
}
await assertSettled(branch)
}
}
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
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