Commit d3d38769 authored by JJ Kasper's avatar JJ Kasper

partial revert

parent 2e3fb9bd
...@@ -45,7 +45,11 @@ import { getRedirectStatus, modifyRouteRegex } from '../../lib/redirect-status' ...@@ -45,7 +45,11 @@ import { getRedirectStatus, modifyRouteRegex } from '../../lib/redirect-status'
import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { escapeStringRegexp } from '../../shared/lib/escape-regexp' import { escapeStringRegexp } from '../../shared/lib/escape-regexp'
import { sortSortableRoutes } from '../../shared/lib/router/utils/sortable-routes' import { sortSortableRoutes } from '../../shared/lib/router/utils/sortable-routes'
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'
import { defaultOverrides } from '../../server/require-hook'
import { makeIgnoreFn } from '../collect-build-traces'
import { generateRoutesManifest } from '../generate-routes-manifest' import { generateRoutesManifest } from '../generate-routes-manifest'
import { Bundler } from '../../lib/bundler'
interface SharedRouteFields { interface SharedRouteFields {
/** /**
...@@ -403,6 +407,7 @@ export async function handleBuildComplete({ ...@@ -403,6 +407,7 @@ export async function handleBuildComplete({
configOutDir, configOutDir,
distDir, distDir,
pageKeys, pageKeys,
bundler,
tracingRoot, tracingRoot,
adapterPath, adapterPath,
appPageKeys, appPageKeys,
...@@ -429,6 +434,7 @@ export async function handleBuildComplete({ ...@@ -429,6 +434,7 @@ export async function handleBuildComplete({
nextVersion: string nextVersion: string
hasStatic404: boolean hasStatic404: boolean
hasStatic500: boolean hasStatic500: boolean
bundler: Bundler
staticPages: Set<string> staticPages: Set<string>
hasNodeMiddleware: boolean hasNodeMiddleware: boolean
config: NextConfigComplete config: NextConfigComplete
...@@ -489,6 +495,26 @@ export async function handleBuildComplete({ ...@@ -489,6 +495,26 @@ export async function handleBuildComplete({
} }
const sharedNodeAssets: Record<string, string> = {} const sharedNodeAssets: Record<string, string> = {}
const pagesSharedNodeAssets: Record<string, string> = {}
const appPagesSharedNodeAssets: Record<string, string> = {}
const sharedTraceIgnores = [
'**/next/dist/compiled/next-server/**/*.dev.js',
'**/next/dist/compiled/webpack/*',
'**/node_modules/webpack5/**/*',
'**/next/dist/server/lib/route-resolver*',
'next/dist/compiled/semver/semver/**/*.js',
'**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js',
'**/*.d.ts',
'**/*.map',
'**/next/dist/pages/**/*',
'**/node_modules/sharp/**/*',
'**/@img/sharp-libvips*/**/*',
'**/next/dist/compiled/edge-runtime/**/*',
'**/next/dist/server/web/sandbox/**/*',
'**/next/dist/server/post-process.js',
]
const sharedIgnoreFn = makeIgnoreFn(tracingRoot, sharedTraceIgnores)
for (const file of requiredServerFiles) { for (const file of requiredServerFiles) {
// add to shared node assets // add to shared node assets
...@@ -496,18 +522,82 @@ export async function handleBuildComplete({ ...@@ -496,18 +522,82 @@ export async function handleBuildComplete({
const fileOutputPath = path.relative(tracingRoot, filePath) const fileOutputPath = path.relative(tracingRoot, filePath)
sharedNodeAssets[fileOutputPath] = filePath sharedNodeAssets[fileOutputPath] = filePath
} }
// add "next/setup-node-env" stub so it can be required via
// TODO: should we make this always available without adapters if (bundler !== Bundler.Turbopack) {
const setupNodeStubPath = path.join( const moduleTypes = ['app-page', 'pages'] as const
path.dirname(require.resolve('next/package.json')),
'setup-node-env.js' for (const type of moduleTypes) {
) const currentDependencies: string[] = []
sharedNodeAssets[path.relative(tracingRoot, setupNodeStubPath)] = const modulePath = require.resolve(
require.resolve('next/dist/build/adapter/setup-node-env.external') `next/dist/server/route-modules/${type}/module.compiled`
)
const contextDir = path.join(
path.dirname(modulePath),
'vendored',
'contexts'
)
for (const item of await fs.readdir(contextDir)) {
if (item.match(/\.(mjs|cjs|js)$/)) {
currentDependencies.push(path.join(contextDir, item))
}
}
const { fileList, esmFileList } = await nodeFileTrace(
currentDependencies,
{
base: tracingRoot,
ignore: sharedIgnoreFn,
}
)
esmFileList.forEach((item) => fileList.add(item))
for (const rootRelativeFilePath of fileList) {
if (type === 'pages') {
pagesSharedNodeAssets[rootRelativeFilePath] = path.join(
tracingRoot,
rootRelativeFilePath
)
} else {
appPagesSharedNodeAssets[rootRelativeFilePath] = path.join(
tracingRoot,
rootRelativeFilePath
)
}
}
}
// These are modules that are necessary for bootstrapping node env
const necessaryNodeDependencies = [
require.resolve('next/dist/server/node-environment'),
require.resolve('next/dist/server/require-hook'),
require.resolve('next/dist/server/node-polyfill-crypto'),
...Object.values(defaultOverrides).filter((item) =>
path.extname(item)
),
]
const { fileList, esmFileList } = await nodeFileTrace(
necessaryNodeDependencies,
{
base: tracingRoot,
ignore: sharedIgnoreFn,
}
)
esmFileList.forEach((item) => fileList.add(item))
for (const rootRelativeFilePath of fileList) {
sharedNodeAssets[rootRelativeFilePath] = path.join(
tracingRoot,
rootRelativeFilePath
)
}
}
if (hasInstrumentationHook) { if (hasInstrumentationHook) {
const assets = await handleTraceFiles( const assets = await handleTraceFiles(
path.join(distDir, 'server', 'instrumentation.js.nft.json') path.join(distDir, 'server', 'instrumentation.js.nft.json'),
'neutral'
) )
const fileOutputPath = path.relative( const fileOutputPath = path.relative(
tracingRoot, tracingRoot,
...@@ -522,11 +612,14 @@ export async function handleBuildComplete({ ...@@ -522,11 +612,14 @@ export async function handleBuildComplete({
} }
async function handleTraceFiles( async function handleTraceFiles(
traceFilePath: string traceFilePath: string,
type: 'pages' | 'app' | 'neutral'
): Promise<Record<string, string>> { ): Promise<Record<string, string>> {
const assets: Record<string, string> = Object.assign( const assets: Record<string, string> = Object.assign(
{}, {},
sharedNodeAssets sharedNodeAssets,
type === 'pages' ? pagesSharedNodeAssets : {},
type === 'app' ? appPagesSharedNodeAssets : {}
) )
const traceData = JSON.parse( const traceData = JSON.parse(
await fs.readFile(traceFilePath, 'utf8') await fs.readFile(traceFilePath, 'utf8')
...@@ -763,12 +856,14 @@ export async function handleBuildComplete({ ...@@ -763,12 +856,14 @@ export async function handleBuildComplete({
} }
const pageTraceFile = `${pageFile}.nft.json` const pageTraceFile = `${pageFile}.nft.json`
const assets = await handleTraceFiles(pageTraceFile).catch((err) => { const assets = await handleTraceFiles(pageTraceFile, 'pages').catch(
if (err.code !== 'ENOENT' || (page !== '/404' && page !== '/500')) { (err) => {
Log.warn(`Failed to locate traced assets for ${pageFile}`, err) if (err.code !== 'ENOENT' || (page !== '/404' && page !== '/500')) {
Log.warn(`Failed to locate traced assets for ${pageFile}`, err)
}
return {} as Record<string, string>
} }
return {} as Record<string, string> )
})
const functionConfig = functionsConfigManifest.functions[route] || {} const functionConfig = functionsConfigManifest.functions[route] || {}
let sourcePage = route.replace(/^\//, '') let sourcePage = route.replace(/^\//, '')
...@@ -858,7 +953,7 @@ export async function handleBuildComplete({ ...@@ -858,7 +953,7 @@ export async function handleBuildComplete({
if (hasNodeMiddleware) { if (hasNodeMiddleware) {
const middlewareFile = path.join(distDir, 'server', 'middleware.js') const middlewareFile = path.join(distDir, 'server', 'middleware.js')
const middlewareTrace = `${middlewareFile}.nft.json` const middlewareTrace = `${middlewareFile}.nft.json`
const assets = await handleTraceFiles(middlewareTrace) const assets = await handleTraceFiles(middlewareTrace, 'neutral')
const functionConfig = const functionConfig =
functionsConfigManifest.functions['/_middleware'] || {} functionsConfigManifest.functions['/_middleware'] || {}
...@@ -905,10 +1000,12 @@ export async function handleBuildComplete({ ...@@ -905,10 +1000,12 @@ export async function handleBuildComplete({
const normalizedPage = normalizeAppPath(page) const normalizedPage = normalizeAppPath(page)
const pageFile = path.join(appDistDir, `${page}.js`) const pageFile = path.join(appDistDir, `${page}.js`)
const pageTraceFile = `${pageFile}.nft.json` const pageTraceFile = `${pageFile}.nft.json`
const assets = await handleTraceFiles(pageTraceFile).catch((err) => { const assets = await handleTraceFiles(pageTraceFile, 'app').catch(
Log.warn(`Failed to copy traced files for ${pageFile}`, err) (err) => {
return {} as Record<string, string> Log.warn(`Failed to copy traced files for ${pageFile}`, err)
}) return {} as Record<string, string>
}
)
// If this is a parallel route we just need to merge // If this is a parallel route we just need to merge
// the assets as they share the same pathname // the assets as they share the same pathname
......
...@@ -5,10 +5,8 @@ ...@@ -5,10 +5,8 @@
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
// eslint-disable-next-line @next/internal/typechecked-require // eslint-disable-next-line @next/internal/typechecked-require
require('next/dist/server/node-environment') require('next/dist/server/node-environment')
try { // eslint-disable-next-line @next/internal/typechecked-require
// eslint-disable-next-line @next/internal/typechecked-require require('next/dist/server/require-hook')
require('next/dist/server/require-hook')
} catch (_) {}
// eslint-disable-next-line @next/internal/typechecked-require // eslint-disable-next-line @next/internal/typechecked-require
require('next/dist/server/node-polyfill-crypto') require('next/dist/server/node-polyfill-crypto')
} }
...@@ -4234,6 +4234,7 @@ export default async function build( ...@@ -4234,6 +4234,7 @@ export default async function build(
config, config,
appType, appType,
buildId, buildId,
bundler,
configOutDir: path.join(dir, configOutDir), configOutDir: path.join(dir, configOutDir),
staticPages, staticPages,
serverPropsPages, serverPropsPages,
......
...@@ -17,11 +17,15 @@ let resolve: typeof require.resolve = process.env.NEXT_MINIMAL ...@@ -17,11 +17,15 @@ let resolve: typeof require.resolve = process.env.NEXT_MINIMAL
export const hookPropertyMap = new Map() export const hookPropertyMap = new Map()
export const defaultOverrides = { export const defaultOverrides: Record<string, string> = {}
'styled-jsx': path.dirname(resolve('styled-jsx/package.json')),
'styled-jsx/style': resolve('styled-jsx/style'), try {
'styled-jsx/style.js': resolve('styled-jsx/style'), Object.assign(defaultOverrides, {
} 'styled-jsx': path.dirname(resolve('styled-jsx/package.json')),
'styled-jsx/style': resolve('styled-jsx/style'),
'styled-jsx/style.js': resolve('styled-jsx/style'),
})
} catch (_) {}
const toResolveMap = (map: Record<string, string>): [string, string][] => const toResolveMap = (map: Record<string, string>): [string, string][] =>
Object.entries(map).map(([key, value]) => [key, resolve(value)]) Object.entries(map).map(([key, value]) => [key, resolve(value)])
......
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