Unverified Commit f3f56ece authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Trace middleware/proxy source files in webpack NFT pipeline (#93871)

Webpack's source-level NFT pass in `next-trace-entrypoints-plugin.ts`
previously ran only for `pages/` and `app/` entries, so middleware fell
back to the post-bundle chunk trace in `collect-build-traces.ts`. That
trace cannot see through webpack's numeric module-ID indirection (`f =
c(3024)` where module 3024 re-exports `require("node:fs")`), so runtime
file references inside Node middleware — e.g.
`fs.readFile(path.join(process.cwd(), 'package.json'))` — never made it
into `middleware.js.nft.json`. Vercel deploys then 500'd with `ENOENT
'/var/task/package.json'` because the file was not shipped into the
function bundle. Turbopack avoids this through its own pre-bundle asset
graph trace, which is why only the webpack deploy path was affected; the
test that surfaced it (the `/test-node-fs` case in
`test/e2e/middleware-general`) had been skipped on deploy until #93614
re-enabled it.

The fix extends the Pass 1 entry filter to also process middleware
entries, keyed off `isMiddlewareFilename` and using
`buildInfo.route.absolutePagePath` as the entry source — middleware
lives at the project root rather than under `pagesDir`/`appDir`, so
`getPageFilePath` does not apply. The existing `createTraceAssets`
emission and the `collect-build-traces.ts` merge already handle
arbitrary entry names, so no further changes are needed downstream.

`test/e2e/middleware-general/app/middleware-node.js` is also cleaned up
to use static `import * as fs from 'node:fs'` / `node:path`, drop the
redundant `process.env.NEXT_RUNTIME === 'nodejs'` guard, and wrap the
callback `fs.readFile` in a Promise. `@vercel/nft`'s symbol table only
recognizes the callback and sync `fs` APIs, not `fs.promises.*`, so the
call site has to remain a direct `fs.readFile(...)` for the path
argument to be backtracked into the trace; a TODO references the
upstream gap.
parent 518e6f8d
......@@ -19,6 +19,7 @@ import { getModuleBuildInfo } from '../loaders/get-module-build-info'
import { getPageFilePath } from '../../entries'
import { resolveExternal } from '../../handle-externals'
import { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'
import { isMiddlewareFilename } from '../../utils'
import { getCompilationSpan } from '../utils'
const PLUGIN_NAME = 'TraceEntryPointsPlugin'
......@@ -335,8 +336,14 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
const isPage = normalizedName.startsWith('pages/')
const isApp =
this.appDirEnabled && normalizedName.startsWith('app/')
if (isApp || isPage) {
// Middleware/proxy lives at the project root rather than
// under pages/ or app/, so it gets its own gate. Without
// this, source-level NFT analysis is skipped for the
// middleware/proxy entry and runtime fs/path/process.cwd()
// patterns never make it into `middleware.js.nft.json`.
const isMiddleware = isMiddlewareFilename(normalizedName)
if (isApp || isPage || isMiddleware) {
for (const dep of entry.dependencies) {
if (!dep) continue
const entryMod = getModuleFromDependency(compilation, dep)
......@@ -347,16 +354,24 @@ export class TraceEntryPointsPlugin implements webpack.WebpackPluginInstance {
const moduleBuildInfo = getModuleBuildInfo(entryMod)
// All loaders that are used to create entries have a `route` property on the buildInfo.
if (moduleBuildInfo.route) {
const absolutePath = getPageFilePath({
absolutePagePath:
moduleBuildInfo.route.absolutePagePath,
rootDir: this.rootDir,
appDir: this.appDir,
pagesDir: this.pagesDir,
})
// Ensures we don't handle non-pages.
// Middleware/proxy sources live at the project root,
// not under pagesDir/appDir, so `getPageFilePath`
// does not apply — use the absolutePagePath directly.
const absolutePath = isMiddleware
? moduleBuildInfo.route.absolutePagePath
: getPageFilePath({
absolutePagePath:
moduleBuildInfo.route.absolutePagePath,
rootDir: this.rootDir,
appDir: this.appDir,
pagesDir: this.pagesDir,
})
// Skip entries whose source is neither a pages/app
// file (under pagesDir/appDir) nor a middleware/proxy
// file at the project root.
if (
isMiddleware ||
(this.pagesDir &&
absolutePath.startsWith(this.pagesDir)) ||
(this.appDir &&
......
/* global globalThis */
import { NextRequest, NextResponse } from 'next/server'
import * as fs from 'node:fs'
import * as path from 'node:path'
import { getSomeData } from './lib/some-data'
import magicValue from 'shared-package'
......@@ -34,14 +36,28 @@ export async function middleware(request) {
const url = request.nextUrl
if (process.env.NEXT_RUNTIME === 'nodejs') {
if (url.pathname.startsWith('/test-node-fs')) {
const fs = await import('fs')
const path = await import('path')
const pkgPath = path.join(process.cwd(), 'package.json')
const pkgData = JSON.parse(await fs.promises.readFile(pkgPath, 'utf8'))
return NextResponse.json(pkgData)
}
if (url.pathname.startsWith('/test-node-fs')) {
const pkgPath = path.join(process.cwd(), 'package.json')
// @vercel/nft's static analysis only recognizes the callback `fs.readFile`
// (and `readFileSync` etc.), not `fs.promises.readFile`. Using the
// callback form lets NFT resolve the path argument and include
// `package.json` in the middleware NFT trace, which Vercel relies on to
// ship files into the deployed function bundle. Turbopack's analysis
// handles `fs.promises.*` natively, so this only matters for webpack.
// TODO: Drop this workaround once @vercel/nft adds static-analysis support
// for `fs.promises.*`.
const pkgData = JSON.parse(
await new Promise((resolve, reject) => {
fs.readFile(pkgPath, 'utf8', (err, data) => {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
)
return NextResponse.json(pkgData)
}
if (request.headers.get('x-prerender-revalidate')) {
......
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