Unverified Commit 3db87862 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix dynamic sitemap detection (#60356)

### What

Fix bad detection of dynamic route of sitemap metadata route, the swc
AST check should process when the text are detected. But prevuious if
there's text with `generateSitemap` such as comment but not the actual
export it will fail.

### How
Add both checks on metadata loader side and detection helper side

* Only call `generateSitemaps` helper when the export existed
* Fix the helper detection logic (major part of this PR)

Fixes #59698
Closes #60344
Closes NEXT-2007
parent 75e13819
......@@ -459,12 +459,12 @@ export async function isDynamicMetadataRoute(
pageFilePath: string
): Promise<boolean> {
const fileContent = (await tryToReadFile(pageFilePath, true)) || ''
if (!/generateImageMetadata|generateSitemaps/.test(fileContent)) return false
const swcAST = await parseModule(pageFilePath, fileContent)
const exportsInfo = checkExports(swcAST, pageFilePath)
return !exportsInfo.generateImageMetadata || !exportsInfo.generateSitemaps
if (/generateImageMetadata|generateSitemaps/.test(fileContent)) {
const swcAST = await parseModule(pageFilePath, fileContent)
const exportsInfo = checkExports(swcAST, pageFilePath)
return !!(exportsInfo.generateImageMetadata || exportsInfo.generateSitemaps)
}
return false
}
/**
......
......@@ -23,9 +23,46 @@ interface Options {
basePath: string
}
export async function getNamedExports(
resourcePath: string,
context: webpack.LoaderContext<any>
): Promise<string[]> {
const mod = await new Promise<webpack.NormalModule>((res, rej) => {
context.loadModule(
resourcePath,
(err: null | Error, _source: any, _sourceMap: any, module: any) => {
if (err) {
return rej(err)
}
res(module)
}
)
})
const exportNames =
mod.dependencies
?.filter((dep) => {
return (
[
'HarmonyExportImportedSpecifierDependency',
'HarmonyExportSpecifierDependency',
].includes(dep.constructor.name) &&
'name' in dep &&
dep.name !== 'default'
)
})
.map((dep: any) => {
return dep.name
}) || []
return exportNames
}
// [NOTE] For turbopack
// refer loader_tree's write_static|dynamic_metadata for corresponding features
async function nextMetadataImageLoader(this: any, content: Buffer) {
async function nextMetadataImageLoader(
this: webpack.LoaderContext<Options>,
content: Buffer
) {
const options: Options = this.getOptions()
const { type, segment, pageExtensions, basePath } = options
const { resourcePath, rootContext: context } = this
......@@ -57,33 +94,9 @@ async function nextMetadataImageLoader(this: any, content: Buffer) {
const pathnamePrefix = normalizePathSep(path.join(basePath, segment))
if (isDynamicResource) {
const mod = await new Promise<webpack.NormalModule>((res, rej) => {
this.loadModule(
resourcePath,
(err: null | Error, _source: any, _sourceMap: any, module: any) => {
if (err) {
return rej(err)
}
res(module)
}
)
})
const exportedFieldsExcludingDefault =
mod.dependencies
?.filter((dep) => {
return (
[
'HarmonyExportImportedSpecifierDependency',
'HarmonyExportSpecifierDependency',
].includes(dep.constructor.name) &&
'name' in dep &&
dep.name !== 'default'
)
})
.map((dep: any) => {
return dep.name
}) || []
const exportedFieldsExcludingDefault = (
await getNamedExports(resourcePath, this)
).filter((name) => name !== 'default')
// re-export and spread as `exportedImageData` to avoid non-exported error
return `\
......
......@@ -2,6 +2,7 @@ import type webpack from 'webpack'
import fs from 'fs'
import path from 'path'
import { imageExtMimeTypeMap } from '../../../lib/mime-type'
import { getNamedExports } from './next-metadata-image-loader'
function errorOnBadHandler(resourcePath: string) {
return `
......@@ -143,16 +144,23 @@ export async function GET(_, ctx) {
`
}
function getDynamicSiteMapRouteCode(resourcePath: string, page: string) {
async function getDynamicSiteMapRouteCode(
resourcePath: string,
page: string,
loaderContext: webpack.LoaderContext<any>
) {
let staticGenerationCode = ''
const exportNames = await getNamedExports(resourcePath, loaderContext)
const hasGenerateSiteMaps = exportNames.includes('generateSitemaps')
if (
process.env.NODE_ENV === 'production' &&
hasGenerateSiteMaps &&
page.includes('[__metadata_id__]')
) {
staticGenerationCode = `\
export async function generateStaticParams() {
const sitemaps = await generateSitemaps()
const sitemaps = generateSitemaps ? await generateSitemaps() : []
const params = []
for (const item of sitemaps) {
......@@ -230,7 +238,7 @@ const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLo
if (fileBaseName === 'robots' || fileBaseName === 'manifest') {
code = getDynamicTextRouteCode(resourcePath)
} else if (fileBaseName === 'sitemap') {
code = getDynamicSiteMapRouteCode(resourcePath, page)
code = await getDynamicSiteMapRouteCode(resourcePath, page, this)
} else {
code = getDynamicImageRouteCode(resourcePath)
}
......
......@@ -2,6 +2,7 @@ import { ImageResponse } from 'next/og'
export const alt = 'Open Graph'
/* without generateImageMetadata */
export default function og() {
return new ImageResponse(
(
......
import 'server-only'
import { MetadataRoute } from 'next'
/* without generateSitemaps */
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
......
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