Unverified Commit 071ecb0b authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update tracing to collect from reasons (#29975)

This updates the `outputFileTracing` to fix a few cases we noticed where files weren't caught and also ensures we match webpack's `esm` resolving so that we don't include `cjs` files when webpack expects `esm`, it also updates to the latest `@vercel/nft` version which removes the caching in favor of ensuring the `reasons` map contains all parents allowing us to trace all entries in one `nodeFileTrace` run and the collect the separate files for each entry from the `reasons` map giving us much better performance/reliability.  

This also ensures we don't include static image imports when enabled in the traces since they can drastically increase deployment size on larger projects. 
parent b7114bce
......@@ -214,6 +214,9 @@ export const NODE_BASE_ESM_RESOLVE_OPTIONS = {
let TSCONFIG_WARNED = false
export const nextImageLoaderRegex =
/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i
export default async function getBaseWebpackConfig(
dir: string,
{
......@@ -1057,7 +1060,7 @@ export default async function getBaseWebpackConfig(
...(!config.images.disableStaticImages
? [
{
test: /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,
test: nextImageLoaderRegex,
loader: 'next-image-loader',
issuer: { not: regexLikeCss },
dependency: { not: ['url'] },
......@@ -1199,6 +1202,8 @@ export default async function getBaseWebpackConfig(
!dev &&
new TraceEntryPointsPlugin({
appDir: dir,
esmExternals: config.experimental.esmExternals,
staticImageImports: !config.images.disableStaticImages,
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
......
import curry from 'next/dist/compiled/lodash.curry'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { nextImageLoaderRegex } from '../../../../webpack-config'
import { loader } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
import { getCustomDocumentImageError } from './messages'
......@@ -12,7 +13,7 @@ export const images = curry(async function images(
loader({
oneOf: [
{
test: /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i,
test: nextImageLoaderRegex,
use: {
loader: 'error-loader',
options: {
......
......@@ -2,10 +2,18 @@ import nodePath from 'path'
import { Span } from '../../../trace'
import { spans } from './profiling-plugin'
import isError from '../../../lib/is-error'
import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'
import {
nodeFileTrace,
NodeFileTraceReasons,
} from 'next/dist/compiled/@vercel/nft'
import { TRACE_OUTPUT_VERSION } from '../../../shared/lib/constants'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import { NODE_RESOLVE_OPTIONS } from '../../webpack-config'
import {
nextImageLoaderRegex,
NODE_ESM_RESOLVE_OPTIONS,
NODE_RESOLVE_OPTIONS,
} from '../../webpack-config'
import { NextConfigComplete } from '../../../server/config-shared'
const PLUGIN_NAME = 'TraceEntryPointsPlugin'
const TRACE_IGNORES = [
......@@ -24,19 +32,31 @@ function getModuleFromDependency(
export class TraceEntryPointsPlugin implements webpack.Plugin {
private appDir: string
private entryTraces: Map<string, string[]>
private entryTraces: Map<string, Set<string>>
private excludeFiles: string[]
private esmExternals?: NextConfigComplete['experimental']['esmExternals']
private staticImageImports?: boolean
private externalDir?: boolean
constructor({
appDir,
excludeFiles,
esmExternals,
staticImageImports,
externalDir,
}: {
appDir: string
excludeFiles?: string[]
externalDir?: boolean
staticImageImports: boolean
esmExternals?: NextConfigComplete['experimental']['esmExternals']
}) {
this.appDir = appDir
this.entryTraces = new Map()
this.externalDir = externalDir
this.esmExternals = esmExternals
this.excludeFiles = excludeFiles || []
this.staticImageImports = staticImageImports
}
// Here we output all traced assets and webpack chunks to a
......@@ -89,7 +109,8 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
doResolve?: (
request: string,
parent: string,
job: import('@vercel/nft/out/node-file-trace').Job
job: import('@vercel/nft/out/node-file-trace').Job,
isEsmRequested: boolean
) => Promise<string>
) {
compilation.hooks.finishModules.tapAsync(
......@@ -130,6 +151,7 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
curMap = new Map()
additionalEntries.set(name, curMap)
}
depModMap.set(entryMod.resource, entryMod)
curMap.set(entryMod.resource, entryMod)
}
}
......@@ -217,90 +239,127 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
}
}
const nftCache = {}
const entryPaths = Array.from(entryModMap.keys())
for (const entry of entryPaths) {
const entrySpan = finishModulesSpan.traceChild('entry', { entry })
await entrySpan.traceAsyncFn(async () => {
depModMap.clear()
const entryMod = entryModMap.get(entry)
// TODO: investigate caching, will require ensuring no traced
// files in the cache have changed, we could potentially hash
// all traced files and only leverage the cache if the hashes
// match
// const cachedTraces = entryMod.buildInfo?.cachedNextEntryTrace
// Use cached trace if available and trace version matches
// if (
// cachedTraces &&
// cachedTraces.version === TRACE_OUTPUT_VERSION
// ) {
// this.entryTraces.set(
// entryNameMap.get(entry)!,
// cachedTraces.tracedDeps
// )
// continue
// }
const collectDependencies = (mod: any) => {
if (!mod || !mod.dependencies) return
for (const dep of mod.dependencies) {
const depMod = getModuleFromDependency(compilation, dep)
if (depMod?.resource && !depModMap.get(depMod.resource)) {
depModMap.set(depMod.resource, depMod)
collectDependencies(depMod)
}
}
const collectDependencies = (mod: any) => {
if (!mod || !mod.dependencies) return
for (const dep of mod.dependencies) {
const depMod = getModuleFromDependency(compilation, dep)
if (depMod?.resource && !depModMap.get(depMod.resource)) {
depModMap.set(depMod.resource, depMod)
collectDependencies(depMod)
}
collectDependencies(entryMod)
}
}
const entriesToTrace = [...entryPaths]
const toTrace: string[] = [entry]
entryPaths.forEach((entry) => {
collectDependencies(entryModMap.get(entry))
const entryName = entryNameMap.get(entry)!
const curExtraEntries = additionalEntries.get(entryName)
const entryName = entryNameMap.get(entry)!
const curExtraEntries = additionalEntries.get(entryName)
if (curExtraEntries) {
entriesToTrace.push(...curExtraEntries.keys())
}
})
let fileList: Set<string>
let reasons: NodeFileTraceReasons
const root = nodePath.parse(process.cwd()).root
if (curExtraEntries) {
toTrace.push(...curExtraEntries.keys())
}
await finishModulesSpan
.traceChild('node-file-trace', {
traceEntryCount: entriesToTrace.length + '',
})
.traceAsyncFn(async () => {
const result = await nodeFileTrace(entriesToTrace, {
base: root,
processCwd: this.appDir,
readFile,
readlink,
stat,
resolve: doResolve
? (id, parent, job, isCjs) =>
// @ts-ignore
doResolve(id, parent, job, !isCjs)
: undefined,
ignore: [...TRACE_IGNORES, ...this.excludeFiles],
mixedModules: true,
})
// @ts-ignore
fileList = result.fileList
result.esmFileList.forEach((file) => fileList.add(file))
reasons = result.reasons
})
const root = nodePath.parse(process.cwd()).root
const fileTraceSpan = entrySpan.traceChild('node-file-trace')
const result = await fileTraceSpan.traceAsyncFn(() =>
nodeFileTrace(toTrace, {
base: root,
cache: nftCache,
processCwd: this.appDir,
readFile,
readlink,
stat,
resolve: doResolve
? (id, parent, job, _isCjs) => doResolve(id, parent, job)
: undefined,
ignore: [...TRACE_IGNORES, ...this.excludeFiles],
mixedModules: true,
})
)
// this uses the reasons tree to collect files specific to a certain
// parent allowing us to not have to trace each parent separately
const parentFilesMap = new Map<string, Set<string>>()
function propagateToParents(
parents: Set<string>,
file: string,
seen = new Set<string>()
) {
for (const parent of parents || []) {
if (!seen.has(parent)) {
seen.add(parent)
let parentFiles = parentFilesMap.get(parent)
if (!parentFiles) {
parentFiles = new Set()
parentFilesMap.set(parent, parentFiles)
}
parentFiles.add(file)
const parentReason = reasons.get(parent)
const tracedDeps: string[] = []
if (parentReason?.parents) {
propagateToParents(parentReason.parents, file, seen)
}
}
}
}
await finishModulesSpan
.traceChild('collect-traced-files')
.traceAsyncFn(() => {
for (const file of fileList!) {
const reason = reasons!.get(file)
for (const file of result.fileList) {
// don't include the entry itself
if (result.reasons[file].type === 'initial') {
if (!reason || reason.type === 'initial' || !reason.parents) {
continue
}
const filepath = nodePath.join(root, file)
tracedDeps.push(filepath)
propagateToParents(reason.parents, file)
}
// entryMod.buildInfo.cachedNextEntryTrace = {
// version: TRACE_OUTPUT_VERSION,
// tracedDeps,
// }
this.entryTraces.set(entryName, tracedDeps)
entryPaths.forEach((entry) => {
const entryName = entryNameMap.get(entry)!
const normalizedEntry = nodePath.relative(root, entry)
const curExtraEntries = additionalEntries.get(entryName)
const finalDeps = new Set<string>()
parentFilesMap.get(normalizedEntry)?.forEach((dep) => {
finalDeps.add(nodePath.join(root, dep))
})
if (curExtraEntries) {
for (const extraEntry of curExtraEntries.keys()) {
const normalizedExtraEntry = nodePath.relative(
root,
extraEntry
)
finalDeps.add(extraEntry)
parentFilesMap
.get(normalizedExtraEntry)
?.forEach((dep) => {
finalDeps.add(nodePath.join(root, dep))
})
}
}
this.entryTraces.set(entryName, finalDeps)
})
})
}
})
.then(
() => callback(),
......@@ -334,11 +393,6 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
)
let resolver = compilation.resolverFactory.get('normal')
resolver = resolver.withOptions({
...NODE_RESOLVE_OPTIONS,
extensions: undefined,
})
function getPkgName(name: string) {
const segments = name.split('/')
if (name[0] === '@' && segments.length > 1)
......@@ -346,67 +400,130 @@ export class TraceEntryPointsPlugin implements webpack.Plugin {
return segments.length ? segments[0] : null
}
const doResolve = async (
request: string,
parent: string,
job: import('@vercel/nft/out/node-file-trace').Job
): Promise<string> => {
return new Promise((resolve, reject) => {
resolver.resolve(
{},
nodePath.dirname(parent),
request,
{
fileDependencies: compilation.fileDependencies,
missingDependencies: compilation.missingDependencies,
contextDependencies: compilation.contextDependencies,
},
async (err: any, result: string, context: any) => {
if (err) return reject(err)
if (!result) {
return reject(new Error('module not found'))
}
const getResolve = (options: any) => {
const curResolver = resolver.withOptions(options)
return (
parent: string,
request: string,
job: import('@vercel/nft/out/node-file-trace').Job
) =>
new Promise<string>((resolve, reject) => {
const context = nodePath.dirname(parent)
curResolver.resolve(
{},
context,
request,
{
fileDependencies: compilation.fileDependencies,
missingDependencies: compilation.missingDependencies,
contextDependencies: compilation.contextDependencies,
},
async (err: any, result: string, resContext: any) => {
if (err) return reject(err)
if (!result) {
return reject(new Error('module not found'))
}
try {
if (result.includes('node_modules')) {
let requestPath = result
if (
!nodePath.isAbsolute(request) &&
request.includes('/') &&
context?.descriptionFileRoot
) {
requestPath =
context.descriptionFileRoot +
request.substr(getPkgName(request)?.length || 0) +
nodePath.sep +
'package.json'
}
try {
// we need to collect all parent package.json's used
// as webpack's resolve doesn't expose this and parent
// package.json could be needed for resolving e.g. stylis
// stylis/package.json -> stylis/dist/umd/package.json
if (result.includes('node_modules')) {
let requestPath = result.replace(/\\/g, '/')
// the descriptionFileRoot is not set to the last used
// package.json so we use nft's resolving for this
// see test/integration/build-trace-extra-entries/app/node_modules/nested-structure for example
const packageJsonResult = await job.getPjsonBoundary(
requestPath
)
if (packageJsonResult) {
await job.emitFile(
packageJsonResult + nodePath.sep + 'package.json',
'resolve',
parent
)
if (
!nodePath.isAbsolute(request) &&
request.includes('/') &&
resContext?.descriptionFileRoot
) {
requestPath = (
resContext.descriptionFileRoot +
request.substr(getPkgName(request)?.length || 0) +
nodePath.sep +
'package.json'
).replace(/\\/g, '/')
}
const rootSeparatorIndex = requestPath.indexOf('/')
let separatorIndex: number
while (
(separatorIndex = requestPath.lastIndexOf('/')) >
rootSeparatorIndex
) {
requestPath = requestPath.substr(0, separatorIndex)
const curPackageJsonPath = `${requestPath}/package.json`
if (await job.isFile(curPackageJsonPath)) {
await job.emitFile(
curPackageJsonPath,
'resolve',
parent
)
}
}
}
} catch (_err) {
// we failed to resolve the package.json boundary,
// we don't block emitting the initial asset from this
}
} catch (_err) {
// we failed to resolve the package.json boundary,
// we don't block emitting the initial asset from this
resolve(result)
}
resolve(result)
}
)
})
}
const CJS_RESOLVE_OPTIONS = {
...NODE_RESOLVE_OPTIONS,
extensions: undefined,
}
const ESM_RESOLVE_OPTIONS = {
...NODE_ESM_RESOLVE_OPTIONS,
extensions: undefined,
}
const doResolve = async (
request: string,
parent: string,
job: import('@vercel/nft/out/node-file-trace').Job,
isEsmRequested: boolean
): Promise<string> => {
if (this.staticImageImports && nextImageLoaderRegex.test(request)) {
throw new Error(
`not resolving ${request} as this is handled by next-image-loader`
)
})
}
// When in esm externals mode, and using import, we resolve with
// ESM resolving options.
const esmExternals = this.esmExternals
const looseEsmExternals = this.esmExternals === 'loose'
const preferEsm = esmExternals && isEsmRequested
const resolve = getResolve(
preferEsm ? ESM_RESOLVE_OPTIONS : CJS_RESOLVE_OPTIONS
)
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
let res: string = ''
try {
res = await resolve(parent, request, job)
} catch (_) {}
// If resolving fails, and we can use an alternative way
// try the alternative resolving options.
if (!res && (isEsmRequested || looseEsmExternals)) {
const resolveAlternative = getResolve(
preferEsm ? CJS_RESOLVE_OPTIONS : ESM_RESOLVE_OPTIONS
)
res = await resolveAlternative(parent, request, job)
}
if (!res) {
throw new Error(`failed to resolve ${request} from ${parent}`)
}
return res
}
this.tapfinishModules(
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -183,7 +183,7 @@
"@types/webpack-sources1": "npm:@types/webpack-sources@0.1.5",
"@types/ws": "8.2.0",
"@vercel/ncc": "0.27.0",
"@vercel/nft": "0.16.1",
"@vercel/nft": "0.17.0",
"amphtml-validator": "1.0.33",
"arg": "4.1.0",
"async-retry": "1.2.3",
......
......@@ -91,7 +91,7 @@ async function main() {
let totalUncompressedSize = 0
for (const file of result.fileList) {
if (result.reasons[file].type === 'initial') {
if (result.reasons.get(file).type === 'initial') {
continue
}
tracedDeps.add(file.replace(/\\/g, '/'))
......
import fs from 'fs'
import path from 'path'
import Image from 'next/image'
import testImage from '../public/test.jpg'
export default function Page(props) {
return (
<div>
<Image src={testImage} placeholder="blur" alt="test" />
</div>
)
}
export function getServerSideProps() {
try {
// this should be included in the trace since it's not an
// import
fs.readFileSync(path.join(process.cwd(), 'public/another.jpg'))
} catch (_) {}
return {
props: {},
}
}
......@@ -25,10 +25,16 @@ describe('build trace with extra entries', () => {
const anotherTrace = await fs.readJSON(
join(appDir, '.next/server/pages/another.js.nft.json')
)
const imageTrace = await fs.readJSON(
join(appDir, '.next/server/pages/image-import.js.nft.json')
)
expect(appTrace.files.some((file) => file.endsWith('hello.json'))).toBe(
true
)
expect(
appTrace.files.some((file) => file.endsWith('lib/get-data.js'))
).toBe(true)
expect(
indexTrace.files.some((file) => file.endsWith('hello.json'))
).toBeFalsy()
......@@ -51,5 +57,11 @@ describe('build trace with extra entries', () => {
file.includes('nested-structure/dist/constants.js')
)
).toBe(true)
expect(
imageTrace.files.some((file) => file.includes('public/another.jpg'))
).toBe(true)
expect(
imageTrace.files.some((file) => file.includes('public/test.jpg'))
).toBe(false)
})
})
import Link from 'next/link'
if (typeof window === 'undefined') {
import('nanoid').then((mod) => console.log(mod.nanoid()))
}
export default () => (
<div>
<Link href="/about">
......
......@@ -104,8 +104,13 @@ describe('Production Usage', () => {
/next\/link\.js/,
/next\/dist\/client\/link\.js/,
/next\/dist\/shared\/lib\/router\/utils\/resolve-rewrites\.js/,
/node_modules\/nanoid\/index\.js/,
/node_modules\/nanoid\/url-alphabet\/index\.js/,
],
notTests: [
/node_modules\/react\/cjs\/react\.development\.js/,
/node_modules\/nanoid\/index\.cjs/,
],
notTests: [/node_modules\/react\/cjs\/react\.development\.js/],
},
{
page: '/counter',
......
......@@ -5054,10 +5054,10 @@
resolved "https://registry.yarnpkg.com/@vercel/ncc/-/ncc-0.27.0.tgz#c0cfeebb0bebb56052719efa4a0ecc090a932c76"
integrity sha512-DllIJQapnU2YwewIhh/4dYesmMQw3h2cFtabECc/zSJHqUbNa0eJuEkRa6DXbZvh1YPWBtYQoPV17NlDpBw1Vw==
"@vercel/nft@0.16.1":
version "0.16.1"
resolved "https://registry.yarnpkg.com/@vercel/nft/-/nft-0.16.1.tgz#a636e3fc55f5502a3c652f8c1e01ca2bfac6cf68"
integrity sha512-OiPCdRDo9qA8QRQkgdyPInjF6TkvtWv79/WVpweufeOxjwUYju0jIUuFLS2PeB4wAIoKc/1CiizjhmJRqXNwAA==
"@vercel/nft@0.17.0":
version "0.17.0"
resolved "https://registry.yarnpkg.com/@vercel/nft/-/nft-0.17.0.tgz#28851fefe42fae7a116dc5e23a0a9da29929a18b"
integrity sha512-dXz4RAODHpEPl1Yfzk1UfVpZfqhY9O80FdI9sF/Hw2bXWj5022U9Z46VpdNYe8pDluSuQv/JUo/ZP4/OcsfDRw==
dependencies:
"@mapbox/node-pre-gyp" "^1.0.5"
acorn "^8.3.0"
......
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