Unverified Commit 765b39c4 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Prerender static metadata under dynamic segments to canonical pathname (#93873)

### What?

Fixes an invariant failure (`failed to find source route
/dynamic/[id]/apple-icon.png for prerender
/dynamic/[id]/apple-icon.png`) raised by the build adapter when an app
contains static metadata files (`apple-icon.png`, `icon.png`,
`opengraph-image.png`, `twitter-image.png`, `sitemap.xml`) under a
dynamic segment.

### Why?

Static metadata files under a dynamic segment were treated as full
dynamic prerenders: they ended up in `prerenderManifest.dynamicRoutes`
with `fallbackRouteParams`, but no `.body` file was exported and they
never received an `appOutputMap` entry. The adapter's `dynamicRoutes`
loop then asked `getParentOutput` for a source route that didn't exist
and threw.

These files are content-stable across params — the route handler returns
the same bytes for every URL that matches the dynamic pattern — so they
should prerender once under a canonical pathname rather than be treated
like per-param dynamic routes.

### How?

- New `getStaticMetadataPrerenderPathname` helper that maps
`/dynamic/[id]/apple-icon.png` to `/dynamic/-/apple-icon.png`. This is
the canonical pathname already used by `fillStaticMetadataSegment` for
HTML link emission.
- In `build/utils.ts`, route `APP_ROUTE` entries that are static
metadata files through a new `buildStaticMetadataStaticPaths` (one
prerender path, no fallback params) instead of the regular
`buildAppStaticPaths`.
- In `build/index.ts`:
- Rewrite each prerendered static metadata route to its `-`-placeholder
pathname before splitting into known/unknown buckets, so it lands in
`prerenderManifest.routes` with a `.body` file.
- Skip static metadata entries in the `dynamicPrerenderedRoutes` loop so
they don't get a stray `PRERENDER` manifest entry.
- Defensive sweep before write: drop any leftover bracketed metadata
keys from `prerenderManifest.dynamicRoutes`.
- In the adapter, look up `prerenderManifest.routes` under the canonical
placeholder pathname (with locale prefix when applicable) and skip
static metadata in the `dynamicRoutes` loop.
- Unit tests in `get-metadata-route.test.ts` lock in the placeholder
behavior for the tricky cases: catchall, optional catchall, multi-level
dynamic, literals between dynamics, dynamic + catchall mix.

Reproduction:
`test/e2e/app-dir/metadata-static-file/metadata-static-file-dynamic-route.test.ts`
configured with `adapterPath` previously crashed at
`handleBuildComplete`; all three cases in that file now pass.

Runtime stays the same: arbitrary param URLs continue to be served by
the dynamic route handler shipped with the app route; only the canonical
`-` URL is statically served.

<!-- NEXT_JS_LLM_PR -->
parent 685d5b9e
...@@ -1277,5 +1277,6 @@ ...@@ -1277,5 +1277,6 @@
"1276": "Compilation failed but no issues were recorded", "1276": "Compilation failed but no issues were recorded",
"1277": "no route matched for path \"%s\"", "1277": "no route matched for path \"%s\"",
"1278": "compileRoute: either routeSpecifier or path is required", "1278": "compileRoute: either routeSpecifier or path is required",
"1279": "\\`experimental.appShells\\` requires the following to also be enabled: %s. Please update your %s accordingly." "1279": "\\`experimental.appShells\\` requires the following to also be enabled: %s. Please update your %s accordingly.",
"1280": "Invariant: expected static metadata route to have a prerender pathname (%s)"
} }
...@@ -43,6 +43,7 @@ import { ...@@ -43,6 +43,7 @@ import {
} from '../../lib/constants' } from '../../lib/constants'
import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
import { getStaticMetadataPrerenderPathname } from '../../lib/metadata/get-metadata-route'
import { isStaticMetadataFile } from '../../lib/metadata/is-metadata-route' import { isStaticMetadataFile } from '../../lib/metadata/is-metadata-route'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix' import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import { getRedirectStatus, modifyRouteRegex } from '../../lib/redirect-status' import { getRedirectStatus, modifyRouteRegex } from '../../lib/redirect-status'
...@@ -988,19 +989,17 @@ export async function handleBuildComplete({ ...@@ -988,19 +989,17 @@ export async function handleBuildComplete({
// Dynamic metadata routes (e.g. robots/sitemap using connection()) // Dynamic metadata routes (e.g. robots/sitemap using connection())
// should remain app routes in adapter outputs. // should remain app routes in adapter outputs.
const isStaticMetadataRoute = isStaticMetadataFile(normalizedPage) const isStaticMetadataRoute = isStaticMetadataFile(normalizedPage)
const staticMetadataPrerenderPathname =
getStaticMetadataPrerenderPathname(normalizedPage) ?? normalizedPage
const isPrerenderedMetadataRoute = const isPrerenderedMetadataRoute =
prerenderManifest.routes[normalizedPage] || prerenderManifest.routes[staticMetadataPrerenderPathname] ||
prerenderManifest.dynamicRoutes[normalizedPage] ||
config.i18n?.locales?.some((locale) => { config.i18n?.locales?.some((locale) => {
const localePathname = path.posix.join( const localePathname = path.posix.join(
'/', '/',
locale, locale,
normalizedPage.slice(1) staticMetadataPrerenderPathname.slice(1)
)
return (
prerenderManifest.routes[localePathname] ||
prerenderManifest.dynamicRoutes[localePathname]
) )
return prerenderManifest.routes[localePathname]
}) })
if (isStaticMetadataRoute && isPrerenderedMetadataRoute) { if (isStaticMetadataRoute && isPrerenderedMetadataRoute) {
...@@ -1522,6 +1521,10 @@ export async function handleBuildComplete({ ...@@ -1522,6 +1521,10 @@ export async function handleBuildComplete({
} }
for (const dynamicRoute in prerenderManifest.dynamicRoutes) { for (const dynamicRoute in prerenderManifest.dynamicRoutes) {
if (isStaticMetadataFile(dynamicRoute)) {
continue
}
const { const {
fallback, fallback,
fallbackExpire, fallbackExpire,
......
...@@ -165,6 +165,8 @@ import { webpackBuild } from './webpack-build' ...@@ -165,6 +165,8 @@ import { webpackBuild } from './webpack-build'
import { NextBuildContext } from './build-context' import { NextBuildContext } from './build-context'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { isAppRouteRoute } from '../lib/is-app-route-route' import { isAppRouteRoute } from '../lib/is-app-route-route'
import { getStaticMetadataPrerenderPathname } from '../lib/metadata/get-metadata-route'
import { isStaticMetadataFile } from '../lib/metadata/is-metadata-route'
import { createClientRouterFilter } from '../lib/create-client-router-filter' import { createClientRouterFilter } from '../lib/create-client-router-filter'
import { startTypeChecking } from './type-check' import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites' import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
...@@ -3184,13 +3186,39 @@ export default async function build( ...@@ -3184,13 +3186,39 @@ export default async function build(
const unsortedUnknownPrerenderRoutes: PrerenderedRoute[] = [] const unsortedUnknownPrerenderRoutes: PrerenderedRoute[] = []
const unsortedKnownPrerenderRoutes: PrerenderedRoute[] = [] const unsortedKnownPrerenderRoutes: PrerenderedRoute[] = []
for (const prerenderedRoute of prerenderedRoutes) { for (const prerenderedRoute of prerenderedRoutes) {
let route = prerenderedRoute
// Static metadata files under dynamic segments (e.g.
// `/[id]/apple-icon.png`) produce the same bytes regardless of
// params, so they prerender once to a canonical pathname with
// dynamic segments replaced by `-` (e.g. `/-/apple-icon.png`).
// Rewriting here ensures they land in `prerenderManifest.routes`
// as known static entries rather than in `dynamicRoutes` with
// fallback params, which they don't actually need.
const staticMetadataPrerenderPathname =
getStaticMetadataPrerenderPathname(prerenderedRoute.pathname)
if ( if (
prerenderedRoute.fallbackRouteParams && staticMetadataPrerenderPathname &&
prerenderedRoute.fallbackRouteParams.length > 0 staticMetadataPrerenderPathname !== prerenderedRoute.pathname
) { ) {
unsortedUnknownPrerenderRoutes.push(prerenderedRoute) route = {
params: prerenderedRoute.params,
pathname: staticMetadataPrerenderPathname,
encodedPathname: staticMetadataPrerenderPathname,
fallbackRouteParams: undefined,
fallbackMode: prerenderedRoute.fallbackMode,
fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined,
}
}
if (
route.fallbackRouteParams &&
route.fallbackRouteParams.length > 0
) {
unsortedUnknownPrerenderRoutes.push(route)
} else { } else {
unsortedKnownPrerenderRoutes.push(prerenderedRoute) unsortedKnownPrerenderRoutes.push(route)
} }
} }
...@@ -3364,6 +3392,16 @@ export default async function build( ...@@ -3364,6 +3392,16 @@ export default async function build(
} }
for (const route of dynamicPrerenderedRoutes) { for (const route of dynamicPrerenderedRoutes) {
// Static metadata files are rewritten above into the known
// static bucket under their `-`-placeholder pathname, so any
// entry that slips through here (e.g. an unexpected fallback
// shape) must not generate a dynamic PRERENDER manifest entry
// — the route handler shipped with the dynamic route still
// serves these at runtime.
if (isStaticMetadataFile(route.pathname)) {
continue
}
const normalizedRoute = normalizePagePath(route.pathname) const normalizedRoute = normalizePagePath(route.pathname)
const parentPageInfo = pageInfos.get(page) as PageInfo const parentPageInfo = pageInfos.get(page) as PageInfo
...@@ -4070,6 +4108,20 @@ export default async function build( ...@@ -4070,6 +4108,20 @@ export default async function build(
NextBuildContext.allowedRevalidateHeaderKeys = NextBuildContext.allowedRevalidateHeaderKeys =
config.experimental.allowedRevalidateHeaderKeys config.experimental.allowedRevalidateHeaderKeys
// Defensive sweep: static metadata files should never end up in
// `dynamicRoutes` because they are rewritten to the `-`-placeholder
// pathname and added to `routes` above. If anything upstream
// (e.g. a code path that calls `addDynamicRoute` directly) still
// registers a bracketed entry like `/[id]/apple-icon.png` here, the
// adapter would later look for a parent app output that doesn't
// exist and throw an invariant error. Strip those entries before the
// manifest is written.
for (const route of Object.keys(prerenderManifest.dynamicRoutes)) {
if (isStaticMetadataFile(route)) {
delete prerenderManifest.dynamicRoutes[route]
}
}
await writePrerenderManifest(distDir, prerenderManifest) await writePrerenderManifest(distDir, prerenderManifest)
await writeManifest( await writeManifest(
path.join(distDir, SERVER_DIRECTORY, PREFETCH_HINTS), path.join(distDir, SERVER_DIRECTORY, PREFETCH_HINTS),
......
...@@ -81,13 +81,9 @@ import type { ...@@ -81,13 +81,9 @@ import type {
import type { FunctionsConfigManifest, ManifestRoute } from './index' import type { FunctionsConfigManifest, ManifestRoute } from './index'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { parseNormalizedAppRoute } from '../shared/lib/router/routes/app' import { parseNormalizedAppRoute } from '../shared/lib/router/routes/app'
import { fillStaticMetadataSegment } from '../lib/metadata/get-metadata-route' import { getStaticMetadataPrerenderPathname } from '../lib/metadata/get-metadata-route'
import { STATIC_METADATA_IMAGES } from '../lib/metadata/is-metadata-route' import { isStaticMetadataFile } from '../lib/metadata/is-metadata-route'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
// Build a set of static metadata image filenames for quick lookup
const staticMetadataImageFilenames = new Set<string>(
Object.values(STATIC_METADATA_IMAGES).map((meta) => meta.filename)
)
/** /**
* Get the display path for build output. For static metadata files under * Get the display path for build output. For static metadata files under
...@@ -95,26 +91,42 @@ const staticMetadataImageFilenames = new Set<string>( ...@@ -95,26 +91,42 @@ const staticMetadataImageFilenames = new Set<string>(
* e.g., /dynamic/[id]/icon.png -> /dynamic/-/icon.png * e.g., /dynamic/[id]/icon.png -> /dynamic/-/icon.png
*/ */
function getTreeViewDisplayPath(pagePath: string): string { function getTreeViewDisplayPath(pagePath: string): string {
// Check if the path contains dynamic segments const prerenderPathname = getStaticMetadataPrerenderPathname(
if (!isDynamicRoute(pagePath)) { pagePath.startsWith('/') ? pagePath : `/${pagePath}`
return pagePath )
} return prerenderPathname ?? pagePath
}
// Check if the filename is a static metadata image function buildStaticMetadataStaticPaths(page: string): {
const lastSlash = pagePath.lastIndexOf('/') fallbackMode: FallbackMode | undefined
const filename = pagePath.slice(lastSlash + 1) prerenderedRoutes: PrerenderedRoute[]
const dotIndex = filename.lastIndexOf('.') } {
const baseName = dotIndex > 0 ? filename.slice(0, dotIndex) : filename let pathname = normalizeAppPath(page)
if (pathname.endsWith('/route')) {
pathname = pathname.slice(0, -'/route'.length)
}
// Check against known static metadata image filenames (e.g., icon, apple-icon, opengraph-image) const prerenderPathname = getStaticMetadataPrerenderPathname(pathname)
if (!staticMetadataImageFilenames.has(baseName)) { if (!prerenderPathname) {
return pagePath throw new Error(
`Invariant: expected static metadata route to have a prerender pathname (${page})`
)
} }
// Transform using the static metadata resolver so dynamic segments use "-" return {
const segment = pagePath.slice(0, lastSlash) fallbackMode: undefined,
const lastSegment = filename prerenderedRoutes: [
return fillStaticMetadataSegment(segment, lastSegment) {
params: {},
pathname: prerenderPathname,
encodedPathname: prerenderPathname,
fallbackRouteParams: undefined,
fallbackMode: undefined,
fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined,
},
],
}
} }
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
...@@ -871,29 +883,42 @@ export async function isPageStatic({ ...@@ -871,29 +883,42 @@ export async function isPageStatic({
// build the static paths. The edge runtime doesn't support static // build the static paths. The edge runtime doesn't support static
// paths. // paths.
if (route.dynamicSegments.length > 0 && !pathIsEdgeRuntime) { if (route.dynamicSegments.length > 0 && !pathIsEdgeRuntime) {
;({ prerenderedRoutes, fallbackMode: prerenderFallbackMode } = let pathname = normalizeAppPath(page)
await buildAppStaticPaths({ if (pathname.endsWith('/route')) {
dir, pathname = pathname.slice(0, -'/route'.length)
page, }
route,
cacheComponents, if (
authInterrupts, routeModule.definition.kind === RouteKind.APP_ROUTE &&
useCacheTimeout, isStaticMetadataFile(pathname)
staticPageGenerationTimeout, ) {
segments, ;({ prerenderedRoutes, fallbackMode: prerenderFallbackMode } =
distDir, buildStaticMetadataStaticPaths(page))
requestHeaders: {}, } else {
isrFlushToDisk, ;({ prerenderedRoutes, fallbackMode: prerenderFallbackMode } =
cacheMaxMemorySize, await buildAppStaticPaths({
cacheHandler, dir,
cacheLifeProfiles, page,
ComponentMod, route,
nextConfigOutput, cacheComponents,
isRoutePPREnabled, authInterrupts,
buildId, useCacheTimeout,
deploymentId, staticPageGenerationTimeout,
rootParamKeys, segments,
})) distDir,
requestHeaders: {},
isrFlushToDisk,
cacheMaxMemorySize,
cacheHandler,
cacheLifeProfiles,
ComponentMod,
nextConfigOutput,
isRoutePPREnabled,
buildId,
deploymentId,
rootParamKeys,
}))
}
} }
} else { } else {
if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') { if (!Comp || !isValidElementType(Comp) || typeof Comp === 'string') {
......
import { import {
fillMetadataSegment, fillMetadataSegment,
fillStaticMetadataSegment, fillStaticMetadataSegment,
getStaticMetadataPrerenderPathname,
normalizeMetadataRoute, normalizeMetadataRoute,
} from './get-metadata-route' } from './get-metadata-route'
...@@ -33,6 +34,57 @@ describe('fillStaticMetadataSegment', () => { ...@@ -33,6 +34,57 @@ describe('fillStaticMetadataSegment', () => {
}) })
}) })
describe('getStaticMetadataPrerenderPathname', () => {
it('should return null for non-metadata routes', () => {
expect(getStaticMetadataPrerenderPathname('/dynamic/[id]/page')).toBeNull()
})
it('should normalize static metadata under dynamic segments', () => {
expect(
getStaticMetadataPrerenderPathname('/dynamic/[id]/apple-icon.png')
).toBe('/dynamic/-/apple-icon.png')
expect(
getStaticMetadataPrerenderPathname('/dynamic/[id]/sitemap.xml')
).toBe('/dynamic/-/sitemap.xml')
})
it('should preserve static metadata routes without dynamic segments', () => {
expect(getStaticMetadataPrerenderPathname('/static/apple-icon.png')).toBe(
'/static/apple-icon.png'
)
})
it('should collapse catchall segments to a single placeholder', () => {
expect(
getStaticMetadataPrerenderPathname('/[...slug]/apple-icon.png')
).toBe('/-/apple-icon.png')
})
it('should collapse optional catchall segments to a single placeholder', () => {
expect(
getStaticMetadataPrerenderPathname('/[[...slug]]/apple-icon.png')
).toBe('/-/apple-icon.png')
})
it('should replace each dynamic segment independently', () => {
expect(getStaticMetadataPrerenderPathname('/[a]/[b]/apple-icon.png')).toBe(
'/-/-/apple-icon.png'
)
})
it('should preserve literal segments between dynamic ones', () => {
expect(
getStaticMetadataPrerenderPathname('/[lang]/posts/[slug]/apple-icon.png')
).toBe('/-/posts/-/apple-icon.png')
})
it('should normalize mixed dynamic and catchall segments', () => {
expect(
getStaticMetadataPrerenderPathname('/[lang]/[...rest]/apple-icon.png')
).toBe('/-/-/apple-icon.png')
})
})
describe('fillMetadataSegment', () => { describe('fillMetadataSegment', () => {
it('should continue to interpolate dynamic metadata routes from params', () => { it('should continue to interpolate dynamic metadata routes from params', () => {
expect( expect(
......
...@@ -5,7 +5,9 @@ import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex' ...@@ -5,7 +5,9 @@ import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { PARAMETER_PATTERN } from '../../shared/lib/router/utils/get-dynamic-param' import { PARAMETER_PATTERN } from '../../shared/lib/router/utils/get-dynamic-param'
import { djb2Hash } from '../../shared/lib/hash' import { djb2Hash } from '../../shared/lib/hash'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { isDynamicRoute } from '../../shared/lib/router/utils'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { isMetadataRouteFile } from './is-metadata-route'
import { import {
isGroupSegment, isGroupSegment,
isParallelRouteSegment, isParallelRouteSegment,
...@@ -98,6 +100,32 @@ export function fillStaticMetadataSegment( ...@@ -98,6 +100,32 @@ export function fillStaticMetadataSegment(
) )
} }
/**
* Returns the pathname used when prerendering static metadata files. Dynamic
* segments are replaced with "-" placeholders so the file is exported once.
*/
export function getStaticMetadataPrerenderPathname(
pathname: string
): string | null {
const normalized = pathname.startsWith('/') ? pathname : `/${pathname}`
if (!isMetadataRouteFile(normalized, [], true)) {
return null
}
if (!isDynamicRoute(normalized)) {
return normalized
}
const lastSlash = normalized.lastIndexOf('/')
if (lastSlash === -1) {
return normalized
}
const segment = normalized.slice(0, lastSlash) || '/'
const lastSegment = normalized.slice(lastSlash + 1)
return fillStaticMetadataSegment(segment, lastSegment)
}
/** /**
* Fill the dynamic segment in the metadata route * Fill the dynamic segment in the metadata route
* *
......
import { nextTestSetup, isNextStart } from 'e2e-utils' import { nextTestSetup, isNextStart } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils' import {
getCommonMetadataHeadTags,
readFixtureBuffer,
readFixtureText,
} from './utils'
describe('metadata-files-static-output-dynamic-route', () => { describe('metadata-files-static-output-dynamic-route', () => {
if (process.env.__NEXT_CACHE_COMPONENTS) { if (process.env.__NEXT_CACHE_COMPONENTS) {
...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-dynamic-route', () => { ...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-dynamic-route', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
...@@ -121,11 +124,11 @@ describe('metadata-files-static-output-dynamic-route', () => { ...@@ -121,11 +124,11 @@ describe('metadata-files-static-output-dynamic-route', () => {
actualTwitterImage, actualTwitterImage,
actualSitemap, actualSitemap,
] = await Promise.all([ ] = await Promise.all([
next.readFileBuffer('app/dynamic/[id]/apple-icon.png'), readFixtureBuffer('app/dynamic/[id]/apple-icon.png'),
next.readFileBuffer('app/dynamic/[id]/icon.png'), readFixtureBuffer('app/dynamic/[id]/icon.png'),
next.readFileBuffer('app/dynamic/[id]/opengraph-image.png'), readFixtureBuffer('app/dynamic/[id]/opengraph-image.png'),
next.readFileBuffer('app/dynamic/[id]/twitter-image.png'), readFixtureBuffer('app/dynamic/[id]/twitter-image.png'),
next.readFile('app/dynamic/[id]/sitemap.xml'), readFixtureText('app/dynamic/[id]/sitemap.xml'),
]) ])
expect({ expect({
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils' import {
getCommonMetadataHeadTags,
readFixtureBuffer,
readFixtureText,
} from './utils'
describe('metadata-files-static-output-group-route', () => { describe('metadata-files-static-output-group-route', () => {
if (process.env.__NEXT_CACHE_COMPONENTS) {
// Cache Components build fails when metadata files are inside a dynamic route.
//
// Route "/dynamic/[id]": Next.js encountered uncached or runtime data in `generateMetadata()`.
//
// This prevents the page from being prerendered, leading to a slower user experience.
//
// Ways to fix this:
// - Use a static metadata export instead of `generateMetadata()`
// - Cache the metadata with `"use cache"` in `generateMetadata()`
// - Add a dynamic data access (e.g. `await connection()`) to the page to render it at request time
// - Set `export const instant = false` to allow a blocking route
//
// Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata
// Error occurred prerendering page "/dynamic/[id]". Read more: https://nextjs.org/docs/messages/prerender-error
// Export encountered an error on /dynamic/[id]/page: /dynamic/[id], exiting the build.
//
// TODO: Remove this skip when metadata files are supported in dynamic routes for Cache Components.
it.skip('should skip test for Cache Components', () => {})
return
}
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
...@@ -118,11 +99,11 @@ describe('metadata-files-static-output-group-route', () => { ...@@ -118,11 +99,11 @@ describe('metadata-files-static-output-group-route', () => {
actualTwitterImage, actualTwitterImage,
actualSitemap, actualSitemap,
] = await Promise.all([ ] = await Promise.all([
next.readFileBuffer('app/(group)/group/apple-icon.png'), readFixtureBuffer('app/(group)/group/apple-icon.png'),
next.readFileBuffer('app/(group)/group/icon.png'), readFixtureBuffer('app/(group)/group/icon.png'),
next.readFileBuffer('app/(group)/group/opengraph-image.png'), readFixtureBuffer('app/(group)/group/opengraph-image.png'),
next.readFileBuffer('app/(group)/group/twitter-image.png'), readFixtureBuffer('app/(group)/group/twitter-image.png'),
next.readFile('app/(group)/group/sitemap.xml'), readFixtureText('app/(group)/group/sitemap.xml'),
]) ])
expect({ expect({
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils' import {
getCommonMetadataHeadTags,
readFixtureBuffer,
readFixtureText,
} from './utils'
describe('metadata-files-static-output-intercepting-route', () => { describe('metadata-files-static-output-intercepting-route', () => {
if (process.env.__NEXT_CACHE_COMPONENTS) { if (process.env.__NEXT_CACHE_COMPONENTS) {
...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-intercepting-route', () => { ...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-intercepting-route', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
...@@ -124,15 +127,13 @@ describe('metadata-files-static-output-intercepting-route', () => { ...@@ -124,15 +127,13 @@ describe('metadata-files-static-output-intercepting-route', () => {
actualTwitterImage, actualTwitterImage,
actualSitemap, actualSitemap,
] = await Promise.all([ ] = await Promise.all([
next.readFileBuffer('app/intercepting/(..)intercept-me/apple-icon.png'), readFixtureBuffer('app/intercepting/(..)intercept-me/apple-icon.png'),
next.readFileBuffer('app/intercepting/(..)intercept-me/icon.png'), readFixtureBuffer('app/intercepting/(..)intercept-me/icon.png'),
next.readFileBuffer( readFixtureBuffer(
'app/intercepting/(..)intercept-me/opengraph-image.png' 'app/intercepting/(..)intercept-me/opengraph-image.png'
), ),
next.readFileBuffer( readFixtureBuffer('app/intercepting/(..)intercept-me/twitter-image.png'),
'app/intercepting/(..)intercept-me/twitter-image.png' readFixtureText('app/intercepting/(..)intercept-me/sitemap.xml'),
),
next.readFile('app/intercepting/(..)intercept-me/sitemap.xml'),
]) ])
expect({ expect({
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils' import {
getCommonMetadataHeadTags,
readFixtureBuffer,
readFixtureText,
} from './utils'
describe('metadata-files-static-output-parallel-route', () => { describe('metadata-files-static-output-parallel-route', () => {
if (process.env.__NEXT_CACHE_COMPONENTS) { if (process.env.__NEXT_CACHE_COMPONENTS) {
...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-parallel-route', () => { ...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-parallel-route', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
...@@ -118,11 +121,11 @@ describe('metadata-files-static-output-parallel-route', () => { ...@@ -118,11 +121,11 @@ describe('metadata-files-static-output-parallel-route', () => {
actualTwitterImage, actualTwitterImage,
actualSitemap, actualSitemap,
] = await Promise.all([ ] = await Promise.all([
next.readFileBuffer('app/parallel/@parallel/apple-icon.png'), readFixtureBuffer('app/parallel/@parallel/apple-icon.png'),
next.readFileBuffer('app/parallel/@parallel/icon.png'), readFixtureBuffer('app/parallel/@parallel/icon.png'),
next.readFileBuffer('app/parallel/@parallel/opengraph-image.png'), readFixtureBuffer('app/parallel/@parallel/opengraph-image.png'),
next.readFileBuffer('app/parallel/@parallel/twitter-image.png'), readFixtureBuffer('app/parallel/@parallel/twitter-image.png'),
next.readFile('app/parallel/@parallel/sitemap.xml'), readFixtureText('app/parallel/@parallel/sitemap.xml'),
]) ])
expect({ expect({
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils' import {
getCommonMetadataHeadTags,
readFixtureBuffer,
readFixtureText,
} from './utils'
describe('metadata-files-static-output-root-route', () => { describe('metadata-files-static-output-root-route', () => {
if (process.env.__NEXT_CACHE_COMPONENTS) { if (process.env.__NEXT_CACHE_COMPONENTS) {
...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-root-route', () => { ...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-root-route', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
...@@ -69,10 +72,10 @@ describe('metadata-files-static-output-root-route', () => { ...@@ -69,10 +72,10 @@ describe('metadata-files-static-output-root-route', () => {
// Compare response content with actual files // Compare response content with actual files
const [actualFavicon, actualManifest, actualRobots, actualSitemap] = const [actualFavicon, actualManifest, actualRobots, actualSitemap] =
await Promise.all([ await Promise.all([
next.readFileBuffer('app/favicon.ico'), readFixtureBuffer('app/favicon.ico'),
next.readFile('app/manifest.json'), readFixtureText('app/manifest.json'),
next.readFile('app/robots.txt'), readFixtureText('app/robots.txt'),
next.readFile('app/sitemap.xml'), readFixtureText('app/sitemap.xml'),
]) ])
expect({ expect({
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils' import {
getCommonMetadataHeadTags,
readFixtureBuffer,
readFixtureText,
} from './utils'
describe('metadata-files-static-output-static-route', () => { describe('metadata-files-static-output-static-route', () => {
if (process.env.__NEXT_CACHE_COMPONENTS) { if (process.env.__NEXT_CACHE_COMPONENTS) {
...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-static-route', () => { ...@@ -26,7 +30,6 @@ describe('metadata-files-static-output-static-route', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
...@@ -118,11 +121,11 @@ describe('metadata-files-static-output-static-route', () => { ...@@ -118,11 +121,11 @@ describe('metadata-files-static-output-static-route', () => {
actualTwitterImage, actualTwitterImage,
actualSitemap, actualSitemap,
] = await Promise.all([ ] = await Promise.all([
next.readFileBuffer('app/static/apple-icon.png'), readFixtureBuffer('app/static/apple-icon.png'),
next.readFileBuffer('app/static/icon.png'), readFixtureBuffer('app/static/icon.png'),
next.readFileBuffer('app/static/opengraph-image.png'), readFixtureBuffer('app/static/opengraph-image.png'),
next.readFileBuffer('app/static/twitter-image.png'), readFixtureBuffer('app/static/twitter-image.png'),
next.readFile('app/static/sitemap.xml'), readFixtureText('app/static/sitemap.xml'),
]) ])
expect({ expect({
......
// @ts-nocheck - On isolated test, this will be a type error. // @ts-nocheck - On isolated test, this will be a type error.
import { promises as fs } from 'fs'
import path from 'path'
import type { Playwright } from 'e2e-utils' import type { Playwright } from 'e2e-utils'
// Fixture files live in this directory (`test/e2e/app-dir/metadata-static-file`),
// so we read them from the repo on the test runner. Using `next.readFile` would
// hit the deployed filesystem, which is not available in deploy test mode.
export function readFixtureBuffer(relativePath: string) {
return fs.readFile(path.join(__dirname, relativePath))
}
export function readFixtureText(relativePath: string) {
return fs.readFile(path.join(__dirname, relativePath), 'utf8')
}
async function getMetadataLinks(browser: Playwright) { async function getMetadataLinks(browser: Playwright) {
const links = await browser.locator('link').evaluateAll((elements: any[]) => { const links = await browser.locator('link').evaluateAll((elements: any[]) => {
return elements return elements
......
...@@ -552,4 +552,10 @@ export class NextDeployInstance extends NextInstance { ...@@ -552,4 +552,10 @@ export class NextDeployInstance extends NextInstance {
): Promise<void> { ): Promise<void> {
throw new Error('renameFile is not available in deploy test mode') throw new Error('renameFile is not available in deploy test mode')
} }
public async readFileBuffer(filename: string): Promise<Buffer> {
throw new Error('readFileBuffer is not available in deploy test mode')
}
public async writeFileBuffer(filename: string, data: Buffer): Promise<void> {
throw new Error('writeFileBuffer is not available in deploy test mode')
}
} }
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