Unverified Commit 3fa9f31c authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: updates for resuming postponed in minimal mode (#57375)

Co-authored-by: 's avatarJimmy Lai <11064311+feedthejim@users.noreply.github.com>
parent b8b1ec24
This diff is collapsed.
...@@ -1284,6 +1284,7 @@ export async function buildAppStaticPaths({ ...@@ -1284,6 +1284,7 @@ export async function buildAppStaticPaths({
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
requestHeaders, requestHeaders,
minimalMode: ciEnvironment.hasNextSupport, minimalMode: ciEnvironment.hasNextSupport,
experimental: { ppr },
}) })
return StaticGenerationAsyncStorageWrapper.wrap( return StaticGenerationAsyncStorageWrapper.wrap(
...@@ -1296,7 +1297,7 @@ export async function buildAppStaticPaths({ ...@@ -1296,7 +1297,7 @@ export async function buildAppStaticPaths({
supportsDynamicHTML: true, supportsDynamicHTML: true,
isRevalidate: false, isRevalidate: false,
isBot: false, isBot: false,
ppr, experimental: { ppr },
}, },
}, },
async () => { async () => {
......
export const RSC = 'RSC' as const export const RSC_HEADER = 'RSC' as const
export const ACTION = 'Next-Action' as const export const ACTION = 'Next-Action' as const
export const NEXT_ROUTER_STATE_TREE = 'Next-Router-State-Tree' as const export const NEXT_ROUTER_STATE_TREE = 'Next-Router-State-Tree' as const
export const NEXT_ROUTER_PREFETCH = 'Next-Router-Prefetch' as const export const NEXT_ROUTER_PREFETCH_HEADER = 'Next-Router-Prefetch' as const
export const NEXT_URL = 'Next-Url' as const export const NEXT_URL = 'Next-Url' as const
export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
export const RSC_VARY_HEADER = export const RSC_VARY_HEADER =
`${RSC}, ${NEXT_ROUTER_STATE_TREE}, ${NEXT_ROUTER_PREFETCH}, ${NEXT_URL}` as const `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_URL}` as const
export const FLIGHT_PARAMETERS = [ export const FLIGHT_PARAMETERS = [
[RSC], [RSC_HEADER],
[NEXT_ROUTER_STATE_TREE], [NEXT_ROUTER_STATE_TREE],
[NEXT_ROUTER_PREFETCH], [NEXT_ROUTER_PREFETCH_HEADER],
] as const ] as const
export const NEXT_RSC_UNION_QUERY = '_rsc' as const export const NEXT_RSC_UNION_QUERY = '_rsc' as const
...@@ -17,11 +17,11 @@ import type { ...@@ -17,11 +17,11 @@ import type {
NextFlightResponse, NextFlightResponse,
} from '../../../server/app-render/types' } from '../../../server/app-render/types'
import { import {
NEXT_ROUTER_PREFETCH, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE, NEXT_ROUTER_STATE_TREE,
NEXT_RSC_UNION_QUERY, NEXT_RSC_UNION_QUERY,
NEXT_URL, NEXT_URL,
RSC, RSC_HEADER,
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
} from '../app-router-headers' } from '../app-router-headers'
import { urlToUrlWithoutFlightMarker } from '../app-router' import { urlToUrlWithoutFlightMarker } from '../app-router'
...@@ -51,13 +51,13 @@ export async function fetchServerResponse( ...@@ -51,13 +51,13 @@ export async function fetchServerResponse(
prefetchKind?: PrefetchKind prefetchKind?: PrefetchKind
): Promise<FetchServerResponseResult> { ): Promise<FetchServerResponseResult> {
const headers: { const headers: {
[RSC]: '1' [RSC_HEADER]: '1'
[NEXT_ROUTER_STATE_TREE]: string [NEXT_ROUTER_STATE_TREE]: string
[NEXT_URL]?: string [NEXT_URL]?: string
[NEXT_ROUTER_PREFETCH]?: '1' [NEXT_ROUTER_PREFETCH_HEADER]?: '1'
} = { } = {
// Enable flight response // Enable flight response
[RSC]: '1', [RSC_HEADER]: '1',
// Provide the current router state // Provide the current router state
[NEXT_ROUTER_STATE_TREE]: encodeURIComponent( [NEXT_ROUTER_STATE_TREE]: encodeURIComponent(
JSON.stringify(flightRouterState) JSON.stringify(flightRouterState)
...@@ -71,7 +71,7 @@ export async function fetchServerResponse( ...@@ -71,7 +71,7 @@ export async function fetchServerResponse(
* - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully * - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully
*/ */
if (prefetchKind === PrefetchKind.AUTO) { if (prefetchKind === PrefetchKind.AUTO) {
headers[NEXT_ROUTER_PREFETCH] = '1' headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
} }
if (nextUrl) { if (nextUrl) {
...@@ -80,7 +80,7 @@ export async function fetchServerResponse( ...@@ -80,7 +80,7 @@ export async function fetchServerResponse(
const uniqueCacheQuery = hexHash( const uniqueCacheQuery = hexHash(
[ [
headers[NEXT_ROUTER_PREFETCH] || '0', headers[NEXT_ROUTER_PREFETCH_HEADER] || '0',
headers[NEXT_ROUTER_STATE_TREE], headers[NEXT_ROUTER_STATE_TREE],
headers[NEXT_URL], headers[NEXT_URL],
].join(',') ].join(',')
......
...@@ -11,7 +11,8 @@ export function createIncrementalCache( ...@@ -11,7 +11,8 @@ export function createIncrementalCache(
fetchCacheKeyPrefix: string | undefined, fetchCacheKeyPrefix: string | undefined,
distDir: string, distDir: string,
dir: string, dir: string,
enabledDirectories: NextEnabledDirectories enabledDirectories: NextEnabledDirectories,
experimental: { ppr: boolean }
) { ) {
// Custom cache handler overrides. // Custom cache handler overrides.
let CacheHandler: any let CacheHandler: any
...@@ -46,6 +47,7 @@ export function createIncrementalCache( ...@@ -46,6 +47,7 @@ export function createIncrementalCache(
serverDistDir: path.join(distDir, 'server'), serverDistDir: path.join(distDir, 'server'),
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
minimalMode: hasNextSupport, minimalMode: hasNextSupport,
experimental,
}) })
;(globalThis as any).__incrementalCache = incrementalCache ;(globalThis as any).__incrementalCache = incrementalCache
......
...@@ -19,7 +19,7 @@ import { formatAmpMessages } from '../build/output/index' ...@@ -19,7 +19,7 @@ import { formatAmpMessages } from '../build/output/index'
import type { AmpPageStatus } from '../build/output/index' import type { AmpPageStatus } from '../build/output/index'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import createSpinner from '../build/spinner' import createSpinner from '../build/spinner'
import { SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants' import { RSC_SUFFIX, SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants'
import { recursiveCopy } from '../lib/recursive-copy' import { recursiveCopy } from '../lib/recursive-copy'
import { import {
BUILD_ID_FILE, BUILD_ID_FILE,
...@@ -504,7 +504,7 @@ export async function exportAppImpl( ...@@ -504,7 +504,7 @@ export async function exportAppImpl(
: {}), : {}),
strictNextHead: !!nextConfig.experimental.strictNextHead, strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId, deploymentId: nextConfig.experimental.deploymentId,
ppr: nextConfig.experimental.ppr === true, experimental: { ppr: nextConfig.experimental.ppr === true },
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
...@@ -776,6 +776,12 @@ export async function exportAppImpl( ...@@ -776,6 +776,12 @@ export async function exportAppImpl(
const endWorkerPromise = workers.end() const endWorkerPromise = workers.end()
// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message
throw new Error('Invariant: PPR cannot be enabled in export mode')
}
// copy prerendered routes to outDir // copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) { if (!options.buildExport && prerenderManifest) {
await Promise.all( await Promise.all(
...@@ -838,7 +844,7 @@ export async function exportAppImpl( ...@@ -838,7 +844,7 @@ export async function exportAppImpl(
await fs.mkdir(dirname(jsonDest), { recursive: true }) await fs.mkdir(dirname(jsonDest), { recursive: true })
const htmlSrc = `${orig}.html` const htmlSrc = `${orig}.html`
const jsonSrc = `${orig}${isAppPath ? '.rsc' : '.json'}` const jsonSrc = `${orig}${isAppPath ? RSC_SUFFIX : '.json'}`
await fs.copyFile(htmlSrc, htmlDest) await fs.copyFile(htmlSrc, htmlDest)
await fs.copyFile(jsonSrc, jsonDest) await fs.copyFile(jsonSrc, jsonDest)
......
...@@ -9,12 +9,16 @@ import type { ...@@ -9,12 +9,16 @@ import type {
MockedResponse, MockedResponse,
} from '../../server/lib/mock-request' } from '../../server/lib/mock-request'
import { import {
RSC, RSC_HEADER,
NEXT_URL, NEXT_URL,
NEXT_ROUTER_PREFETCH, NEXT_ROUTER_PREFETCH_HEADER,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error' import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { NEXT_CACHE_TAGS_HEADER } from '../../lib/constants' import {
NEXT_CACHE_TAGS_HEADER,
RSC_PREFETCH_SUFFIX,
RSC_SUFFIX,
} from '../../lib/constants'
import { hasNextSupport } from '../../telemetry/ci-info' import { hasNextSupport } from '../../telemetry/ci-info'
import { lazyRenderAppPage } from '../../server/future/route-modules/app-page/module.render' import { lazyRenderAppPage } from '../../server/future/route-modules/app-page/module.render'
...@@ -25,7 +29,7 @@ export const enum ExportedAppPageFiles { ...@@ -25,7 +29,7 @@ export const enum ExportedAppPageFiles {
POSTPONED = 'POSTPONED', POSTPONED = 'POSTPONED',
} }
export async function generatePrefetchRsc( async function generatePrefetchRsc(
req: MockedRequest, req: MockedRequest,
path: string, path: string,
res: MockedResponse, res: MockedResponse,
...@@ -34,9 +38,17 @@ export async function generatePrefetchRsc( ...@@ -34,9 +38,17 @@ export async function generatePrefetchRsc(
renderOpts: RenderOpts, renderOpts: RenderOpts,
fileWriter: FileWriter fileWriter: FileWriter
) { ) {
req.headers[RSC.toLowerCase()] = '1' // When we're in PPR, the RSC payload is emitted as the prefetch payload, so
// attempting to generate a prefetch RSC is an error.
if (renderOpts.experimental.ppr) {
throw new Error(
'Invariant: explicit prefetch RSC cannot be generated with PPR enabled'
)
}
req.headers[RSC_HEADER.toLowerCase()] = '1'
req.headers[NEXT_URL.toLowerCase()] = path req.headers[NEXT_URL.toLowerCase()] = path
req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] = '1' req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
renderOpts.supportsDynamicHTML = true renderOpts.supportsDynamicHTML = true
renderOpts.isPrefetch = true renderOpts.isPrefetch = true
...@@ -56,7 +68,7 @@ export async function generatePrefetchRsc( ...@@ -56,7 +68,7 @@ export async function generatePrefetchRsc(
await fileWriter( await fileWriter(
ExportedAppPageFiles.FLIGHT, ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, '.prefetch.rsc'), htmlFilepath.replace(/\.html$/, RSC_PREFETCH_SUFFIX),
prefetchRscData prefetchRscData
) )
} }
...@@ -102,11 +114,18 @@ export async function exportAppPage( ...@@ -102,11 +114,18 @@ export async function exportAppPage(
query, query,
renderOpts renderOpts
) )
const html = result.toUnchunkedString() const html = result.toUnchunkedString()
const {
metadata: { pageData, revalidate = false, postponed, fetchTags },
} = result
const { metadata } = result const { metadata } = result
const flightData = metadata.pageData
const revalidate = metadata.revalidate ?? false // Ensure we don't postpone without having PPR enabled.
const postponed = metadata.postponed if (postponed && !renderOpts.experimental.ppr) {
throw new Error('Invariant: page postponed without PPR being enabled')
}
if (revalidate === 0) { if (revalidate === 0) {
if (isDynamicError) { if (isDynamicError) {
...@@ -145,10 +164,29 @@ export async function exportAppPage( ...@@ -145,10 +164,29 @@ export async function exportAppPage(
return { revalidate: 0 } return { revalidate: 0 }
} }
// If PPR is enabled, we want to emit a prefetch rsc file for the page
// instead of the standard rsc. This is because the standard rsc will
// contain the dynamic data.
else if (renderOpts.experimental.ppr) {
// If PPR is enabled, we should emit the flight data as the prefetch
// payload.
await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, RSC_PREFETCH_SUFFIX),
pageData
)
} else {
// Writing the RSC payload to a file if we don't have PPR enabled.
await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, RSC_SUFFIX),
pageData
)
}
let headers: OutgoingHttpHeaders | undefined let headers: OutgoingHttpHeaders | undefined
if (metadata.fetchTags) { if (fetchTags) {
headers = { [NEXT_CACHE_TAGS_HEADER]: metadata.fetchTags } headers = { [NEXT_CACHE_TAGS_HEADER]: fetchTags }
} }
// Writing static HTML to a file. // Writing static HTML to a file.
...@@ -172,13 +210,6 @@ export async function exportAppPage( ...@@ -172,13 +210,6 @@ export async function exportAppPage(
JSON.stringify(meta, null, 2) JSON.stringify(meta, null, 2)
) )
// Writing the RSC payload to a file.
await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, '.rsc'),
flightData
)
return { return {
// Only include the metadata if the environment has next support. // Only include the metadata if the environment has next support.
metadata: hasNextSupport ? meta : undefined, metadata: hasNextSupport ? meta : undefined,
......
...@@ -60,7 +60,7 @@ export async function exportAppRoute( ...@@ -60,7 +60,7 @@ export async function exportAppRoute(
notFoundRoutes: [], notFoundRoutes: [],
}, },
renderOpts: { renderOpts: {
ppr: false, experimental: { ppr: false },
originalPathname: page, originalPathname: page,
nextExport: true, nextExport: true,
supportsDynamicHTML: false, supportsDynamicHTML: false,
......
...@@ -224,7 +224,9 @@ async function exportPageImpl( ...@@ -224,7 +224,9 @@ async function exportPageImpl(
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
distDir, distDir,
dir, dir,
enabledDirectories enabledDirectories,
// PPR is not available for Pages.
{ ppr: false }
) )
: undefined : undefined
......
...@@ -8,6 +8,9 @@ export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER = ...@@ -8,6 +8,9 @@ export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
export const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed' export const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed'
export const RSC_PREFETCH_SUFFIX = '.prefetch.rsc'
export const RSC_SUFFIX = '.rsc'
export const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags' export const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags'
export const NEXT_CACHE_SOFT_TAGS_HEADER = 'x-next-cache-soft-tags' export const NEXT_CACHE_SOFT_TAGS_HEADER = 'x-next-cache-soft-tags'
export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags' export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'
......
...@@ -9,7 +9,7 @@ import type { SizeLimit } from '../../../types' ...@@ -9,7 +9,7 @@ import type { SizeLimit } from '../../../types'
import { import {
ACTION, ACTION,
RSC, RSC_HEADER,
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { isNotFoundError } from '../../client/components/not-found' import { isNotFoundError } from '../../client/components/not-found'
...@@ -146,7 +146,7 @@ async function createRedirectRenderResult( ...@@ -146,7 +146,7 @@ async function createRedirectRenderResult(
// if we're redirecting to a relative path, we'll try to stream the response // if we're redirecting to a relative path, we'll try to stream the response
if (redirectUrl.startsWith('/')) { if (redirectUrl.startsWith('/')) {
const forwardedHeaders = getForwardedHeaders(req, res) const forwardedHeaders = getForwardedHeaders(req, res)
forwardedHeaders.set(RSC, '1') forwardedHeaders.set(RSC_HEADER, '1')
const host = req.headers['host'] const host = req.headers['host']
const proto = const proto =
......
...@@ -32,9 +32,9 @@ import { ...@@ -32,9 +32,9 @@ import {
import { canSegmentBeOverridden } from '../../client/components/match-segments' import { canSegmentBeOverridden } from '../../client/components/match-segments'
import { stripInternalQueries } from '../internal-utils' import { stripInternalQueries } from '../internal-utils'
import { import {
NEXT_ROUTER_PREFETCH, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE, NEXT_ROUTER_STATE_TREE,
RSC, RSC_HEADER,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { createMetadataComponents } from '../../lib/metadata/metadata' import { createMetadataComponents } from '../../lib/metadata/metadata'
import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper' import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper'
...@@ -393,7 +393,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -393,7 +393,6 @@ async function renderToHTMLOrFlightImpl(
renderOpts: RenderOpts, renderOpts: RenderOpts,
baseCtx: AppRenderBaseContext baseCtx: AppRenderBaseContext
) { ) {
const isFlight = req.headers[RSC.toLowerCase()] !== undefined
const isNotFoundPath = pagePath === '/404' const isNotFoundPath = pagePath === '/404'
// A unique request timestamp used by development to ensure that it's // A unique request timestamp used by development to ensure that it's
...@@ -469,7 +468,8 @@ async function renderToHTMLOrFlightImpl( ...@@ -469,7 +468,8 @@ async function renderToHTMLOrFlightImpl(
const isStaticGeneration = staticGenerationStore.isStaticGeneration const isStaticGeneration = staticGenerationStore.isStaticGeneration
// when static generation fails during PPR, we log the errors separately. We intentionally // when static generation fails during PPR, we log the errors separately. We intentionally
// silence the error logger in this case to avoid double logging. // silence the error logger in this case to avoid double logging.
const silenceStaticGenerationErrors = renderOpts.ppr && isStaticGeneration const silenceStaticGenerationErrors =
renderOpts.experimental.ppr && isStaticGeneration
const serverComponentsErrorHandler = createErrorHandler({ const serverComponentsErrorHandler = createErrorHandler({
_source: 'serverComponentsRenderer', _source: 'serverComponentsRenderer',
...@@ -539,17 +539,21 @@ async function renderToHTMLOrFlightImpl( ...@@ -539,17 +539,21 @@ async function renderToHTMLOrFlightImpl(
query = { ...query } query = { ...query }
stripInternalQueries(query) stripInternalQueries(query)
const isPrefetch = const isRSCRequest = req.headers[RSC_HEADER.toLowerCase()] !== undefined
req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] !== undefined
const isPrefetchRSCRequest =
isRSCRequest &&
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] !== undefined
/** /**
* Router state provided from the client-side router. Used to handle rendering from the common layout down. * Router state provided from the client-side router. Used to handle rendering from the common layout down.
*/ */
let providedFlightRouterState = isFlight let providedFlightRouterState =
? parseAndValidateFlightRouterState( isRSCRequest && (!isPrefetchRSCRequest || !renderOpts.experimental.ppr)
req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()] ? parseAndValidateFlightRouterState(
) req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()]
: undefined )
: undefined
/** /**
* The metadata items array created in next-app-loader with all relevant information * The metadata items array created in next-app-loader with all relevant information
...@@ -584,7 +588,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -584,7 +588,7 @@ async function renderToHTMLOrFlightImpl(
...baseCtx, ...baseCtx,
getDynamicParamFromSegment, getDynamicParamFromSegment,
query, query,
isPrefetch, isPrefetch: isPrefetchRSCRequest,
providedSearchParams, providedSearchParams,
requestTimestamp, requestTimestamp,
searchParamsProps, searchParamsProps,
...@@ -601,7 +605,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -601,7 +605,7 @@ async function renderToHTMLOrFlightImpl(
res, res,
} }
if (isFlight && !isStaticGeneration) { if (isRSCRequest && !isStaticGeneration) {
return generateFlight(ctx) return generateFlight(ctx)
} }
...@@ -701,7 +705,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -701,7 +705,7 @@ async function renderToHTMLOrFlightImpl(
) )
const renderer = createStaticRenderer({ const renderer = createStaticRenderer({
ppr: renderOpts.ppr, ppr: renderOpts.experimental.ppr,
isStaticGeneration: staticGenerationStore.isStaticGeneration, isStaticGeneration: staticGenerationStore.isStaticGeneration,
postponed: renderOpts.postponed postponed: renderOpts.postponed
? JSON.parse(renderOpts.postponed) ? JSON.parse(renderOpts.postponed)
...@@ -1003,7 +1007,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1003,7 +1007,7 @@ async function renderToHTMLOrFlightImpl(
if ( if (
// if PPR is enabled // if PPR is enabled
renderOpts.ppr && renderOpts.experimental.ppr &&
// and a call to `maybePostpone` happened // and a call to `maybePostpone` happened
staticGenerationStore.postponeWasTriggered && staticGenerationStore.postponeWasTriggered &&
// but there's no postpone state // but there's no postpone state
......
...@@ -139,7 +139,7 @@ export interface RenderOptsPartial { ...@@ -139,7 +139,7 @@ export interface RenderOptsPartial {
allowedForwardedHosts?: string[] allowedForwardedHosts?: string[]
params?: ParsedUrlQuery params?: ParsedUrlQuery
isPrefetch?: boolean isPrefetch?: boolean
ppr: boolean experimental: { ppr: boolean }
postponed?: string postponed?: string
} }
......
...@@ -17,7 +17,7 @@ export type StaticGenerationContext = { ...@@ -17,7 +17,7 @@ export type StaticGenerationContext = {
isDraftMode?: boolean isDraftMode?: boolean
isServerAction?: boolean isServerAction?: boolean
waitUntil?: Promise<any> waitUntil?: Promise<any>
ppr: boolean experimental: { ppr: boolean }
/** /**
* A hack around accessing the store value outside the context of the * A hack around accessing the store value outside the context of the
...@@ -76,9 +76,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -76,9 +76,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate, isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
isDraftMode: renderOpts.isDraftMode, isDraftMode: renderOpts.isDraftMode,
experimental: { experimental: renderOpts.experimental,
ppr: renderOpts.ppr,
},
} }
// TODO: remove this when we resolve accessing the store outside the execution context // TODO: remove this when we resolve accessing the store outside the execution context
......
This diff is collapsed.
import type { Normalizer } from '../normalizer' import type { PathnameNormalizer } from './pathname-normalizer'
export class BasePathPathnameNormalizer implements Normalizer { export class BasePathPathnameNormalizer implements PathnameNormalizer {
private readonly basePath?: string private readonly basePath?: string
constructor(basePath: string) { constructor(basePath: string) {
// A basePath of `/` is not a basePath. // A basePath of `/` is not a basePath.
......
import type { Normalizer } from '../normalizer' import type { PathnameNormalizer } from './pathname-normalizer'
export class NextDataPathnameNormalizer implements Normalizer { export class NextDataPathnameNormalizer implements PathnameNormalizer {
private readonly prefix: string private readonly prefix: string
constructor(buildID: string) { constructor(buildID: string) {
if (!buildID) { if (!buildID) {
......
import type { Normalizer } from '../normalizer'
export interface PathnameNormalizer extends Normalizer {
match(pathname: string): boolean
normalize(pathname: string, matched?: boolean): string
}
...@@ -65,5 +65,10 @@ describe('PostponedPathnameNormalizer', () => { ...@@ -65,5 +65,10 @@ describe('PostponedPathnameNormalizer', () => {
) )
} }
}) })
it('should normalize `/index` to `/`', () => {
const normalizer = new PostponedPathnameNormalizer(true)
expect(normalizer.normalize('/_next/postponed/index', true)).toBe('/')
})
}) })
}) })
import type { Normalizer } from '../normalizer' import type { PathnameNormalizer } from './pathname-normalizer'
export class PostponedPathnameNormalizer implements Normalizer { export class PostponedPathnameNormalizer implements PathnameNormalizer {
constructor(private readonly ppr: boolean | undefined) {} constructor(private readonly ppr: boolean | undefined) {}
public match(pathname: string) { public match(pathname: string) {
...@@ -21,6 +21,11 @@ export class PostponedPathnameNormalizer implements Normalizer { ...@@ -21,6 +21,11 @@ export class PostponedPathnameNormalizer implements Normalizer {
if (!matched && !this.match(pathname)) return pathname if (!matched && !this.match(pathname)) return pathname
// Remove the prefix. // Remove the prefix.
return pathname.substring('/_next/postponed'.length) || '/' pathname = pathname.substring('/_next/postponed'.length) || '/'
// If the pathname is equal to `/index`, we normalize it to `/`.
if (pathname === '/index') return '/'
return pathname
} }
} }
import { PrefetchRSCPathnameNormalizer } from './prefetch-rsc'
describe('PrefetchRSCPathnameNormalizer', () => {
describe('match', () => {
it('should return false if the pathname does not end with `.prefetch.rsc`', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return true if it matches', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(true)
}
})
it('should return false if it is disabled but ends with .prefetch.rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return false if it only ends in .rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
})
describe('normalize', () => {
it('should return the same pathname if we are not matched and the pathname does not end with `.prefetch.rsc`', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
it('should strip the `.prefetch.rsc` extension from the pathname when it matches', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
const expected = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(
expected[pathnames.indexOf(pathname)]
)
}
})
it('should return the same pathname if it is disabled but ends with .prefetch.rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
})
})
import type { PathnameNormalizer } from './pathname-normalizer'
import { RSC_PREFETCH_SUFFIX } from '../../../../lib/constants'
import { SuffixPathnameNormalizer } from './suffix'
export class PrefetchRSCPathnameNormalizer implements PathnameNormalizer {
private readonly suffix = new SuffixPathnameNormalizer(RSC_PREFETCH_SUFFIX)
constructor(private readonly hasAppDir: boolean) {}
public match(pathname: string) {
// If there's no app directory, we don't match.
if (!this.hasAppDir) return false
return this.suffix.match(pathname)
}
public normalize(pathname: string, matched?: boolean): string {
// If there's no app directory, we don't need to normalize.
if (!this.hasAppDir) return pathname
return this.suffix.normalize(pathname, matched)
}
}
import type { Normalizer } from '../normalizer' import type { PathnameNormalizer } from './pathname-normalizer'
import { RSC_SUFFIX } from '../../../../lib/constants'
import { SuffixPathnameNormalizer } from './suffix'
export class RSCPathnameNormalizer implements PathnameNormalizer {
private readonly suffix = new SuffixPathnameNormalizer(RSC_SUFFIX)
export class RSCPathnameNormalizer implements Normalizer {
constructor(private readonly hasAppDir: boolean) {} constructor(private readonly hasAppDir: boolean) {}
public match(pathname: string) { public match(pathname: string) {
// If there's no app directory, we don't match. // If there's no app directory, we don't match.
if (!this.hasAppDir) return false if (!this.hasAppDir) return false
// If the pathname doesn't end in `.rsc`, we don't match. return this.suffix.match(pathname)
if (!pathname.endsWith('.rsc')) return false
return true
} }
public normalize(pathname: string, matched?: boolean): string { public normalize(pathname: string, matched?: boolean): string {
// If there's no app directory, we don't need to normalize. // If there's no app directory, we don't need to normalize.
if (!this.hasAppDir) return pathname if (!this.hasAppDir) return pathname
// If we're not matched and we don't match, we don't need to normalize. return this.suffix.normalize(pathname, matched)
if (!matched && !this.match(pathname)) return pathname
return pathname.substring(0, pathname.length - 4)
} }
} }
import type { Normalizer } from '../normalizer'
export class SuffixPathnameNormalizer implements Normalizer {
constructor(private readonly suffix: string) {}
public match(pathname: string) {
// If the pathname doesn't end in the suffix, we don't match.
if (!pathname.endsWith(this.suffix)) return false
return true
}
public normalize(pathname: string, matched?: boolean): string {
// If we're not matched and we don't match, we don't need to normalize.
if (!matched && !this.match(pathname)) return pathname
return pathname.substring(0, pathname.length - this.suffix.length)
}
}
...@@ -8,7 +8,11 @@ import type { ...@@ -8,7 +8,11 @@ import type {
import LRUCache from 'next/dist/compiled/lru-cache' import LRUCache from 'next/dist/compiled/lru-cache'
import path from '../../../shared/lib/isomorphic/path' import path from '../../../shared/lib/isomorphic/path'
import { NEXT_CACHE_TAGS_HEADER } from '../../../lib/constants' import {
NEXT_CACHE_TAGS_HEADER,
RSC_PREFETCH_SUFFIX,
RSC_SUFFIX,
} from '../../../lib/constants'
type FileSystemCacheContext = Omit< type FileSystemCacheContext = Omit<
CacheHandlerContext, CacheHandlerContext,
...@@ -16,6 +20,7 @@ type FileSystemCacheContext = Omit< ...@@ -16,6 +20,7 @@ type FileSystemCacheContext = Omit<
> & { > & {
fs: CacheFs fs: CacheFs
serverDistDir: string serverDistDir: string
experimental: { ppr: boolean }
} }
type TagsManifest = { type TagsManifest = {
...@@ -33,6 +38,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -33,6 +38,7 @@ export default class FileSystemCache implements CacheHandler {
private pagesDir: boolean private pagesDir: boolean
private tagsManifestPath?: string private tagsManifestPath?: string
private revalidatedTags: string[] private revalidatedTags: string[]
private readonly experimental: { ppr: boolean }
constructor(ctx: FileSystemCacheContext) { constructor(ctx: FileSystemCacheContext) {
this.fs = ctx.fs this.fs = ctx.fs
...@@ -41,6 +47,7 @@ export default class FileSystemCache implements CacheHandler { ...@@ -41,6 +47,7 @@ export default class FileSystemCache implements CacheHandler {
this.appDir = !!ctx._appDir this.appDir = !!ctx._appDir
this.pagesDir = !!ctx._pagesDir this.pagesDir = !!ctx._pagesDir
this.revalidatedTags = ctx.revalidatedTags this.revalidatedTags = ctx.revalidatedTags
this.experimental = ctx.experimental
if (ctx.maxMemoryCacheSize && !memoryCache) { if (ctx.maxMemoryCacheSize && !memoryCache) {
memoryCache = new LRUCache({ memoryCache = new LRUCache({
...@@ -187,7 +194,12 @@ export default class FileSystemCache implements CacheHandler { ...@@ -187,7 +194,12 @@ export default class FileSystemCache implements CacheHandler {
} else { } else {
const pageData = isAppPath const pageData = isAppPath
? await this.fs.readFile( ? await this.fs.readFile(
this.getFilePath(`${key}.rsc`, 'app'), this.getFilePath(
`${key}${
this.experimental.ppr ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX
}`,
'app'
),
'utf8' 'utf8'
) )
: JSON.parse( : JSON.parse(
......
...@@ -32,6 +32,7 @@ export interface CacheHandlerContext { ...@@ -32,6 +32,7 @@ export interface CacheHandlerContext {
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
prerenderManifest?: PrerenderManifest prerenderManifest?: PrerenderManifest
revalidatedTags: string[] revalidatedTags: string[]
experimental: { ppr: boolean }
_appDir: boolean _appDir: boolean
_pagesDir: boolean _pagesDir: boolean
_requestHeaders: IncrementalCache['requestHeaders'] _requestHeaders: IncrementalCache['requestHeaders']
...@@ -91,6 +92,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -91,6 +92,7 @@ export class IncrementalCache implements IncrementalCacheType {
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
CurCacheHandler, CurCacheHandler,
allowedRevalidateHeaderKeys, allowedRevalidateHeaderKeys,
experimental,
}: { }: {
fs?: CacheFs fs?: CacheFs
dev: boolean dev: boolean
...@@ -107,6 +109,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -107,6 +109,7 @@ export class IncrementalCache implements IncrementalCacheType {
getPrerenderManifest: () => PrerenderManifest getPrerenderManifest: () => PrerenderManifest
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
CurCacheHandler?: typeof CacheHandler CurCacheHandler?: typeof CacheHandler
experimental: { ppr: boolean }
}) { }) {
const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
if (!CurCacheHandler) { if (!CurCacheHandler) {
...@@ -175,6 +178,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -175,6 +178,7 @@ export class IncrementalCache implements IncrementalCacheType {
_appDir: !!appDir, _appDir: !!appDir,
_requestHeaders: requestHeaders, _requestHeaders: requestHeaders,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
experimental,
}) })
} }
} }
...@@ -569,12 +573,15 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -569,12 +573,15 @@ export class IncrementalCache implements IncrementalCacheType {
// revalidateAfter values so we update this on set // revalidateAfter values so we update this on set
if (typeof ctx.revalidate !== 'undefined' && !ctx.fetchCache) { if (typeof ctx.revalidate !== 'undefined' && !ctx.fetchCache) {
this.prerenderManifest.routes[pathname] = { this.prerenderManifest.routes[pathname] = {
experimentalPPR: undefined,
dataRoute: path.posix.join( dataRoute: path.posix.join(
'/_next/data', '/_next/data',
`${normalizePagePath(pathname)}.json` `${normalizePagePath(pathname)}.json`
), ),
srcRoute: null, // FIXME: provide actual source route, however, when dynamically appending it doesn't really matter srcRoute: null, // FIXME: provide actual source route, however, when dynamically appending it doesn't really matter
initialRevalidateSeconds: ctx.revalidate, initialRevalidateSeconds: ctx.revalidate,
// Pages routes do not have a prefetch data route.
prefetchDataRoute: undefined,
} }
} }
await this.cacheHandler?.set(pathname, data, ctx) await this.cacheHandler?.set(pathname, data, ctx)
......
...@@ -39,6 +39,7 @@ import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-s ...@@ -39,6 +39,7 @@ import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-s
import { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route' import { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route'
import { RSCPathnameNormalizer } from '../../future/normalizers/request/rsc' import { RSCPathnameNormalizer } from '../../future/normalizers/request/rsc'
import { PostponedPathnameNormalizer } from '../../future/normalizers/request/postponed' import { PostponedPathnameNormalizer } from '../../future/normalizers/request/postponed'
import { PrefetchRSCPathnameNormalizer } from '../../future/normalizers/request/prefetch-rsc'
export type FsOutput = { export type FsOutput = {
type: type:
...@@ -371,6 +372,7 @@ export async function setupFsCheck(opts: { ...@@ -371,6 +372,7 @@ export async function setupFsCheck(opts: {
// Because we can't know if the app directory is enabled or not at this // Because we can't know if the app directory is enabled or not at this
// stage, we assume that it is. // stage, we assume that it is.
rsc: new RSCPathnameNormalizer(true), rsc: new RSCPathnameNormalizer(true),
prefetchRSC: new PrefetchRSCPathnameNormalizer(true),
postponed: new PostponedPathnameNormalizer(opts.config.experimental.ppr), postponed: new PostponedPathnameNormalizer(opts.config.experimental.ppr),
} }
...@@ -419,7 +421,9 @@ export async function setupFsCheck(opts: { ...@@ -419,7 +421,9 @@ export async function setupFsCheck(opts: {
// Simulate minimal mode requests by normalizing RSC and postponed // Simulate minimal mode requests by normalizing RSC and postponed
// requests. // requests.
if (opts.minimalMode) { if (opts.minimalMode) {
if (normalizers.rsc.match(itemPath)) { if (normalizers.prefetchRSC.match(itemPath)) {
itemPath = normalizers.prefetchRSC.normalize(itemPath, true)
} else if (normalizers.rsc.match(itemPath)) {
itemPath = normalizers.rsc.normalize(itemPath, true) itemPath = normalizers.rsc.normalize(itemPath, true)
} else if (normalizers.postponed.match(itemPath)) { } else if (normalizers.postponed.match(itemPath)) {
itemPath = normalizers.postponed.normalize(itemPath, true) itemPath = normalizers.postponed.normalize(itemPath, true)
......
...@@ -82,7 +82,10 @@ import { setHttpClientAndAgentOptions } from './setup-http-agent-env' ...@@ -82,7 +82,10 @@ import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
import { isPagesAPIRouteMatch } from './future/route-matches/pages-api-route-match' import { isPagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import type { PagesAPIRouteMatch } from './future/route-matches/pages-api-route-match' import type { PagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import type { MatchOptions } from './future/route-matcher-managers/route-matcher-manager' import type { MatchOptions } from './future/route-matcher-managers/route-matcher-manager'
import { INSTRUMENTATION_HOOK_FILENAME } from '../lib/constants' import {
INSTRUMENTATION_HOOK_FILENAME,
RSC_PREFETCH_SUFFIX,
} 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' import { nodeFs } from './lib/node-fs-methods'
...@@ -324,6 +327,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -324,6 +327,7 @@ export default class NextNodeServer extends BaseServer {
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk, !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => this.getPrerenderManifest(), getPrerenderManifest: () => this.getPrerenderManifest(),
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
experimental: this.renderOpts.experimental,
}) })
} }
...@@ -996,7 +1000,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -996,7 +1000,7 @@ export default class NextNodeServer extends BaseServer {
protected getPrefetchRsc(pathname: string): Promise<string> { protected getPrefetchRsc(pathname: string): Promise<string> {
return this.getCacheFilesystem().readFile( return this.getCacheFilesystem().readFile(
join(this.serverDistDir, 'app', `${pathname}.prefetch.rsc`), join(this.serverDistDir, 'app', `${pathname}${RSC_PREFETCH_SUFFIX}`),
'utf8' 'utf8'
) )
} }
......
...@@ -14,7 +14,10 @@ type ContentTypeOption = string | undefined ...@@ -14,7 +14,10 @@ type ContentTypeOption = string | undefined
export type RenderResultMetadata = { export type RenderResultMetadata = {
pageData?: any pageData?: any
revalidate?: Revalidate revalidate?: Revalidate
staticBailoutInfo?: any staticBailoutInfo?: {
stack?: string
description?: string
}
assetQueryString?: string assetQueryString?: string
isNotFound?: boolean isNotFound?: boolean
isRedirect?: boolean isRedirect?: boolean
......
...@@ -68,6 +68,16 @@ export interface RequestMeta { ...@@ -68,6 +68,16 @@ export interface RequestMeta {
*/ */
incrementalCache?: any incrementalCache?: any
/**
* True when the request is for the prefetch flight data.
*/
isPrefetchRSCRequest?: true
/**
* True when the request is for the flight data.
*/
isRSCRequest?: true
/** /**
* Postponed state to use for resumption. If present it's assumed that the * Postponed state to use for resumption. If present it's assumed that the
* request is for a page that has postponed (there are no guarantees that the * request is for a page that has postponed (there are no guarantees that the
......
...@@ -74,6 +74,8 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -74,6 +74,8 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
CurCacheHandler: CurCacheHandler:
this.serverOptions.webServerConfig.incrementalCacheHandler, this.serverOptions.webServerConfig.incrementalCacheHandler,
getPrerenderManifest: () => this.getPrerenderManifest(), getPrerenderManifest: () => this.getPrerenderManifest(),
// PPR is not supported in the edge runtime.
experimental: { ppr: false },
}) })
} }
protected getResponseCache() { protected getResponseCache() {
......
...@@ -110,7 +110,7 @@ export class EdgeRouteModuleWrapper { ...@@ -110,7 +110,7 @@ export class EdgeRouteModuleWrapper {
renderOpts: { renderOpts: {
supportsDynamicHTML: true, supportsDynamicHTML: true,
// App Route's cannot be postponed. // App Route's cannot be postponed.
ppr: false, experimental: { ppr: false },
}, },
} }
......
...@@ -2557,9 +2557,12 @@ const runTests = (isDev = false) => { ...@@ -2557,9 +2557,12 @@ const runTests = (isDev = false) => {
rsc: { rsc: {
header: 'RSC', header: 'RSC',
contentTypeHeader: 'text/x-component', contentTypeHeader: 'text/x-component',
didPostponeHeader: 'x-nextjs-postponed',
varyHeader: varyHeader:
'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url', 'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url',
prefetchHeader: 'Next-Router-Prefetch', prefetchHeader: 'Next-Router-Prefetch',
prefetchSuffix: '.prefetch.rsc',
suffix: '.rsc',
}, },
}) })
}) })
......
...@@ -1492,9 +1492,12 @@ function runTests({ dev }) { ...@@ -1492,9 +1492,12 @@ function runTests({ dev }) {
rsc: { rsc: {
header: 'RSC', header: 'RSC',
contentTypeHeader: 'text/x-component', contentTypeHeader: 'text/x-component',
didPostponeHeader: 'x-nextjs-postponed',
varyHeader: varyHeader:
'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url', 'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url',
prefetchHeader: 'Next-Router-Prefetch', prefetchHeader: 'Next-Router-Prefetch',
prefetchSuffix: '.prefetch.rsc',
suffix: '.rsc',
}, },
}) })
}) })
......
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
describe('minimal-mode-response-cache', () => { describe('minimal-mode-response-cache', () => {
let next: NextInstance let next: NextInstance
let server let server
let port
let appPort let appPort
let output = '' let output = ''
...@@ -60,14 +61,14 @@ describe('minimal-mode-response-cache', () => { ...@@ -60,14 +61,14 @@ describe('minimal-mode-response-cache', () => {
.replace('console.error(err)', `console.error('top-level', err)`) .replace('console.error(err)', `console.error('top-level', err)`)
.replace('port:', 'minimalMode: true,port:') .replace('port:', 'minimalMode: true,port:')
) )
appPort = await findPort() port = await findPort()
server = await initNextServerScript( server = await initNextServerScript(
testServer, testServer,
/- Local:/, /- Local:/,
{ {
...process.env, ...process.env,
HOSTNAME: '', HOSTNAME: '',
PORT: appPort, PORT: port.toString(),
}, },
undefined, undefined,
{ {
...@@ -80,6 +81,7 @@ describe('minimal-mode-response-cache', () => { ...@@ -80,6 +81,7 @@ describe('minimal-mode-response-cache', () => {
}, },
} }
) )
appPort = `http://127.0.0.1:${port}`
}) })
afterAll(async () => { afterAll(async () => {
await next.destroy() await next.destroy()
...@@ -128,25 +130,22 @@ describe('minimal-mode-response-cache', () => { ...@@ -128,25 +130,22 @@ describe('minimal-mode-response-cache', () => {
headers, headers,
}) })
const content1 = await res1.text() const content1 = await res1.text()
expect(res1.headers.get('content-type')).toContain('text/x-component')
expect(content1).not.toContain('<html') expect(content1).not.toContain('<html')
expect(content1).toContain('app-another') expect(content1).toContain('app-another')
expect(res1.headers.get('content-type')).toContain('text/x-component')
const res2 = await fetchViaHTTP(appPort, '/app-another', undefined, { const res2 = await fetchViaHTTP(appPort, '/app-another', undefined, {
headers, headers,
}) })
const content2 = await res2.text() const content2 = await res2.text()
expect(res2.headers.get('content-type')).toContain('text/html')
expect(content2).toContain('<html') expect(content2).toContain('<html')
expect(content2).toContain('app-another') expect(content2).toContain('app-another')
expect(res2.headers.get('content-type')).toContain('text/html')
}) })
it('should have correct "Started server on" log', async () => { it('should have correct "Started server on" log', async () => {
expect(output).toContain(`- Local:`) expect(output).toContain(`- Local:`)
let pattern = new RegExp( expect(output).toContain(`http://localhost:${port}`)
`Local:\\s*http://localhost:${appPort}|Local:\\s*http://127.0.0.1:${appPort}|Local: http://\\[::1\\]:${appPort}`
)
expect(output).toMatch(pattern)
}) })
it('should have correct responses', async () => { it('should have correct responses', async () => {
......
...@@ -15,6 +15,9 @@ describe('FileSystemCache', () => { ...@@ -15,6 +15,9 @@ describe('FileSystemCache', () => {
fs: nodeFs, fs: nodeFs,
serverDistDir: cacheDir, serverDistDir: cacheDir,
revalidatedTags: [], revalidatedTags: [],
experimental: {
ppr: false,
},
}) })
const binary = await fs.readFile( const binary = await fs.readFile(
......
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