Unverified Commit bfc3849b authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update generateStaticParams handling with fetch cache (#46906)

This ensures we leverage the fetch cache when calling
`generateStaticParams` and also ensures paths with
`generateStaticParams` without `dynamicParams = false` don't error when
only partial params are provided.

x-ref: [slack
thread](https://vercel.slack.com/archives/C035J346QQL/p1678149362238089)
parent 9a1798b6
...@@ -1463,6 +1463,11 @@ export default async function build( ...@@ -1463,6 +1463,11 @@ export default async function build(
edgeInfo, edgeInfo,
pageType, pageType,
hasServerComponents: !!appDir, hasServerComponents: !!appDir,
incrementalCacheHandlerPath:
config.experimental.incrementalCacheHandlerPath,
isrFlushToDisk: config.experimental.isrFlushToDisk,
maxMemoryCacheSize:
config.experimental.isrMemoryCacheSize,
}) })
} }
) )
......
...@@ -55,6 +55,10 @@ import { ...@@ -55,6 +55,10 @@ import {
overrideBuiltInReactPackages, overrideBuiltInReactPackages,
} from './webpack/require-hook' } from './webpack/require-hook'
import { isClientReference } from './is-client-reference' import { isClientReference } from './is-client-reference'
import { StaticGenerationAsyncStorageWrapper } from '../server/async-storage/static-generation-async-storage-wrapper'
import { IncrementalCache } from '../server/lib/incremental-cache'
import { patchFetch } from '../server/lib/patch-fetch'
import { nodeFs } from '../server/lib/node-fs-methods'
loadRequireHook() loadRequireHook()
if (process.env.NEXT_PREBUNDLED_REACT) { if (process.env.NEXT_PREBUNDLED_REACT) {
...@@ -998,6 +1002,15 @@ export async function buildStaticPaths({ ...@@ -998,6 +1002,15 @@ export async function buildStaticPaths({
(repeat && !Array.isArray(paramValue)) || (repeat && !Array.isArray(paramValue)) ||
(!repeat && typeof paramValue !== 'string') (!repeat && typeof paramValue !== 'string')
) { ) {
// If from appDir and not all params were provided from
// generateStaticParams we can just filter this entry out
// as it's meant to be generated at runtime
if (appDir) {
builtPage = ''
encodedBuiltPage = ''
return
}
throw new Error( throw new Error(
`A required parameter (${validParamKey}) was not provided as ${ `A required parameter (${validParamKey}) was not provided as ${
repeat ? 'an array' : 'a string' repeat ? 'an array' : 'a string'
...@@ -1031,6 +1044,10 @@ export async function buildStaticPaths({ ...@@ -1031,6 +1044,10 @@ export async function buildStaticPaths({
.replace(/(?!^)\/$/, '') .replace(/(?!^)\/$/, '')
}) })
if (!builtPage && !encodedBuiltPage) {
return
}
if (entry.locale && !locales?.includes(entry.locale)) { if (entry.locale && !locales?.includes(entry.locale)) {
throw new Error( throw new Error(
`Invalid locale returned from getStaticPaths for ${page}, the locale ${entry.locale} is not specified in ${configFileName}` `Invalid locale returned from getStaticPaths for ${page}, the locale ${entry.locale} is not specified in ${configFileName}`
...@@ -1143,89 +1160,155 @@ export const collectGenerateParams = async ( ...@@ -1143,89 +1160,155 @@ export const collectGenerateParams = async (
export async function buildAppStaticPaths({ export async function buildAppStaticPaths({
page, page,
distDir,
configFileName, configFileName,
generateParams, generateParams,
isrFlushToDisk,
incrementalCacheHandlerPath,
requestHeaders,
maxMemoryCacheSize,
fetchCacheKeyPrefix,
staticGenerationAsyncStorage,
serverHooks,
}: { }: {
page: string page: string
configFileName: string configFileName: string
generateParams: GenerateParams generateParams: GenerateParams
incrementalCacheHandlerPath?: string
distDir: string
isrFlushToDisk?: boolean
fetchCacheKeyPrefix?: string
maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders']
staticGenerationAsyncStorage: Parameters<
typeof patchFetch
>[0]['staticGenerationAsyncStorage']
serverHooks: Parameters<typeof patchFetch>[0]['serverHooks']
}) { }) {
const pageEntry = generateParams[generateParams.length - 1] patchFetch({
staticGenerationAsyncStorage,
// if the page has legacy getStaticPaths we call it like normal serverHooks,
if (typeof pageEntry?.getStaticPaths === 'function') { })
return buildStaticPaths({ let CacheHandler: any
page,
configFileName, if (incrementalCacheHandlerPath) {
getStaticPaths: pageEntry.getStaticPaths, CacheHandler = require(incrementalCacheHandlerPath)
}) CacheHandler = CacheHandler.default || CacheHandler
} else { }
// if generateStaticParams is being used we iterate over them
// collecting them from each level const incrementalCache = new IncrementalCache({
type Params = Array<Record<string, string | string[]>> fs: nodeFs,
let hadGenerateParams = false dev: true,
appDir: true,
const buildParams = async ( flushToDisk: isrFlushToDisk,
paramsItems: Params = [{}], serverDistDir: path.join(distDir, 'server'),
idx = 0 fetchCacheKeyPrefix,
): Promise<Params> => { maxMemoryCacheSize,
const curGenerate = generateParams[idx] getPrerenderManifest: () => ({
version: -1 as any, // letting us know this doesn't conform to spec
if (idx === generateParams.length) { routes: {},
return paramsItems dynamicRoutes: {},
} notFoundRoutes: [],
if ( preview: null as any, // `preview` is special case read in next-dev-server
typeof curGenerate.generateStaticParams !== 'function' && }),
idx < generateParams.length CurCacheHandler: CacheHandler,
) { requestHeaders,
return buildParams(paramsItems, idx + 1) })
}
hadGenerateParams = true const wrapper = new StaticGenerationAsyncStorageWrapper()
return wrapper.wrap(
staticGenerationAsyncStorage,
{
pathname: page,
renderOpts: {
incrementalCache,
supportsDynamicHTML: true,
isRevalidate: false,
isBot: false,
},
},
async () => {
const pageEntry = generateParams[generateParams.length - 1]
// if the page has legacy getStaticPaths we call it like normal
if (typeof pageEntry?.getStaticPaths === 'function') {
return buildStaticPaths({
page,
configFileName,
getStaticPaths: pageEntry.getStaticPaths,
})
} else {
// if generateStaticParams is being used we iterate over them
// collecting them from each level
type Params = Array<Record<string, string | string[]>>
let hadGenerateParams = false
const buildParams = async (
paramsItems: Params = [{}],
idx = 0
): Promise<Params> => {
const curGenerate = generateParams[idx]
if (idx === generateParams.length) {
return paramsItems
}
if (
typeof curGenerate.generateStaticParams !== 'function' &&
idx < generateParams.length
) {
return buildParams(paramsItems, idx + 1)
}
hadGenerateParams = true
const newParams = []
const newParams = [] for (const params of paramsItems) {
const result = await curGenerate.generateStaticParams({ params })
// TODO: validate the result is valid here or wait for
// buildStaticPaths to validate?
for (const item of result) {
newParams.push({ ...params, ...item })
}
}
for (const params of paramsItems) { if (idx < generateParams.length) {
const result = await curGenerate.generateStaticParams({ params }) return buildParams(newParams, idx + 1)
// TODO: validate the result is valid here or wait for }
// buildStaticPaths to validate? return newParams
for (const item of result) {
newParams.push({ ...params, ...item })
} }
} const builtParams = await buildParams()
const fallback = !generateParams.some(
// TODO: dynamic params should be allowed
// to be granular per segment but we need
// additional information stored/leveraged in
// the prerender-manifest to allow this behavior
(generate) => generate.config?.dynamicParams === false
)
if (idx < generateParams.length) { if (!hadGenerateParams) {
return buildParams(newParams, idx + 1) return {
} paths: undefined,
return newParams fallback:
} process.env.NODE_ENV === 'production' && isDynamicRoute(page)
const builtParams = await buildParams() ? true
const fallback = !generateParams.some( : undefined,
// TODO: check complementary configs that can impact encodedPaths: undefined,
// dynamicParams behavior }
(generate) => generate.config?.dynamicParams === false }
)
if (!hadGenerateParams) { return buildStaticPaths({
return { staticPathsResult: {
paths: undefined, fallback,
fallback: paths: builtParams.map((params) => ({ params })),
process.env.NODE_ENV === 'production' && isDynamicRoute(page) },
? true page,
: undefined, configFileName,
encodedPaths: undefined, appDir: true,
})
} }
} }
)
return buildStaticPaths({
staticPathsResult: {
fallback,
paths: builtParams.map((params) => ({ params })),
},
page,
configFileName,
appDir: true,
})
}
} }
export async function isPageStatic({ export async function isPageStatic({
...@@ -1243,6 +1326,9 @@ export async function isPageStatic({ ...@@ -1243,6 +1326,9 @@ export async function isPageStatic({
pageType, pageType,
hasServerComponents, hasServerComponents,
originalAppPath, originalAppPath,
isrFlushToDisk,
maxMemoryCacheSize,
incrementalCacheHandlerPath,
}: { }: {
page: string page: string
distDir: string distDir: string
...@@ -1258,6 +1344,9 @@ export async function isPageStatic({ ...@@ -1258,6 +1344,9 @@ export async function isPageStatic({
pageRuntime?: ServerRuntime pageRuntime?: ServerRuntime
hasServerComponents?: boolean hasServerComponents?: boolean
originalAppPath?: string originalAppPath?: string
isrFlushToDisk?: boolean
maxMemoryCacheSize?: number
incrementalCacheHandlerPath?: string
}): Promise<{ }): Promise<{
isStatic?: boolean isStatic?: boolean
isAmpOnly?: boolean isAmpOnly?: boolean
...@@ -1335,6 +1424,9 @@ export async function isPageStatic({ ...@@ -1335,6 +1424,9 @@ export async function isPageStatic({
isClientComponent = isClientReference(componentsResult.ComponentMod) isClientComponent = isClientReference(componentsResult.ComponentMod)
const tree = componentsResult.ComponentMod.tree const tree = componentsResult.ComponentMod.tree
const handlers = componentsResult.ComponentMod.handlers const handlers = componentsResult.ComponentMod.handlers
const staticGenerationAsyncStorage =
componentsResult.ComponentMod.staticGenerationAsyncStorage
const serverHooks = componentsResult.ComponentMod.serverHooks
const generateParams: GenerateParams = handlers const generateParams: GenerateParams = handlers
? [ ? [
...@@ -1399,8 +1491,15 @@ export async function isPageStatic({ ...@@ -1399,8 +1491,15 @@ export async function isPageStatic({
encodedPaths: encodedPrerenderRoutes, encodedPaths: encodedPrerenderRoutes,
} = await buildAppStaticPaths({ } = await buildAppStaticPaths({
page, page,
serverHooks,
staticGenerationAsyncStorage,
configFileName, configFileName,
generateParams, generateParams,
distDir,
requestHeaders: {},
isrFlushToDisk,
maxMemoryCacheSize,
incrementalCacheHandlerPath,
})) }))
} }
} else { } else {
......
...@@ -49,7 +49,8 @@ export class Worker { ...@@ -49,7 +49,8 @@ export class Worker {
_child: ChildProcess _child: ChildProcess
}[]) { }[]) {
worker._child.on('exit', (code, signal) => { worker._child.on('exit', (code, signal) => {
if (code || signal) { // log unexpected exit if .end() wasn't called
if ((code || signal) && this._worker) {
console.error( console.error(
`Static worker unexpectedly exited with code: ${code} and signal: ${signal}` `Static worker unexpectedly exited with code: ${code} and signal: ${signal}`
) )
......
...@@ -1096,6 +1096,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1096,6 +1096,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
pathname, pathname,
}: { }: {
pathname: string pathname: string
requestHeaders: import('./lib/incremental-cache').IncrementalCache['requestHeaders']
originalAppPath?: string originalAppPath?: string
}): Promise<{ }): Promise<{
staticPaths?: string[] staticPaths?: string[]
...@@ -1162,6 +1163,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1162,6 +1163,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const pathsResult = await this.getStaticPaths({ const pathsResult = await this.getStaticPaths({
pathname, pathname,
originalAppPath: components.pathname, originalAppPath: components.pathname,
requestHeaders: req.headers,
}) })
staticPaths = pathsResult.staticPaths staticPaths = pathsResult.staticPaths
...@@ -1607,7 +1609,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1607,7 +1609,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (!staticPaths) { if (!staticPaths) {
;({ staticPaths, fallbackMode } = hasStaticPaths ;({ staticPaths, fallbackMode } = hasStaticPaths
? await this.getStaticPaths({ pathname }) ? await this.getStaticPaths({
pathname,
requestHeaders: req.headers,
})
: { staticPaths: undefined, fallbackMode: false }) : { staticPaths: undefined, fallbackMode: false })
} }
......
...@@ -97,6 +97,7 @@ import { DefaultFileReader } from '../future/route-matcher-providers/dev/helpers ...@@ -97,6 +97,7 @@ import { DefaultFileReader } from '../future/route-matcher-providers/dev/helpers
import { NextBuildContext } from '../../build/build-context' import { NextBuildContext } from '../../build/build-context'
import { logAppDirError } from './log-app-dir-error' import { logAppDirError } from './log-app-dir-error'
import { createClientRouterFilter } from '../../lib/create-client-router-filter' import { createClientRouterFilter } from '../../lib/create-client-router-filter'
import { IncrementalCache } from '../lib/incremental-cache'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: FunctionComponent let ReactDevOverlayImpl: FunctionComponent
...@@ -1511,9 +1512,11 @@ export default class DevServer extends Server { ...@@ -1511,9 +1512,11 @@ export default class DevServer extends Server {
protected async getStaticPaths({ protected async getStaticPaths({
pathname, pathname,
originalAppPath, originalAppPath,
requestHeaders,
}: { }: {
pathname: string pathname: string
originalAppPath?: string originalAppPath?: string
requestHeaders: IncrementalCache['requestHeaders']
}): Promise<{ }): Promise<{
staticPaths?: string[] staticPaths?: string[]
fallbackMode?: false | 'static' | 'blocking' fallbackMode?: false | 'static' | 'blocking'
...@@ -1545,6 +1548,12 @@ export default class DevServer extends Server { ...@@ -1545,6 +1548,12 @@ export default class DevServer extends Server {
defaultLocale, defaultLocale,
originalAppPath, originalAppPath,
isAppPath: !!originalAppPath, isAppPath: !!originalAppPath,
requestHeaders,
incrementalCacheHandlerPath:
this.nextConfig.experimental.incrementalCacheHandlerPath,
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize,
}) })
return pathsResult return pathsResult
} }
......
...@@ -13,6 +13,9 @@ import { ...@@ -13,6 +13,9 @@ import {
loadRequireHook, loadRequireHook,
overrideBuiltInReactPackages, overrideBuiltInReactPackages,
} from '../../build/webpack/require-hook' } from '../../build/webpack/require-hook'
import { IncrementalCache } from '../lib/incremental-cache'
import * as serverHooks from '../../client/components/hooks-server-context'
import { staticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage'
type RuntimeConfig = any type RuntimeConfig = any
...@@ -40,6 +43,11 @@ export async function loadStaticPaths({ ...@@ -40,6 +43,11 @@ export async function loadStaticPaths({
defaultLocale, defaultLocale,
isAppPath, isAppPath,
originalAppPath, originalAppPath,
isrFlushToDisk,
fetchCacheKeyPrefix,
maxMemoryCacheSize,
requestHeaders,
incrementalCacheHandlerPath,
}: { }: {
distDir: string distDir: string
pathname: string pathname: string
...@@ -50,6 +58,11 @@ export async function loadStaticPaths({ ...@@ -50,6 +58,11 @@ export async function loadStaticPaths({
defaultLocale?: string defaultLocale?: string
isAppPath?: boolean isAppPath?: boolean
originalAppPath?: string originalAppPath?: string
isrFlushToDisk?: boolean
fetchCacheKeyPrefix?: string
maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders']
incrementalCacheHandlerPath?: string
}): Promise<{ }): Promise<{
paths?: string[] paths?: string[]
encodedPaths?: string[] encodedPaths?: string[]
...@@ -104,6 +117,14 @@ export async function loadStaticPaths({ ...@@ -104,6 +117,14 @@ export async function loadStaticPaths({
page: pathname, page: pathname,
generateParams, generateParams,
configFileName: config.configFileName, configFileName: config.configFileName,
distDir,
requestHeaders,
incrementalCacheHandlerPath,
serverHooks,
staticGenerationAsyncStorage,
isrFlushToDisk,
fetchCacheKeyPrefix,
maxMemoryCacheSize,
}) })
} }
......
import _fs from 'fs'
import { CacheFs } from '../../shared/lib/utils'
export const nodeFs: CacheFs = {
readFile: (f) => _fs.promises.readFile(f, 'utf8'),
readFileSync: (f) => _fs.readFileSync(f, 'utf8'),
writeFile: (f, d) => _fs.promises.writeFile(f, d, 'utf8'),
mkdir: (dir) => _fs.promises.mkdir(dir, { recursive: true }),
stat: (f) => _fs.promises.stat(f),
}
...@@ -99,6 +99,7 @@ import { MatchOptions } from './future/route-matcher-managers/route-matcher-mana ...@@ -99,6 +99,7 @@ import { MatchOptions } from './future/route-matcher-managers/route-matcher-mana
import { INSTRUMENTATION_HOOK_FILENAME } from '../lib/constants' import { INSTRUMENTATION_HOOK_FILENAME } from '../lib/constants'
import { getTracer } from './lib/trace/tracer' import { getTracer } from './lib/trace/tracer'
import { NextNodeServerSpan } from './lib/trace/constants' import { NextNodeServerSpan } from './lib/trace/constants'
import { nodeFs } from './lib/node-fs-methods'
export * from './base-server' export * from './base-server'
...@@ -1336,13 +1337,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1336,13 +1337,7 @@ export default class NextNodeServer extends BaseServer {
} }
protected getCacheFilesystem(): CacheFs { protected getCacheFilesystem(): CacheFs {
return { return nodeFs
readFile: (f) => fs.promises.readFile(f, 'utf8'),
readFileSync: (f) => fs.readFileSync(f, 'utf8'),
writeFile: (f, d) => fs.promises.writeFile(f, d, 'utf8'),
mkdir: (dir) => fs.promises.mkdir(dir, { recursive: true }),
stat: (f) => fs.promises.stat(f),
}
} }
private normalizeReq( private normalizeReq(
......
...@@ -22,13 +22,30 @@ createNextDescribe( ...@@ -22,13 +22,30 @@ createNextDescribe(
}, },
}, },
({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => { ({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => {
let prerenderManifest
beforeAll(async () => {
if (isNextStart) {
prerenderManifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
)
}
})
if (isNextStart) { if (isNextStart) {
it('should output HTML/RSC files for static paths', async () => { it('should output HTML/RSC files for static paths', async () => {
const files = ( const files = (
await glob('**/*', { await glob('**/*', {
cwd: join(next.testDir, '.next/server/app'), cwd: join(next.testDir, '.next/server/app'),
}) })
).filter((file) => file.match(/.*\.(js|html|rsc)$/)) )
.filter((file) => file.match(/.*\.(js|html|rsc)$/))
.map((file) => {
return file.replace(
/partial-gen-params-no-additional-([\w]{1,})\/([\w]{1,})\/([\d]{1,})/,
'partial-gen-params-no-additional-$1/$2/RAND'
)
})
expect(files).toEqual([ expect(files).toEqual([
'(new)/custom/page.js', '(new)/custom/page.js',
...@@ -74,6 +91,33 @@ createNextDescribe( ...@@ -74,6 +91,33 @@ createNextDescribe(
'hooks/use-search-params/with-suspense.html', 'hooks/use-search-params/with-suspense.html',
'hooks/use-search-params/with-suspense.rsc', 'hooks/use-search-params/with-suspense.rsc',
'hooks/use-search-params/with-suspense/page.js', 'hooks/use-search-params/with-suspense/page.js',
'partial-gen-params-no-additional-lang/[lang]/[slug]/page.js',
'partial-gen-params-no-additional-lang/en/RAND.html',
'partial-gen-params-no-additional-lang/en/RAND.rsc',
'partial-gen-params-no-additional-lang/en/first.html',
'partial-gen-params-no-additional-lang/en/first.rsc',
'partial-gen-params-no-additional-lang/en/second.html',
'partial-gen-params-no-additional-lang/en/second.rsc',
'partial-gen-params-no-additional-lang/fr/RAND.html',
'partial-gen-params-no-additional-lang/fr/RAND.rsc',
'partial-gen-params-no-additional-lang/fr/first.html',
'partial-gen-params-no-additional-lang/fr/first.rsc',
'partial-gen-params-no-additional-lang/fr/second.html',
'partial-gen-params-no-additional-lang/fr/second.rsc',
'partial-gen-params-no-additional-slug/[lang]/[slug]/page.js',
'partial-gen-params-no-additional-slug/en/RAND.html',
'partial-gen-params-no-additional-slug/en/RAND.rsc',
'partial-gen-params-no-additional-slug/en/first.html',
'partial-gen-params-no-additional-slug/en/first.rsc',
'partial-gen-params-no-additional-slug/en/second.html',
'partial-gen-params-no-additional-slug/en/second.rsc',
'partial-gen-params-no-additional-slug/fr/RAND.html',
'partial-gen-params-no-additional-slug/fr/RAND.rsc',
'partial-gen-params-no-additional-slug/fr/first.html',
'partial-gen-params-no-additional-slug/fr/first.rsc',
'partial-gen-params-no-additional-slug/fr/second.html',
'partial-gen-params-no-additional-slug/fr/second.rsc',
'partial-gen-params/[lang]/[slug]/page.js',
'ssg-preview.html', 'ssg-preview.html',
'ssg-preview.rsc', 'ssg-preview.rsc',
'ssg-preview/[[...route]]/page.js', 'ssg-preview/[[...route]]/page.js',
...@@ -112,12 +156,10 @@ createNextDescribe( ...@@ -112,12 +156,10 @@ createNextDescribe(
}) })
it('should have correct prerender-manifest entries', async () => { it('should have correct prerender-manifest entries', async () => {
const manifest = JSON.parse( const curManifest = JSON.parse(JSON.stringify(prerenderManifest))
await next.readFile('.next/prerender-manifest.json')
)
Object.keys(manifest.dynamicRoutes).forEach((key) => { for (const key of Object.keys(curManifest.dynamicRoutes)) {
const item = manifest.dynamicRoutes[key] const item = curManifest.dynamicRoutes[key]
if (item.dataRouteRegex) { if (item.dataRouteRegex) {
item.dataRouteRegex = normalizeRegEx(item.dataRouteRegex) item.dataRouteRegex = normalizeRegEx(item.dataRouteRegex)
...@@ -125,10 +167,25 @@ createNextDescribe( ...@@ -125,10 +167,25 @@ createNextDescribe(
if (item.routeRegex) { if (item.routeRegex) {
item.routeRegex = normalizeRegEx(item.routeRegex) item.routeRegex = normalizeRegEx(item.routeRegex)
} }
}) }
for (const key of Object.keys(curManifest.routes)) {
const newKey = key.replace(
/partial-gen-params-no-additional-([\w]{1,})\/([\w]{1,})\/([\d]{1,})/,
'partial-gen-params-no-additional-$1/$2/RAND'
)
if (newKey !== key) {
const route = curManifest.routes[key]
delete curManifest.routes[key]
curManifest.routes[newKey] = {
...route,
dataRoute: `${newKey}.rsc`,
}
}
}
expect(manifest.version).toBe(4) expect(curManifest.version).toBe(4)
expect(manifest.routes).toEqual({ expect(curManifest.routes).toEqual({
'/blog/tim': { '/blog/tim': {
initialRevalidateSeconds: 10, initialRevalidateSeconds: 10,
srcRoute: '/blog/[author]', srcRoute: '/blog/[author]',
...@@ -184,6 +241,66 @@ createNextDescribe( ...@@ -184,6 +241,66 @@ createNextDescribe(
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
srcRoute: '/hooks/use-search-params/with-suspense', srcRoute: '/hooks/use-search-params/with-suspense',
}, },
'/partial-gen-params-no-additional-lang/en/RAND': {
dataRoute: '/partial-gen-params-no-additional-lang/en/RAND.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-lang/[lang]/[slug]',
},
'/partial-gen-params-no-additional-lang/en/first': {
dataRoute: '/partial-gen-params-no-additional-lang/en/first.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-lang/[lang]/[slug]',
},
'/partial-gen-params-no-additional-lang/en/second': {
dataRoute: '/partial-gen-params-no-additional-lang/en/second.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-lang/[lang]/[slug]',
},
'/partial-gen-params-no-additional-lang/fr/RAND': {
dataRoute: '/partial-gen-params-no-additional-lang/fr/RAND.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-lang/[lang]/[slug]',
},
'/partial-gen-params-no-additional-lang/fr/first': {
dataRoute: '/partial-gen-params-no-additional-lang/fr/first.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-lang/[lang]/[slug]',
},
'/partial-gen-params-no-additional-lang/fr/second': {
dataRoute: '/partial-gen-params-no-additional-lang/fr/second.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-lang/[lang]/[slug]',
},
'/partial-gen-params-no-additional-slug/en/RAND': {
dataRoute: '/partial-gen-params-no-additional-slug/en/RAND.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]',
},
'/partial-gen-params-no-additional-slug/en/first': {
dataRoute: '/partial-gen-params-no-additional-slug/en/first.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]',
},
'/partial-gen-params-no-additional-slug/en/second': {
dataRoute: '/partial-gen-params-no-additional-slug/en/second.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]',
},
'/partial-gen-params-no-additional-slug/fr/RAND': {
dataRoute: '/partial-gen-params-no-additional-slug/fr/RAND.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]',
},
'/partial-gen-params-no-additional-slug/fr/first': {
dataRoute: '/partial-gen-params-no-additional-slug/fr/first.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]',
},
'/partial-gen-params-no-additional-slug/fr/second': {
dataRoute: '/partial-gen-params-no-additional-slug/fr/second.rsc',
initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]',
},
'/force-static/first': { '/force-static/first': {
dataRoute: '/force-static/first.rsc', dataRoute: '/force-static/first.rsc',
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
...@@ -240,7 +357,7 @@ createNextDescribe( ...@@ -240,7 +357,7 @@ createNextDescribe(
srcRoute: '/variable-revalidate/revalidate-3', srcRoute: '/variable-revalidate/revalidate-3',
}, },
}) })
expect(manifest.dynamicRoutes).toEqual({ expect(curManifest.dynamicRoutes).toEqual({
'/blog/[author]/[slug]': { '/blog/[author]/[slug]': {
routeRegex: normalizeRegEx('^/blog/([^/]+?)/([^/]+?)(?:/)?$'), routeRegex: normalizeRegEx('^/blog/([^/]+?)/([^/]+?)(?:/)?$'),
dataRoute: '/blog/[author]/[slug].rsc', dataRoute: '/blog/[author]/[slug].rsc',
...@@ -255,9 +372,13 @@ createNextDescribe( ...@@ -255,9 +372,13 @@ createNextDescribe(
}, },
'/dynamic-error/[id]': { '/dynamic-error/[id]': {
dataRoute: '/dynamic-error/[id].rsc', dataRoute: '/dynamic-error/[id].rsc',
dataRouteRegex: '^\\/dynamic\\-error\\/([^\\/]+?)\\.rsc$', dataRouteRegex: normalizeRegEx(
'^\\/dynamic\\-error\\/([^\\/]+?)\\.rsc$'
),
fallback: null, fallback: null,
routeRegex: '^\\/dynamic\\-error\\/([^\\/]+?)(?:\\/)?$', routeRegex: normalizeRegEx(
'^\\/dynamic\\-error\\/([^\\/]+?)(?:\\/)?$'
),
}, },
'/gen-params-dynamic-revalidate/[slug]': { '/gen-params-dynamic-revalidate/[slug]': {
dataRoute: '/gen-params-dynamic-revalidate/[slug].rsc', dataRoute: '/gen-params-dynamic-revalidate/[slug].rsc',
...@@ -279,6 +400,38 @@ createNextDescribe( ...@@ -279,6 +400,38 @@ createNextDescribe(
'^\\/hooks\\/use\\-pathname\\/([^\\/]+?)(?:\\/)?$' '^\\/hooks\\/use\\-pathname\\/([^\\/]+?)(?:\\/)?$'
), ),
}, },
'/partial-gen-params-no-additional-lang/[lang]/[slug]': {
dataRoute:
'/partial-gen-params-no-additional-lang/[lang]/[slug].rsc',
dataRouteRegex: normalizeRegEx(
'^\\/partial\\-gen\\-params\\-no\\-additional\\-lang\\/([^\\/]+?)\\/([^\\/]+?)\\.rsc$'
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/partial\\-gen\\-params\\-no\\-additional\\-lang\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$'
),
},
'/partial-gen-params-no-additional-slug/[lang]/[slug]': {
dataRoute:
'/partial-gen-params-no-additional-slug/[lang]/[slug].rsc',
dataRouteRegex: normalizeRegEx(
'^\\/partial\\-gen\\-params\\-no\\-additional\\-slug\\/([^\\/]+?)\\/([^\\/]+?)\\.rsc$'
),
fallback: false,
routeRegex: normalizeRegEx(
'^\\/partial\\-gen\\-params\\-no\\-additional\\-slug\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$'
),
},
'/partial-gen-params/[lang]/[slug]': {
dataRoute: '/partial-gen-params/[lang]/[slug].rsc',
dataRouteRegex: normalizeRegEx(
'^\\/partial\\-gen\\-params\\/([^\\/]+?)\\/([^\\/]+?)\\.rsc$'
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/partial\\-gen\\-params\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$'
),
},
'/force-static/[slug]': { '/force-static/[slug]': {
dataRoute: '/force-static/[slug].rsc', dataRoute: '/force-static/[slug].rsc',
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
...@@ -388,6 +541,166 @@ createNextDescribe( ...@@ -388,6 +541,166 @@ createNextDescribe(
}) })
} }
it('should handle partial-gen-params with default dynamicParams correctly', async () => {
const res = await next.fetch('/partial-gen-params/en/first')
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
const params = JSON.parse($('#params').text())
expect(params).toEqual({ lang: 'en', slug: 'first' })
})
it('should handle partial-gen-params with layout dynamicParams = false correctly', async () => {
for (const { path, status, params } of [
// these checks don't work with custom memory only
// cache handler
...(process.env.CUSTOM_CACHE_HANDLER
? []
: [
{
path: '/partial-gen-params-no-additional-lang/en/first',
status: 200,
params: { lang: 'en', slug: 'first' },
},
]),
{
path: '/partial-gen-params-no-additional-lang/de/first',
status: 404,
params: {},
},
{
path: '/partial-gen-params-no-additional-lang/en/non-existent',
status: 404,
params: {},
},
]) {
const res = await next.fetch(path)
expect(res.status).toBe(status)
const html = await res.text()
const $ = cheerio.load(html)
const curParams = JSON.parse($('#params').text() || '{}')
expect(curParams).toEqual(params)
}
})
it('should handle partial-gen-params with page dynamicParams = false correctly', async () => {
for (const { path, status, params } of [
// these checks don't work with custom memory only
// cache handler
...(process.env.CUSTOM_CACHE_HANDLER
? []
: [
{
path: '/partial-gen-params-no-additional-slug/en/first',
status: 200,
params: { lang: 'en', slug: 'first' },
},
]),
{
path: '/partial-gen-params-no-additional-slug/de/first',
status: 404,
params: {},
},
{
path: '/partial-gen-params-no-additional-slug/en/non-existent',
status: 404,
params: {},
},
]) {
const res = await next.fetch(path)
expect(res.status).toBe(status)
const html = await res.text()
const $ = cheerio.load(html)
const curParams = JSON.parse($('#params').text() || '{}')
expect(curParams).toEqual(params)
}
})
// fetch cache in generateStaticParams needs fs for persistence
// so doesn't behave as expected with custom in memory only
// cache handler
if (!process.env.CUSTOM_CACHE_HANDLER) {
it('should honor fetch cache in generateStaticParams', async () => {
const initialRes = await next.fetch(
`/partial-gen-params-no-additional-lang/en/first`
)
expect(initialRes.status).toBe(200)
// we can't read prerender-manifest from deployment
if (isNextDeploy) return
let langFetchSlug
let slugFetchSlug
if (isDev) {
await check(() => {
const matches = stripAnsi(next.cliOutput).match(
/partial-gen-params fetch ([\d]{1,})/
)
if (matches[1]) {
langFetchSlug = matches[1]
slugFetchSlug = langFetchSlug
}
return langFetchSlug ? 'success' : next.cliOutput
}, 'success')
} else {
// the fetch cache can potentially be a miss since
// the generateStaticParams are executed parallel
// in separate workers so parse value from
// prerender-manifest
const routes = Object.keys(prerenderManifest.routes)
for (const route of routes) {
const langSlug = route.match(
/partial-gen-params-no-additional-lang\/en\/([\d]{1,})/
)?.[1]
if (langSlug) {
langFetchSlug = langSlug
}
const slugSlug = route.match(
/partial-gen-params-no-additional-slug\/en\/([\d]{1,})/
)?.[1]
if (slugSlug) {
slugFetchSlug = slugSlug
}
}
}
require('console').log({ langFetchSlug, slugFetchSlug })
for (const { pathname, slug } of [
{
pathname: '/partial-gen-params-no-additional-lang/en',
slug: langFetchSlug,
},
{
pathname: '/partial-gen-params-no-additional-slug/en',
slug: slugFetchSlug,
},
]) {
const res = await next.fetch(`${pathname}/${slug}`)
expect(res.status).toBe(200)
expect(
JSON.parse(
cheerio
.load(await res.text())('#params')
.text()
)
).toEqual({ lang: 'en', slug })
}
})
}
it('should honor fetch cache correctly', async () => { it('should honor fetch cache correctly', async () => {
await check(async () => { await check(async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
......
export const dynamicParams = true
export async function generateStaticParams() {
const res = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?staticGen'
)
const data = await res.text()
const fetchSlug = Math.round(Number(data) * 100)
console.log('partial-gen-params fetch', fetchSlug)
return [
{
slug: 'first',
},
{
slug: 'second',
},
{
slug: fetchSlug + '',
},
]
}
export default function Page({ params }) {
return (
<>
<p id="page">/partial-gen-params/[lang]/[slug]</p>
<p id="params">{JSON.stringify(params)}</p>
</>
)
}
export const dynamicParams = false
export function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'fr' }]
}
export default function Layout({ children }) {
return <>{children}</>
}
export const dynamicParams = false
export async function generateStaticParams() {
const res = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?staticGen'
)
const data = await res.text()
const fetchSlug = Math.round(Number(data) * 100)
console.log('partial-gen-params fetch', fetchSlug)
return [
{
slug: 'first',
},
{
slug: 'second',
},
{
slug: fetchSlug + '',
},
]
}
export default function Page({ params }) {
return (
<>
<p id="page">/partial-gen-params/[lang]/[slug]</p>
<p id="params">{JSON.stringify(params)}</p>
</>
)
}
export const dynamicParams = true
export function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'fr' }]
}
export default function Layout({ children }) {
return <>{children}</>
}
export default function Page({ params }) {
return (
<>
<p id="page">/partial-gen-params/[lang]/[slug]</p>
<p id="params">{JSON.stringify(params)}</p>
</>
)
}
export function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'fr' }]
}
export default function Layout({ children }) {
return <>{children}</>
}
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