Repository: vercel/next.js
Pull request: Turbopack build: fix deterministic build test

## What?

Fixes the test checking deterministic builds. The reason it was failing is that we incorrectly wrote the build manifest directly as middleware build manifest but it needs some adjustments. There's a function for that already, so just using that function matches the behavior we use with webpack. Easy fix.

Improved the test to show the file contents whenever the test fails.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes PACK-4221

Changed files:
filename: packages/next/src/build/webpack/plugins/build-manifest-plugin.ts
patch: @@ -36,10 +36,12 @@ function buildNodejsLowPriorityPath(filename: string, buildId: string) {
   return `${CLIENT_STATIC_FILES_PATH}/${buildId}/${filename}`
 }
 
-function createEdgeRuntimeManifest(originAssetMap: BuildManifest): string {
+export function createEdgeRuntimeManifest(
+  originAssetMap: Partial<BuildManifest>
+): string {
   const manifestFilenames = ['_buildManifest.js', '_ssgManifest.js']
 
-  const assetMap: BuildManifest = {
+  const assetMap: Partial<BuildManifest> = {
     ...originAssetMap,
     lowPriorityFiles: [],
   }

filename: packages/next/src/shared/lib/turbopack/manifest-loader.ts
patch: @@ -40,6 +40,7 @@ import {
   normalizeRewritesForBuildManifest,
   srcEmptySsgManifest,
   processRoute,
+  createEdgeRuntimeManifest,
 } from '../../../build/webpack/plugins/build-manifest-plugin'
 import getAssetPathFromRoute from '../router/utils/get-asset-path-from-route'
 import { getEntryKey, type EntryKey } from './entry-key'
@@ -454,7 +455,7 @@ export class TurbopackManifestLoader {
       middlewareBuildManifestPath,
       // we use globalThis here because middleware can be node
       // which doesn't have "self"
-      `globalThis.__BUILD_MANIFEST=${JSON.stringify(buildManifest)};`
+      createEdgeRuntimeManifest(buildManifest)
     )
 
     const interceptionRewrites = JSON.stringify(

filename: test/production/deterministic-build/index.test.ts
patch: @@ -1,10 +1,29 @@
 import crypto from 'crypto'
 import { NextInstance, nextTestSetup } from 'e2e-utils'
 
-function generateMD5(text: string) {
+type Md5Hash = string & { __brand: 'Md5Hash' }
+
+type Record = [filePath: string, hash: string, content: string]
+
+interface RouteFileHashRecords {
+  [key: string]: Record[]
+}
+
+function generateMD5(text: string): Md5Hash {
   const hash = crypto.createHash('md5')
   hash.update(text)
-  return hash.digest('hex')
+  return hash.digest('hex') as Md5Hash
+}
+
+function getNodeFileHashes(next: NextInstance): RouteFileHashRecords {
+  const nodeBuildFileMd5Hashes: RouteFileHashRecords = {}
+  for (const file of nodeFilePaths) {
+    const content = next.readFileSync(`.next/server/${file}.js`)
+    const md5 = generateMD5(content)
+    nodeBuildFileMd5Hashes[file] = [[file, md5, content]]
+  }
+
+  return nodeBuildFileMd5Hashes
 }
 
 const nodeFilePaths = [
@@ -14,22 +33,28 @@ const nodeFilePaths = [
   'pages/pages-page',
 ]
 
-async function getEdgeRouteFilesFromManifest(next: NextInstance) {
+function getEdgeRouteFileHashes(next: NextInstance): RouteFileHashRecords {
   const manifest: any = JSON.parse(
-    await next.readFile('.next/server/middleware-manifest.json')
+    next.readFileSync('.next/server/middleware-manifest.json')
   )
   const routeKeys = Object.keys(manifest.functions)
-  const md5Map: Record<string, string[]> = {}
+  const hashMap: RouteFileHashRecords = {}
   for (const route of routeKeys) {
     const files: string[] = manifest.functions[route].files
-    const filesMd5Promises = files.map(async (filePath: string) => {
-      const content = await next.readFile(`.next/${filePath}`)
-      return generateMD5(content)
-    })
-    const md5s = await Promise.all(filesMd5Promises)
-    md5Map[route] = md5s
+
+    const hashes: Record[] = []
+    for (const filePath of files) {
+      const content = next.readFileSync(`.next/${filePath}`)
+      hashes.push([filePath, generateMD5(content), content])
+    }
+    hashMap[route] = hashes
   }
-  return md5Map
+  return hashMap
+}
+
+interface Runs {
+  run1: RouteFileHashRecords
+  run2: RouteFileHashRecords
 }
 
 describe('deterministic build', () => {
@@ -38,31 +63,30 @@ describe('deterministic build', () => {
     skipStart: true,
   })
 
-  // Edge - { [route]: [file md5s] }
-  const edgeBuildFileMd5Hashes: Record<string, string[]>[] = []
-  // Node - { [route]: page.js or route.js md5 }
-  const nodeBuildFileMd5Hashes: Record<string, string>[] = [{}, {}]
+  const edgeBuildFileMd5Hashes: Runs = {
+    run1: {},
+    run2: {},
+  }
+
+  const nodeBuildFileMd5Hashes: Runs = {
+    run1: {},
+    run2: {},
+  }
 
   beforeAll(async () => {
     // First build
     await next.build()
-    edgeBuildFileMd5Hashes.push(await getEdgeRouteFilesFromManifest(next))
-    for (const file of nodeFilePaths) {
-      const content = await next.readFile(`.next/server/${file}.js`)
-      nodeBuildFileMd5Hashes[0][file] = generateMD5(content)
-    }
+    edgeBuildFileMd5Hashes.run1 = getEdgeRouteFileHashes(next)
+    nodeBuildFileMd5Hashes.run1 = getNodeFileHashes(next)
 
     // Second build
     await next.build()
-    edgeBuildFileMd5Hashes.push(await getEdgeRouteFilesFromManifest(next))
-    for (const file of nodeFilePaths) {
-      const content = await next.readFile(`.next/server/${file}.js`)
-      nodeBuildFileMd5Hashes[1][file] = generateMD5(content)
-    }
+    edgeBuildFileMd5Hashes.run2 = getEdgeRouteFileHashes(next)
+    nodeBuildFileMd5Hashes.run2 = getNodeFileHashes(next)
   })
 
   it('should have same md5 file across build', async () => {
-    expect(edgeBuildFileMd5Hashes[0]).toEqual(edgeBuildFileMd5Hashes[1])
-    expect(nodeBuildFileMd5Hashes[0]).toEqual(nodeBuildFileMd5Hashes[1])
+    expect(edgeBuildFileMd5Hashes.run1).toEqual(edgeBuildFileMd5Hashes.run2)
+    expect(nodeBuildFileMd5Hashes.run1).toEqual(nodeBuildFileMd5Hashes.run2)
   })
 })

filename: test/turbopack-build-tests-manifest.json
patch: @@ -18007,8 +18007,8 @@
     "runtimeError": false
   },
   "test/production/deterministic-build/index.test.ts": {
-    "passed": [],
-    "failed": ["deterministic build should have same md5 file across build"],
+    "passed": ["deterministic build should have same md5 file across build"],
+    "failed": [],
     "pending": [],
     "flakey": [],
     "runtimeError": false