Unverified Commit 023be2e8 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

metadata: use fixed segment in dynamic routes with static metadata files (#88113)

parent be6fcb25
...@@ -251,7 +251,7 @@ impl AppPageLoaderTreeBuilder { ...@@ -251,7 +251,7 @@ impl AppPageLoaderTreeBuilder {
let metadata_route = &*get_metadata_route_name(item.clone().into()).await?; let metadata_route = &*get_metadata_route_name(item.clone().into()).await?;
writeln!( writeln!(
self.loader_tree_code, self.loader_tree_code,
"{s} url: fillMetadataSegment({}, await props.params, {}) + \ "{s} url: fillMetadataSegment({}, await props.params, {}, true) + \
`?${{{identifier}.src.split(\"/\").splice(-1)[0]}}`,", `?${{{identifier}.src.split(\"/\").splice(-1)[0]}}`,",
StringifyJs(&pathname_prefix), StringifyJs(&pathname_prefix),
StringifyJs(metadata_route), StringifyJs(metadata_route),
......
...@@ -74,7 +74,7 @@ async fn dynamic_image_metadata_with_generator_source( ...@@ -74,7 +74,7 @@ async fn dynamic_image_metadata_with_generator_source(
export default async function (props) {{ export default async function (props) {{
const {{ __metadata_id__: _, ...params }} = await props.params const {{ __metadata_id__: _, ...params }} = await props.params
const imageUrl = fillMetadataSegment({pathname_prefix}, params, {page_segment}) const imageUrl = fillMetadataSegment({pathname_prefix}, params, {page_segment}, false)
const {{ generateImageMetadata }} = imageModule const {{ generateImageMetadata }} = imageModule
...@@ -148,7 +148,7 @@ async fn dynamic_image_metadata_without_generator_source( ...@@ -148,7 +148,7 @@ async fn dynamic_image_metadata_without_generator_source(
export default async function (props) {{ export default async function (props) {{
const {{ __metadata_id__: _, ...params }} = await props.params const {{ __metadata_id__: _, ...params }} = await props.params
const imageUrl = fillMetadataSegment({pathname_prefix}, params, {page_segment}) const imageUrl = fillMetadataSegment({pathname_prefix}, params, {page_segment}, false)
function getImageMetadata(imageMetadata, idParam) {{ function getImageMetadata(imageMetadata, idParam) {{
const data = {{ const data = {{
......
...@@ -85,6 +85,41 @@ import type { TurbopackResult } from './swc/types' ...@@ -85,6 +85,41 @@ import type { TurbopackResult } from './swc/types'
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 { parseAppRoute } from '../shared/lib/router/routes/app' import { parseAppRoute } from '../shared/lib/router/routes/app'
import { fillMetadataSegment } from '../lib/metadata/get-metadata-route'
import { STATIC_METADATA_IMAGES } from '../lib/metadata/is-metadata-route'
// 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
* dynamic routes, this normalizes the path to use "-" placeholder.
* e.g., /dynamic/[id]/icon.png -> /dynamic/-/icon.png
*/
function getTreeViewDisplayPath(pagePath: string): string {
// Check if the path contains dynamic segments
if (!isDynamicRoute(pagePath)) {
return pagePath
}
// Check if the filename is a static metadata image
const lastSlash = pagePath.lastIndexOf('/')
const filename = pagePath.slice(lastSlash + 1)
const dotIndex = filename.lastIndexOf('.')
const baseName = dotIndex > 0 ? filename.slice(0, dotIndex) : filename
// Check against known static metadata image filenames (e.g., icon, apple-icon, opengraph-image)
if (!staticMetadataImageFilenames.has(baseName)) {
return pagePath
}
// Transform using fillMetadataSegment with isStatic=true
const segment = pagePath.slice(0, lastSlash)
const lastSegment = filename
return fillMetadataSegment(segment, {}, lastSegment, true)
}
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
...@@ -416,10 +451,12 @@ export async function printTreeView( ...@@ -416,10 +451,12 @@ export async function printTreeView(
symbol = 'ƒ' symbol = 'ƒ'
} }
const displayPath = getTreeViewDisplayPath(item)
if (hasGSPAndRevalidateZero.has(item)) { if (hasGSPAndRevalidateZero.has(item)) {
usedSymbols.add('ƒ') usedSymbols.add('ƒ')
messages.push([ messages.push([
`${border} ƒ ${item}${ `${border} ƒ ${displayPath}${
totalDuration > MIN_DURATION totalDuration > MIN_DURATION
? ` (${getPrettyDuration(totalDuration)})` ? ` (${getPrettyDuration(totalDuration)})`
: '' : ''
...@@ -436,7 +473,7 @@ export async function printTreeView( ...@@ -436,7 +473,7 @@ export async function printTreeView(
usedSymbols.add(symbol) usedSymbols.add(symbol)
messages.push([ messages.push([
`${border} ${symbol} ${item}${ `${border} ${symbol} ${displayPath}${
totalDuration > MIN_DURATION totalDuration > MIN_DURATION
? ` (${getPrettyDuration(totalDuration)})` ? ` (${getPrettyDuration(totalDuration)})`
: '' : ''
......
...@@ -91,7 +91,7 @@ async function nextMetadataImageLoader( ...@@ -91,7 +91,7 @@ async function nextMetadataImageLoader(
function getImageMetadata(imageMetadata, idParam, resolvedParams) { function getImageMetadata(imageMetadata, idParam, resolvedParams) {
const imageUrl = fillMetadataSegment(${JSON.stringify( const imageUrl = fillMetadataSegment(${JSON.stringify(
pathnamePrefix pathnamePrefix
)}, resolvedParams, ${JSON.stringify(pageSegment)}) )}, resolvedParams, ${JSON.stringify(pageSegment)}, false)
const data = { const data = {
alt: imageMetadata.alt, alt: imageMetadata.alt,
type: imageMetadata.contentType || 'image/png', type: imageMetadata.contentType || 'image/png',
...@@ -175,7 +175,7 @@ async function nextMetadataImageLoader( ...@@ -175,7 +175,7 @@ async function nextMetadataImageLoader(
const imageData = ${JSON.stringify(imageData)} const imageData = ${JSON.stringify(imageData)}
const imageUrl = fillMetadataSegment(${JSON.stringify( const imageUrl = fillMetadataSegment(${JSON.stringify(
pathnamePrefix pathnamePrefix
)}, await props.params, ${JSON.stringify(pageSegment)}) )}, await props.params, ${JSON.stringify(pageSegment)}, true)
return [{ return [{
...imageData, ...imageData,
......
...@@ -52,19 +52,39 @@ function getMetadataRouteSuffix(page: string) { ...@@ -52,19 +52,39 @@ function getMetadataRouteSuffix(page: string) {
* Fill the dynamic segment in the metadata route * Fill the dynamic segment in the metadata route
* *
* Example: * Example:
* fillMetadataSegment('/a/[slug]', { params: { slug: 'b' } }, 'open-graph') -> '/a/b/open-graph' * fillMetadataSegment('/a/[slug]', { params: { slug: 'b' } }, 'open-graph', false) -> '/a/b/open-graph'
*
* When isStatic is true, all dynamic segments are filled with "-" placeholder
* since static metadata files have consistent responses regardless of params.
* Example:
* fillMetadataSegment('/a/[slug]', {}, 'icon.png', true) -> '/a/-/icon.png'
* *
*/ */
export function fillMetadataSegment( export function fillMetadataSegment(
segment: string, segment: string,
params: any, params: any,
lastSegment: string lastSegment: string,
isStatic: boolean
) { ) {
const pathname = normalizeAppPath(segment) const pathname = normalizeAppPath(segment)
const routeRegex = getNamedRouteRegex(pathname, { const routeRegex = getNamedRouteRegex(pathname, {
prefixRouteKeys: false, prefixRouteKeys: false,
}) })
const route = interpolateDynamicPath(pathname, params, routeRegex)
// For static metadata files, fill all dynamic segments with "-" placeholder
const routeParams = isStatic
? Object.keys(routeRegex.groups).reduce(
(acc, key) => {
const { repeat } = routeRegex.groups[key]
// Use array for catch-all segments, string for regular segments
acc[key] = repeat ? ['-'] : '-'
return acc
},
{} as Record<string, string | string[]>
)
: params
const route = interpolateDynamicPath(pathname, routeParams, routeRegex)
const { name, ext } = path.parse(lastSegment) const { name, ext } = path.parse(lastSegment)
const pagePath = path.posix.join(segment, name) const pagePath = path.posix.join(segment, name)
const suffix = getMetadataRouteSuffix(pagePath) const suffix = getMetadataRouteSuffix(pagePath)
......
...@@ -65,7 +65,10 @@ import { ...@@ -65,7 +65,10 @@ import {
isMetadataRouteFile, isMetadataRouteFile,
isStaticMetadataFile, isStaticMetadataFile,
} from '../../../lib/metadata/is-metadata-route' } from '../../../lib/metadata/is-metadata-route'
import { normalizeMetadataPageToRoute } from '../../../lib/metadata/get-metadata-route' import {
fillMetadataSegment,
normalizeMetadataPageToRoute,
} from '../../../lib/metadata/get-metadata-route'
import { JsConfigPathsPlugin } from '../../../build/webpack/plugins/jsconfig-paths-plugin' import { JsConfigPathsPlugin } from '../../../build/webpack/plugins/jsconfig-paths-plugin'
import { store as consoleStore } from '../../../build/output/store' import { store as consoleStore } from '../../../build/output/store'
import { import {
...@@ -680,7 +683,16 @@ async function startWatcher( ...@@ -680,7 +683,16 @@ async function startWatcher(
if (useFileSystemPublicRoutes) { if (useFileSystemPublicRoutes) {
// Static metadata files will be served from filesystem. // Static metadata files will be served from filesystem.
if (appDir && isStaticMetadataFile(fileName.replace(appDir, ''))) { if (appDir && isStaticMetadataFile(fileName.replace(appDir, ''))) {
staticMetadataFiles.set(pageName, fileName) // Use "-" placeholder for dynamic segments since static files have consistent content
const segment = path.posix.dirname(pageName)
const lastSegment = path.posix.basename(pageName)
const normalizedPath = fillMetadataSegment(
segment,
{},
lastSegment,
true
)
staticMetadataFiles.set(normalizedPath, fileName)
} else { } else {
appFiles.add(pageName) appFiles.add(pageName)
} }
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup, isNextStart } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils' import { getCommonMetadataHeadTags } from './utils'
describe('metadata-files-static-output-dynamic-route', () => { describe('metadata-files-static-output-dynamic-route', () => {
...@@ -25,19 +25,21 @@ describe('metadata-files-static-output-dynamic-route', () => { ...@@ -25,19 +25,21 @@ describe('metadata-files-static-output-dynamic-route', () => {
return return
} }
it('should have correct link tags for dynamic page', async () => { it('should have correct link tags for dynamic page with static placeholder', async () => {
const browser = await next.browser('/dynamic/123') const browser = await next.browser('/dynamic/123')
// Static metadata files under dynamic routes use "-" as placeholder
// since the file content is the same regardless of params
expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(` expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`
{ {
"links": [ "links": [
{ {
"href": "/dynamic/123/apple-icon.png", "href": "/dynamic/-/apple-icon.png",
"rel": "apple-touch-icon", "rel": "apple-touch-icon",
"type": "image/png", "type": "image/png",
}, },
{ {
"href": "/dynamic/123/icon.png", "href": "/dynamic/-/icon.png",
"rel": "icon", "rel": "icon",
"type": "image/png", "type": "image/png",
}, },
...@@ -87,7 +89,8 @@ describe('metadata-files-static-output-dynamic-route', () => { ...@@ -87,7 +89,8 @@ describe('metadata-files-static-output-dynamic-route', () => {
`) `)
}) })
it('should serve static files when requested to its route for dynamic page', async () => { it('should serve static files when requested with placeholder for dynamic page', async () => {
// Static metadata files use "-" as placeholder for dynamic segments
const [ const [
appleIconRes, appleIconRes,
iconRes, iconRes,
...@@ -95,11 +98,11 @@ describe('metadata-files-static-output-dynamic-route', () => { ...@@ -95,11 +98,11 @@ describe('metadata-files-static-output-dynamic-route', () => {
twitterImageRes, twitterImageRes,
sitemapRes, sitemapRes,
] = await Promise.all([ ] = await Promise.all([
next.fetch('/dynamic/123/apple-icon.png'), next.fetch('/dynamic/-/apple-icon.png'),
next.fetch('/dynamic/123/icon.png'), next.fetch('/dynamic/-/icon.png'),
next.fetch('/dynamic/123/opengraph-image.png'), next.fetch('/dynamic/-/opengraph-image.png'),
next.fetch('/dynamic/123/twitter-image.png'), next.fetch('/dynamic/-/twitter-image.png'),
next.fetch('/dynamic/123/sitemap.xml'), next.fetch('/dynamic/-/sitemap.xml'),
]) ])
// Compare response content with actual files // Compare response content with actual files
...@@ -144,4 +147,18 @@ describe('metadata-files-static-output-dynamic-route', () => { ...@@ -144,4 +147,18 @@ describe('metadata-files-static-output-dynamic-route', () => {
sitemap: actualSitemap, sitemap: actualSitemap,
}) })
}) })
if (isNextStart) {
it('should display static metadata files with "-" placeholder in build output', () => {
// Build output should show normalized paths with "-" for dynamic segments
expect(next.cliOutput).toContain('/dynamic/-/apple-icon.png')
expect(next.cliOutput).toContain('/dynamic/-/icon.png')
expect(next.cliOutput).toContain('/dynamic/-/opengraph-image.png')
expect(next.cliOutput).toContain('/dynamic/-/twitter-image.png')
// Should NOT show the dynamic segment pattern in output for static files
expect(next.cliOutput).not.toMatch(/\/dynamic\/\[id\]\/icon\.png/)
expect(next.cliOutput).not.toMatch(/\/dynamic\/\[id\]\/apple-icon\.png/)
})
}
}) })
...@@ -597,8 +597,10 @@ describe('app dir - metadata', () => { ...@@ -597,8 +597,10 @@ describe('app dir - metadata', () => {
const $dynamic = await next.render$('/icons/static/dynamic-routes/123') const $dynamic = await next.render$('/icons/static/dynamic-routes/123')
const $dynamicIcon = $dynamic('link[rel="icon"][type!="image/x-icon"]') const $dynamicIcon = $dynamic('link[rel="icon"][type!="image/x-icon"]')
const dynamicIconHref = $dynamicIcon.attr('href') const dynamicIconHref = $dynamicIcon.attr('href')
// Static icon files under dynamic routes use "-" as placeholder
// since the file content is the same regardless of params
expect(dynamicIconHref).toMatch( expect(dynamicIconHref).toMatch(
/\/icons\/static\/dynamic-routes\/123\/icon/ /\/icons\/static\/dynamic-routes\/-\/icon/
) )
const dynamicIconRes = await next.fetch(dynamicIconHref) const dynamicIconRes = await next.fetch(dynamicIconHref)
expect(dynamicIconRes.status).toBe(200) expect(dynamicIconRes.status).toBe(200)
......
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