Unverified Commit 29010ffd authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update cases for build complete with adapters (#84361)

This handles `i18n` cases, ensures `pathname` field is prefixed with
`basePath` when configured, and fixes interop with `output: 'export'`
configured.
parent 9c9e793b
...@@ -35,6 +35,8 @@ import { ...@@ -35,6 +35,8 @@ import {
JSON_CONTENT_TYPE_HEADER, JSON_CONTENT_TYPE_HEADER,
NEXT_RESUME_HEADER, NEXT_RESUME_HEADER,
} from '../../lib/constants' } from '../../lib/constants'
import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
interface SharedRouteFields { interface SharedRouteFields {
/** /**
...@@ -62,6 +64,12 @@ interface SharedRouteFields { ...@@ -62,6 +64,12 @@ interface SharedRouteFields {
*/ */
assets: Record<string, string> assets: Record<string, string>
/**
* wasmAssets are bundled wasm files with mapping of name
* to filePath on disk
*/
wasmAssets?: Record<string, string>
/** /**
* config related to the route * config related to the route
*/ */
...@@ -77,6 +85,12 @@ interface SharedRouteFields { ...@@ -77,6 +85,12 @@ interface SharedRouteFields {
* region preferences to the provider being used * region preferences to the provider being used
*/ */
preferredRegion?: string | string[] preferredRegion?: string | string[]
/**
* env is the environment variables to expose, this is only
* populated for edge runtime currently
*/
env?: Record<string, string>
} }
} }
...@@ -297,9 +311,30 @@ export interface NextAdapter { ...@@ -297,9 +311,30 @@ export interface NextAdapter {
}) => Promise<void> | void }) => Promise<void> | void
} }
function normalizePathnames(
config: NextConfigComplete,
outputs: AdapterOutputs
) {
// normalize pathname field with basePath
if (config.basePath) {
for (const output of [
...outputs.pages,
...outputs.pagesApi,
...outputs.appPages,
...outputs.appRoutes,
...outputs.prerenders,
...outputs.staticFiles,
...(outputs.middleware ? [outputs.middleware] : []),
]) {
output.pathname = addPathPrefix(output.pathname, config.basePath)
}
}
}
export async function handleBuildComplete({ export async function handleBuildComplete({
dir, dir,
config, config,
configOutDir,
distDir, distDir,
pageKeys, pageKeys,
tracingRoot, tracingRoot,
...@@ -318,6 +353,7 @@ export async function handleBuildComplete({ ...@@ -318,6 +353,7 @@ export async function handleBuildComplete({
}: { }: {
dir: string dir: string
distDir: string distDir: string
configOutDir: string
adapterPath: string adapterPath: string
tracingRoot: string tracingRoot: string
nextVersion: string nextVersion: string
...@@ -341,16 +377,34 @@ export async function handleBuildComplete({ ...@@ -341,16 +377,34 @@ export async function handleBuildComplete({
if (typeof adapterMod.onBuildComplete === 'function') { if (typeof adapterMod.onBuildComplete === 'function') {
Log.info(`Running onBuildComplete from ${adapterMod.name}`) Log.info(`Running onBuildComplete from ${adapterMod.name}`)
try { const outputs: AdapterOutputs = {
const outputs: AdapterOutputs = { pages: [],
pages: [], pagesApi: [],
pagesApi: [], appPages: [],
appPages: [], appRoutes: [],
appRoutes: [], prerenders: [],
prerenders: [], staticFiles: [],
staticFiles: [], }
}
if (config.output === 'export') {
// collect export assets and provide as static files
const exportFiles = await recursiveReadDir(configOutDir)
for (const file of exportFiles) {
let pathname = (
file.endsWith('.html') ? file.replace(/\.html$/, '') : file
).replace(/\\/g, '/')
pathname = pathname.startsWith('/') ? pathname : `/${pathname}`
outputs.staticFiles.push({
id: file,
pathname,
filePath: path.join(configOutDir, file),
type: AdapterOutputType.STATIC_FILE,
} satisfies AdapterOutput['STATIC_FILE'])
}
} else {
const staticFiles = await recursiveReadDir(path.join(distDir, 'static')) const staticFiles = await recursiveReadDir(path.join(distDir, 'static'))
for (const file of staticFiles) { for (const file of staticFiles) {
...@@ -460,12 +514,15 @@ export async function handleBuildComplete({ ...@@ -460,12 +514,15 @@ export async function handleBuildComplete({
'' ''
), ),
assets: {}, assets: {},
config: wasmAssets: {},
type === AdapterOutputType.MIDDLEWARE config: {
...(type === AdapterOutputType.MIDDLEWARE
? { ? {
matchers: page.matchers, matchers: page.matchers,
} }
: {}, : {}),
env: page.env,
},
} }
function handleFile(file: string) { function handleFile(file: string) {
...@@ -482,9 +539,15 @@ export async function handleBuildComplete({ ...@@ -482,9 +539,15 @@ export async function handleBuildComplete({
for (const file of page.files) { for (const file of page.files) {
handleFile(file) handleFile(file)
} }
for (const item of [...(page.wasm || []), ...(page.assets || [])]) { for (const item of [...(page.assets || [])]) {
handleFile(item.filePath) handleFile(item.filePath)
} }
for (const item of page.wasm || []) {
if (!output.wasmAssets) {
output.wasmAssets = {}
}
output.wasmAssets[item.name] = item.filePath
}
if (type === AdapterOutputType.MIDDLEWARE) { if (type === AdapterOutputType.MIDDLEWARE) {
outputs.middleware = output outputs.middleware = output
...@@ -528,12 +591,28 @@ export async function handleBuildComplete({ ...@@ -528,12 +591,28 @@ export async function handleBuildComplete({
// if it's an auto static optimized page it's just // if it's an auto static optimized page it's just
// a static file // a static file
if (staticPages.has(page)) { if (staticPages.has(page)) {
outputs.staticFiles.push({ if (config.i18n) {
id: page, for (const locale of config.i18n.locales || []) {
pathname: route, const localePage =
type: AdapterOutputType.STATIC_FILE, page === '/' ? `/${locale}` : addPathPrefix(page, `/${locale}`)
filePath: pageFile.replace(/\.js$/, '.html'), outputs.staticFiles.push({
} satisfies AdapterOutput['STATIC_FILE']) id: localePage,
pathname: localePage,
type: AdapterOutputType.STATIC_FILE,
filePath: path.join(
pagesDistDir,
`${normalizePagePath(localePage)}.html`
),
} satisfies AdapterOutput['STATIC_FILE'])
}
} else {
outputs.staticFiles.push({
id: page,
pathname: route,
type: AdapterOutputType.STATIC_FILE,
filePath: pageFile.replace(/\.js$/, '.html'),
} satisfies AdapterOutput['STATIC_FILE'])
}
continue continue
} }
...@@ -639,7 +718,12 @@ export async function handleBuildComplete({ ...@@ -639,7 +718,12 @@ export async function handleBuildComplete({
childRoute: string, childRoute: string,
allowMissing?: boolean allowMissing?: boolean
) => { ) => {
const parentOutput = pageOutputMap[srcRoute] || appOutputMap[srcRoute] const normalizedSrcRoute = normalizeLocalePath(
srcRoute,
config.i18n?.locales || []
).pathname
const parentOutput =
pageOutputMap[normalizedSrcRoute] || appOutputMap[normalizedSrcRoute]
if (!parentOutput && !allowMissing) { if (!parentOutput && !allowMissing) {
console.error({ console.error({
...@@ -966,7 +1050,11 @@ export async function handleBuildComplete({ ...@@ -966,7 +1050,11 @@ export async function handleBuildComplete({
} }
prerenderGroupId += 1 prerenderGroupId += 1
} }
}
normalizePathnames(config, outputs)
try {
await adapterMod.onBuildComplete({ await adapterMod.onBuildComplete({
routes: { routes: {
dynamicRoutes: routesManifest.dynamicRoutes, dynamicRoutes: routesManifest.dynamicRoutes,
......
...@@ -3796,7 +3796,7 @@ export default async function build( ...@@ -3796,7 +3796,7 @@ export default async function build(
dataRoute: path.posix.join( dataRoute: path.posix.join(
'/_next/data', '/_next/data',
buildId, buildId,
`${file}.json` `${localePage}.json`
), ),
prefetchDataRoute: undefined, prefetchDataRoute: undefined,
allowHeader: ALLOWED_HEADERS, allowHeader: ALLOWED_HEADERS,
...@@ -4085,6 +4085,9 @@ export default async function build( ...@@ -4085,6 +4085,9 @@ export default async function build(
}) })
} }
// This should come after output: export handling but before
// output: standalone, in the future output: standalone might
// not be allowed if an adapter with onBuildComplete is configured
const adapterPath = config.experimental.adapterPath const adapterPath = config.experimental.adapterPath
if (adapterPath) { if (adapterPath) {
await nextBuildSpan await nextBuildSpan
...@@ -4094,6 +4097,7 @@ export default async function build( ...@@ -4094,6 +4097,7 @@ export default async function build(
dir, dir,
distDir, distDir,
config, config,
configOutDir: path.join(dir, configOutDir),
staticPages, staticPages,
nextVersion: process.env.__NEXT_VERSION as string, nextVersion: process.env.__NEXT_VERSION as string,
tracingRoot: outputFileTracingRoot, tracingRoot: outputFileTracingRoot,
......
import fs from 'fs'
import type { NextAdapter } from 'next'
import { nextTestSetup } from 'e2e-utils'
import { version as nextVersion } from 'next/package.json'
process.env.TEST_EXPORT = '1'
describe('adapter-config export', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
it('should call onBuildComplete with correct context', async () => {
const nonExportFiles = [
'app/node-app/page.tsx',
'app/node-route/route.ts',
'app/edge-route/route.ts',
'app/isr-route/route.ts',
'app/isr-route/[slug]/route.ts',
'app/edge-app/page.tsx',
'pages/api/edge-pages.ts',
'pages/api/node-pages.ts',
'pages/edge-pages/index.tsx',
'pages/node-pages/index.tsx',
]
for (const file of nonExportFiles) {
await next.remove(file)
}
await next.build()
expect(next.cliOutput).toContain('onBuildComplete called')
const {
outputs,
routes,
config,
...ctx
}: Parameters<NextAdapter['onBuildComplete']>[0] = await next.readJSON(
'build-complete.json'
)
for (const field of ['distDir', 'projectDir', 'repoRoot']) {
expect(ctx[field]).toBeString()
if (!fs.existsSync(ctx[field])) {
throw new Error(
`Invalid dir value provided for ${field} value ${ctx[field]}`
)
}
}
expect(ctx.nextVersion).toBe(nextVersion)
expect(config?.basePath).toBe('/docs')
const combinedRouteOutputs = [
...outputs.appPages,
...outputs.appRoutes,
...outputs.pages,
...outputs.pagesApi,
]
expect(outputs.middleware).toBeFalsy()
expect(outputs.prerenders).toEqual([])
expect(combinedRouteOutputs).toEqual([])
for (const output of outputs.staticFiles) {
expect(output.id).toBeTruthy()
if (output.filePath.endsWith('.html')) {
expect(output.pathname.endsWith('.html')).toBe(false)
}
expect(output.pathname).toStartWith('/docs/')
const stats = await fs.promises.stat(output.filePath)
expect(stats.isFile()).toBe(true)
}
expect(routes).toEqual({
dynamicRoutes: expect.toBeArray(),
rewrites: expect.toBeObject(),
redirects: expect.toBeArray(),
headers: expect.toBeArray(),
})
})
})
...@@ -95,7 +95,7 @@ describe('adapter-config', () => { ...@@ -95,7 +95,7 @@ describe('adapter-config', () => {
if (output.filePath.endsWith('.html')) { if (output.filePath.endsWith('.html')) {
expect(output.pathname.endsWith('.html')).toBe(false) expect(output.pathname.endsWith('.html')).toBe(false)
} else { } else {
expect(output.pathname).toStartWith('/_next/static') expect(output.pathname).toStartWith('/docs/_next/static')
} }
const stats = await fs.promises.stat(output.filePath) const stats = await fs.promises.stat(output.filePath)
...@@ -153,6 +153,15 @@ describe('adapter-config', () => { ...@@ -153,6 +153,15 @@ describe('adapter-config', () => {
expect(route.config).toBeObject() expect(route.config).toBeObject()
expect(route.pathname).toBeString() expect(route.pathname).toBeString()
expect(route.runtime).toBe('edge') expect(route.runtime).toBe('edge')
expect(route.config.env).toEqual(
expect.objectContaining({
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: expect.toBeString(),
__NEXT_BUILD_ID: expect.toBeString(),
__NEXT_PREVIEW_MODE_ENCRYPTION_KEY: expect.toBeString(),
__NEXT_PREVIEW_MODE_ID: expect.toBeString(),
__NEXT_PREVIEW_MODE_SIGNING_KEY: expect.toBeString(),
})
)
const stats = await fs.promises.stat(route.filePath) const stats = await fs.promises.stat(route.filePath)
expect(stats.isFile()).toBe(true) expect(stats.isFile()).toBe(true)
......
...@@ -7,6 +7,7 @@ const nextConfig = { ...@@ -7,6 +7,7 @@ const nextConfig = {
adapterPath: require.resolve('./my-adapter.mjs'), adapterPath: require.resolve('./my-adapter.mjs'),
ppr: Boolean(process.env.TEST_PPR), ppr: Boolean(process.env.TEST_PPR),
}, },
output: process.env.TEST_EXPORT ? 'export' : undefined,
} }
export default nextConfig export default nextConfig
...@@ -27,7 +27,8 @@ export function getStaticProps({ params }) { ...@@ -27,7 +27,8 @@ export function getStaticProps({ params }) {
params, params,
now: Date.now(), now: Date.now(),
}, },
revalidate: params.slug === 'first' ? 60 : undefined, revalidate:
!process.env.TEST_EXPORT && params.slug === 'first' ? 60 : undefined,
} }
} }
......
...@@ -27,7 +27,8 @@ export function getStaticProps({ params }) { ...@@ -27,7 +27,8 @@ export function getStaticProps({ params }) {
params, params,
now: Date.now(), now: Date.now(),
}, },
revalidate: params.slug === 'first' ? 60 : undefined, revalidate:
!process.env.TEST_EXPORT && params.slug === 'first' ? 60 : undefined,
} }
} }
......
...@@ -27,7 +27,8 @@ export function getStaticProps({ params }) { ...@@ -27,7 +27,8 @@ export function getStaticProps({ params }) {
params, params,
now: Date.now(), now: Date.now(),
}, },
revalidate: params.slug === 'first' ? 60 : undefined, revalidate:
!process.env.TEST_EXPORT && params.slug === 'first' ? 60 : undefined,
} }
} }
......
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