Unverified Commit edf19014 authored by Shohei Maeda's avatar Shohei Maeda Committed by GitHub

feat: support outputFileTracing in App Router (#59139)

Fixes https://github.com/vercel/next.js/issues/54245

https://nextjs.org/docs/app/api-reference/next-config-js/output#caveats

Currently, `outputFileTracingExcludes`/`outputFileTracingIncludes` only
works with Pages router. This PR adds support for App router.
parent 936ae3de
...@@ -67,7 +67,6 @@ export async function collectBuildTraces({ ...@@ -67,7 +67,6 @@ export async function collectBuildTraces({
dir, dir,
config, config,
distDir, distDir,
pageKeys,
pageInfos, pageInfos,
staticPages, staticPages,
nextBuildSpan = new Span({ name: 'build' }), nextBuildSpan = new Span({ name: 'build' }),
...@@ -77,10 +76,6 @@ export async function collectBuildTraces({ ...@@ -77,10 +76,6 @@ export async function collectBuildTraces({
}: { }: {
dir: string dir: string
distDir: string distDir: string
pageKeys: {
app?: string[]
pages: string[]
}
staticPages: string[] staticPages: string[]
hasSsrAmpPages: boolean hasSsrAmpPages: boolean
outputFileTracingRoot: string outputFileTracingRoot: string
...@@ -191,6 +186,7 @@ export async function collectBuildTraces({ ...@@ -191,6 +186,7 @@ export async function collectBuildTraces({
const { outputFileTracingIncludes = {}, outputFileTracingExcludes = {} } = const { outputFileTracingIncludes = {}, outputFileTracingExcludes = {} } =
config.experimental config.experimental
const excludeGlobKeys = Object.keys(outputFileTracingExcludes) const excludeGlobKeys = Object.keys(outputFileTracingExcludes)
const includeGlobKeys = Object.keys(outputFileTracingIncludes)
await nextBuildSpan await nextBuildSpan
.traceChild('node-file-trace-build', { .traceChild('node-file-trace-build', {
...@@ -492,7 +488,6 @@ export async function collectBuildTraces({ ...@@ -492,7 +488,6 @@ export async function collectBuildTraces({
const isApp = entryName.startsWith('app/') const isApp = entryName.startsWith('app/')
const isPages = entryName.startsWith('pages/') const isPages = entryName.startsWith('pages/')
let route = entryName let route = entryName
if (isApp) { if (isApp) {
route = normalizeAppPath(route.substring('app'.length)) route = normalizeAppPath(route.substring('app'.length))
} }
...@@ -603,10 +598,8 @@ export async function collectBuildTraces({ ...@@ -603,10 +598,8 @@ export async function collectBuildTraces({
]) ])
}) })
// apply outputFileTracingIncludes/outputFileTracingExcludes after runTurbotrace
const includeExcludeSpan = nextBuildSpan.traceChild('apply-include-excludes') const includeExcludeSpan = nextBuildSpan.traceChild('apply-include-excludes')
const resolvedTraceIncludes = new Map<string, string[]>()
const includeGlobKeys = Object.keys(outputFileTracingIncludes)
await includeExcludeSpan.traceAsyncFn(async () => { await includeExcludeSpan.traceAsyncFn(async () => {
const globOrig = const globOrig =
require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob') require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')
...@@ -625,87 +618,107 @@ export async function collectBuildTraces({ ...@@ -625,87 +618,107 @@ export async function collectBuildTraces({
}) })
} }
for (let page of pageKeys.pages) { const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}
// edge routes have no trace files await Promise.all(
const [, pageInfo] = pageInfos.find((item) => item[0] === page) || [] [
if (pageInfo?.runtime === 'edge') { ...(entryNameFilesMap ? Object.entries(entryNameFilesMap) : new Map()),
continue ].map(async ([entryName]) => {
} const isApp = entryName.startsWith('app/')
const isPages = entryName.startsWith('pages/')
let route = entryName
if (isApp) {
route = normalizeAppPath(entryName)
}
if (isPages) {
route = normalizePagePath(entryName)
}
const combinedIncludes = new Set<string>() if (staticPages.includes(route)) {
const combinedExcludes = new Set<string>() return
}
page = normalizePagePath(page) // edge routes have no trace files
const [, pageInfo] = pageInfos.find((item) => item[0] === route) || []
if (pageInfo?.runtime === 'edge') {
return
}
for (const curGlob of includeGlobKeys) { const combinedIncludes = new Set<string>()
if (isMatch(page, [curGlob], { dot: true, contains: true })) { const combinedExcludes = new Set<string>()
for (const include of outputFileTracingIncludes[curGlob]) { for (const curGlob of includeGlobKeys) {
combinedIncludes.add(include.replace(/\\/g, '/')) if (isMatch(route, [curGlob], { dot: true, contains: true })) {
for (const include of outputFileTracingIncludes[curGlob]) {
combinedIncludes.add(include.replace(/\\/g, '/'))
}
} }
} }
}
for (const curGlob of excludeGlobKeys) { for (const curGlob of excludeGlobKeys) {
if (isMatch(page, [curGlob], { dot: true, contains: true })) { if (isMatch(route, [curGlob], { dot: true, contains: true })) {
for (const exclude of outputFileTracingExcludes[curGlob]) { for (const exclude of outputFileTracingExcludes[curGlob]) {
combinedExcludes.add(exclude) combinedExcludes.add(exclude)
}
} }
} }
}
if (!combinedIncludes?.size && !combinedExcludes?.size) { if (!combinedIncludes?.size && !combinedExcludes?.size) {
continue return
} }
const traceFile = path.join( const traceFile = path.join(
distDir, distDir,
'server/pages', `server`,
`${page}.js.nft.json` `${entryName}.js.nft.json`
) )
const pageDir = path.dirname(traceFile) const pageDir = path.dirname(traceFile)
const traceContent = JSON.parse(await fs.readFile(traceFile, 'utf8')) const traceContent = JSON.parse(await fs.readFile(traceFile, 'utf8'))
const includes: string[] = [] const includes: string[] = []
const resolvedTraceIncludes = new Map<string, string[]>()
if (combinedIncludes?.size) {
await Promise.all(
[...combinedIncludes].map(async (includeGlob) => {
const results = await glob(includeGlob)
const resolvedInclude = resolvedTraceIncludes.get(
includeGlob
) || [
...results.map((file) => {
return path.relative(pageDir, path.join(dir, file))
}),
]
includes.push(...resolvedInclude)
resolvedTraceIncludes.set(includeGlob, resolvedInclude)
})
)
}
const combined = new Set([...traceContent.files, ...includes])
if (combinedIncludes?.size) { if (combinedExcludes?.size) {
await Promise.all( const resolvedGlobs = [...combinedExcludes].map((exclude) =>
[...combinedIncludes].map(async (includeGlob) => { path.join(dir, exclude)
const results = await glob(includeGlob) )
const resolvedInclude = resolvedTraceIncludes.get(includeGlob) || [ combined.forEach((file) => {
...results.map((file) => { if (
return path.relative(pageDir, path.join(dir, file)) isMatch(path.join(pageDir, file), resolvedGlobs, {
}), dot: true,
] contains: true,
includes.push(...resolvedInclude) })
resolvedTraceIncludes.set(includeGlob, resolvedInclude) ) {
combined.delete(file)
}
}) })
) }
}
const combined = new Set([...traceContent.files, ...includes])
if (combinedExcludes?.size) { // overwrite trace file with custom includes/excludes
const resolvedGlobs = [...combinedExcludes].map((exclude) => await fs.writeFile(
path.join(dir, exclude) traceFile,
JSON.stringify({
version: traceContent.version,
files: [...combined],
})
) )
combined.forEach((file) => { })
if ( )
isMatch(path.join(pageDir, file), resolvedGlobs, {
dot: true,
contains: true,
})
) {
combined.delete(file)
}
})
}
await fs.writeFile(
traceFile,
JSON.stringify({
version: traceContent.version,
files: [...combined],
})
)
}
}) })
debug(`finished build tracing ${Date.now() - startTime}ms`) debug(`finished build tracing ${Date.now() - startTime}ms`)
......
...@@ -1109,7 +1109,6 @@ export default async function build( ...@@ -1109,7 +1109,6 @@ export default async function build(
dir, dir,
config, config,
distDir, distDir,
pageKeys,
pageInfos: [], pageInfos: [],
staticPages: [], staticPages: [],
hasSsrAmpPages: false, hasSsrAmpPages: false,
...@@ -1924,7 +1923,6 @@ export default async function build( ...@@ -1924,7 +1923,6 @@ export default async function build(
dir, dir,
config, config,
distDir, distDir,
pageKeys,
pageInfos: Object.entries(pageInfos), pageInfos: Object.entries(pageInfos),
staticPages: [...staticPages], staticPages: [...staticPages],
nextBuildSpan, nextBuildSpan,
......
import fs from 'fs'
import path from 'path'
export const dynamic = 'force-dynamic'
export async function GET() {
// dummy call
fs.readdirSync(path.join(process.cwd(), 'public/exclude-me'))
return new Response('foo')
}
...@@ -22,9 +22,11 @@ module.exports = { ...@@ -22,9 +22,11 @@ module.exports = {
experimental: { experimental: {
outputFileTracingIncludes: { outputFileTracingIncludes: {
'/index': ['include-me/*'], '/index': ['include-me/*'],
'/route1': ['include-me/*'],
}, },
outputFileTracingExcludes: { outputFileTracingExcludes: {
'/index': ['public/exclude-me/**/*'], '/index': ['public/exclude-me/**/*'],
'/route1': ['public/exclude-me/**/*'],
}, },
turbotrace: { turbotrace: {
contextDirectory: path.join(__dirname, '..', '..', '..', '..'), contextDirectory: path.join(__dirname, '..', '..', '..', '..'),
......
...@@ -29,6 +29,23 @@ describe('build trace with extra entries', () => { ...@@ -29,6 +29,23 @@ describe('build trace with extra entries', () => {
const imageTrace = await fs.readJSON( const imageTrace = await fs.readJSON(
join(appDir, '.next/server/pages/image-import.js.nft.json') join(appDir, '.next/server/pages/image-import.js.nft.json')
) )
const appDirRoute1Trace = await fs.readJSON(
join(appDir, '.next/server/app/route1/route.js.nft.json')
)
expect(
appDirRoute1Trace.files.some(
(file) => file === '../../../../include-me/hello.txt'
)
).toBe(true)
expect(
appDirRoute1Trace.files.some(
(file) => file === '../../../../include-me/second.txt'
)
).toBe(true)
expect(
appDirRoute1Trace.files.some((file) => file.includes('exclude-me'))
).toBe(false)
const tracedFiles = [ const tracedFiles = [
...appTrace.files, ...appTrace.files,
......
import fs from 'fs'
import path from 'path'
export const dynamic = 'force-dynamic'
export async function GET() {
// dummy call
fs.readdirSync(path.join(process.cwd(), 'public/exclude-me'))
return new Response('foo')
}
...@@ -22,9 +22,11 @@ module.exports = { ...@@ -22,9 +22,11 @@ module.exports = {
experimental: { experimental: {
outputFileTracingIncludes: { outputFileTracingIncludes: {
'/index': ['include-me/**/*'], '/index': ['include-me/**/*'],
'/route1': ['include-me/**/*'],
}, },
outputFileTracingExcludes: { outputFileTracingExcludes: {
'/index': ['public/exclude-me/**/*'], '/index': ['public/exclude-me/**/*'],
'/route1': ['public/exclude-me/**/*'],
}, },
}, },
} }
...@@ -29,6 +29,23 @@ describe('build trace with extra entries', () => { ...@@ -29,6 +29,23 @@ describe('build trace with extra entries', () => {
const imageTrace = await fs.readJSON( const imageTrace = await fs.readJSON(
join(appDir, '.next/server/pages/image-import.js.nft.json') join(appDir, '.next/server/pages/image-import.js.nft.json')
) )
const appDirRoute1Trace = await fs.readJSON(
join(appDir, '.next/server/app/route1/route.js.nft.json')
)
expect(
appDirRoute1Trace.files.some(
(file) => file === '../../../../include-me/hello.txt'
)
).toBe(true)
expect(
appDirRoute1Trace.files.some(
(file) => file === '../../../../include-me/second.txt'
)
).toBe(true)
expect(
appDirRoute1Trace.files.some((file) => file.includes('exclude-me'))
).toBe(false)
expect(appTrace.files.some((file) => file.endsWith('hello.json'))).toBe( expect(appTrace.files.some((file) => file.endsWith('hello.json'))).toBe(
true true
......
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