Unverified Commit 0eb71b6f authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Misc Typescript and export updates (#55841)

This refactors a bit of the typescript types around the export and build pipelines. This does not introduce any new functionality.
Co-authored-by: 's avatarJiachi Liu <4800338+huozhi@users.noreply.github.com>
parent aa3377ed
This diff is collapsed.
/**
* Formats the manifest depending on the environment variable
* `NODE_ENV`. If it's set to `development`, it will return a pretty printed
* JSON string, otherwise it will return a minified JSON string.
*/
export function formatManifest<T extends object>(manifest: T): string {
if (process.env.NODE_ENV === 'development') {
return JSON.stringify(manifest, null, 2)
}
return JSON.stringify(manifest)
}
#!/usr/bin/env node #!/usr/bin/env node
import type { ExportAppOptions } from '../export/types'
import { resolve, join } from 'path' import { resolve, join } from 'path'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import { cyan } from '../lib/picocolors' import { cyan } from '../lib/picocolors'
import exportApp, { ExportError, ExportOptions } from '../export' import exportApp, { ExportError } from '../export'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import { printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
import { CliCommand } from '../lib/commands' import { CliCommand } from '../lib/commands'
...@@ -43,7 +45,7 @@ const nextExport: CliCommand = (args) => { ...@@ -43,7 +45,7 @@ const nextExport: CliCommand = (args) => {
printAndExit(`> No such directory exists as the project root: ${dir}`) printAndExit(`> No such directory exists as the project root: ${dir}`)
} }
const options: ExportOptions = { const options: ExportAppOptions = {
silent: args['--silent'] || false, silent: args['--silent'] || false,
threads: args['--threads'], threads: args['--threads'],
outdir: args['--outdir'] ? resolve(args['--outdir']) : join(dir, 'out'), outdir: args['--outdir'] ? resolve(args['--outdir']) : join(dir, 'out'),
......
This diff is collapsed.
import type { ExportPageResult } from '../types' import type { ExportRouteResult, FileWriter } from '../types'
import type { AppPageRender } from '../../server/app-render/app-render'
import type { RenderOpts } from '../../server/app-render/types' import type { RenderOpts } from '../../server/app-render/types'
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
import type { NextParsedUrlQuery } from '../../server/request-meta' import type { NextParsedUrlQuery } from '../../server/request-meta'
import fs from 'fs/promises'
import { MockedRequest, MockedResponse } from '../../server/lib/mock-request' import { MockedRequest, MockedResponse } from '../../server/lib/mock-request'
import { import {
RSC, RSC,
...@@ -14,14 +12,13 @@ import { ...@@ -14,14 +12,13 @@ import {
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 } 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'
/** export const enum ExportedAppPageFiles {
* Lazily loads and runs the app page render function. HTML = 'HTML',
*/ FLIGHT = 'FLIGHT',
const render: AppPageRender = (...args) => { META = 'META',
return require('../../server/future/route-modules/app-page/module.compiled').renderToHTMLOrFlight( POSTPONED = 'POSTPONED',
...args
)
} }
export async function generatePrefetchRsc( export async function generatePrefetchRsc(
...@@ -30,7 +27,8 @@ export async function generatePrefetchRsc( ...@@ -30,7 +27,8 @@ export async function generatePrefetchRsc(
res: MockedResponse, res: MockedResponse,
pathname: string, pathname: string,
htmlFilepath: string, htmlFilepath: string,
renderOpts: RenderOpts renderOpts: RenderOpts,
fileWriter: FileWriter
) { ) {
req.headers[RSC.toLowerCase()] = '1' req.headers[RSC.toLowerCase()] = '1'
req.headers[NEXT_URL.toLowerCase()] = path req.headers[NEXT_URL.toLowerCase()] = path
...@@ -40,7 +38,13 @@ export async function generatePrefetchRsc( ...@@ -40,7 +38,13 @@ export async function generatePrefetchRsc(
renderOpts.isPrefetch = true renderOpts.isPrefetch = true
delete renderOpts.isRevalidate delete renderOpts.isRevalidate
const prefetchRenderResult = await render(req, res, pathname, {}, renderOpts) const prefetchRenderResult = await lazyRenderAppPage(
req,
res,
pathname,
{},
renderOpts
)
prefetchRenderResult.pipe(res) prefetchRenderResult.pipe(res)
await res.hasStreamed await res.hasStreamed
...@@ -49,7 +53,8 @@ export async function generatePrefetchRsc( ...@@ -49,7 +53,8 @@ export async function generatePrefetchRsc(
if ((renderOpts as any).store.staticPrefetchBailout) return if ((renderOpts as any).store.staticPrefetchBailout) return
await fs.writeFile( await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, '.prefetch.rsc'), htmlFilepath.replace(/\.html$/, '.prefetch.rsc'),
prefetchRscData prefetchRscData
) )
...@@ -66,8 +71,9 @@ export async function exportAppPage( ...@@ -66,8 +71,9 @@ export async function exportAppPage(
htmlFilepath: string, htmlFilepath: string,
debugOutput: boolean, debugOutput: boolean,
isDynamicError: boolean, isDynamicError: boolean,
isAppPrefetch: boolean isAppPrefetch: boolean,
): Promise<ExportPageResult> { fileWriter: FileWriter
): Promise<ExportRouteResult> {
// If the page is `/_not-found`, then we should update the page to be `/404`. // If the page is `/_not-found`, then we should update the page to be `/404`.
if (page === '/_not-found') { if (page === '/_not-found') {
pathname = '/404' pathname = '/404'
...@@ -81,13 +87,20 @@ export async function exportAppPage( ...@@ -81,13 +87,20 @@ export async function exportAppPage(
res, res,
pathname, pathname,
htmlFilepath, htmlFilepath,
renderOpts renderOpts,
fileWriter
) )
return { fromBuildExportRevalidate: 0 } return { revalidate: 0 }
} }
const result = await render(req, res, pathname, query, renderOpts) const result = await lazyRenderAppPage(
req,
res,
pathname,
query,
renderOpts
)
const html = result.toUnchunkedString() const html = result.toUnchunkedString()
const { metadata } = result const { metadata } = result
const flightData = metadata.pageData const flightData = metadata.pageData
...@@ -107,7 +120,8 @@ export async function exportAppPage( ...@@ -107,7 +120,8 @@ export async function exportAppPage(
res, res,
pathname, pathname,
htmlFilepath, htmlFilepath,
renderOpts renderOpts,
fileWriter
) )
} }
...@@ -127,7 +141,7 @@ export async function exportAppPage( ...@@ -127,7 +141,7 @@ export async function exportAppPage(
console.warn(err) console.warn(err)
} }
return { fromBuildExportRevalidate: 0 } return { revalidate: 0 }
} }
let headers: OutgoingHttpHeaders | undefined let headers: OutgoingHttpHeaders | undefined
...@@ -136,28 +150,38 @@ export async function exportAppPage( ...@@ -136,28 +150,38 @@ export async function exportAppPage(
} }
// Writing static HTML to a file. // Writing static HTML to a file.
await fs.writeFile(htmlFilepath, html ?? '', 'utf8') await fileWriter(
ExportedAppPageFiles.HTML,
htmlFilepath,
html ?? '',
'utf8'
)
// Writing the request metadata to a file. // Writing the request metadata to a file.
const meta = { headers } const meta = { headers }
await fs.writeFile( await fileWriter(
ExportedAppPageFiles.META,
htmlFilepath.replace(/\.html$/, '.meta'), htmlFilepath.replace(/\.html$/, '.meta'),
JSON.stringify(meta) JSON.stringify(meta)
) )
// Writing the RSC payload to a file. // Writing the RSC payload to a file.
await fs.writeFile(htmlFilepath.replace(/\.html$/, '.rsc'), flightData) await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, '.rsc'),
flightData
)
return { return {
fromBuildExportRevalidate: revalidate,
// Only include the metadata if the environment has next support. // Only include the metadata if the environment has next support.
fromBuildExportMeta: hasNextSupport ? meta : undefined, metadata: hasNextSupport ? meta : undefined,
revalidate,
} }
} catch (err: any) { } catch (err: any) {
if (!isDynamicUsageError(err)) { if (!isDynamicUsageError(err)) {
throw err throw err
} }
return { fromBuildExportRevalidate: 0 } return { revalidate: 0 }
} }
} }
import type { ExportPageResult } from '../types' import type { ExportRouteResult, FileWriter } from '../types'
import type AppRouteRouteModule from '../../server/future/route-modules/app-route/module' import type AppRouteRouteModule from '../../server/future/route-modules/app-route/module'
import type { AppRouteRouteHandlerContext } from '../../server/future/route-modules/app-route/module' import type { AppRouteRouteHandlerContext } from '../../server/future/route-modules/app-route/module'
import type { IncrementalCache } from '../../server/lib/incremental-cache' import type { IncrementalCache } from '../../server/lib/incremental-cache'
import fs from 'fs/promises'
import { join } from 'path' import { join } from 'path'
import { NEXT_CACHE_TAGS_HEADER } from '../../lib/constants' import { NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'
import { NodeNextRequest } from '../../server/base-http/node' import { NodeNextRequest } from '../../server/base-http/node'
...@@ -18,6 +17,11 @@ import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error' ...@@ -18,6 +17,11 @@ import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { SERVER_DIRECTORY } from '../../shared/lib/constants' import { SERVER_DIRECTORY } from '../../shared/lib/constants'
import { hasNextSupport } from '../../telemetry/ci-info' import { hasNextSupport } from '../../telemetry/ci-info'
export const enum ExportedAppRouteFiles {
BODY = 'BODY',
META = 'META',
}
export async function exportAppRoute( export async function exportAppRoute(
req: MockedRequest, req: MockedRequest,
res: MockedResponse, res: MockedResponse,
...@@ -25,8 +29,9 @@ export async function exportAppRoute( ...@@ -25,8 +29,9 @@ export async function exportAppRoute(
page: string, page: string,
incrementalCache: IncrementalCache | undefined, incrementalCache: IncrementalCache | undefined,
distDir: string, distDir: string,
htmlFilepath: string htmlFilepath: string,
): Promise<ExportPageResult> { fileWriter: FileWriter
): Promise<ExportRouteResult> {
// Ensure that the URL is absolute. // Ensure that the URL is absolute.
req.url = `http://localhost:3000${req.url}` req.url = `http://localhost:3000${req.url}`
...@@ -51,7 +56,7 @@ export async function exportAppRoute( ...@@ -51,7 +56,7 @@ export async function exportAppRoute(
}, },
notFoundRoutes: [], notFoundRoutes: [],
}, },
staticGenerationContext: { renderOpts: {
originalPathname: page, originalPathname: page,
nextExport: true, nextExport: true,
supportsDynamicHTML: false, supportsDynamicHTML: false,
...@@ -60,7 +65,7 @@ export async function exportAppRoute( ...@@ -60,7 +65,7 @@ export async function exportAppRoute(
} }
if (hasNextSupport) { if (hasNextSupport) {
context.staticGenerationContext.isRevalidate = true context.renderOpts.isRevalidate = true
} }
// This is a route handler, which means it has it's handler in the // This is a route handler, which means it has it's handler in the
...@@ -74,15 +79,14 @@ export async function exportAppRoute( ...@@ -74,15 +79,14 @@ export async function exportAppRoute(
const isValidStatus = response.status < 400 || response.status === 404 const isValidStatus = response.status < 400 || response.status === 404
if (!isValidStatus) { if (!isValidStatus) {
return { fromBuildExportRevalidate: 0 } return { revalidate: 0 }
} }
const blob = await response.blob() const blob = await response.blob()
const revalidate = const revalidate = context.renderOpts.store?.revalidate || false
context.staticGenerationContext.store?.revalidate || false
const headers = toNodeOutgoingHttpHeaders(response.headers) const headers = toNodeOutgoingHttpHeaders(response.headers)
const cacheTags = (context.staticGenerationContext as any).fetchTags const cacheTags = (context.renderOpts as any).fetchTags
if (cacheTags) { if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags headers[NEXT_CACHE_TAGS_HEADER] = cacheTags
...@@ -94,24 +98,30 @@ export async function exportAppRoute( ...@@ -94,24 +98,30 @@ export async function exportAppRoute(
// Writing response body to a file. // Writing response body to a file.
const body = Buffer.from(await blob.arrayBuffer()) const body = Buffer.from(await blob.arrayBuffer())
await fs.writeFile(htmlFilepath.replace(/\.html$/, '.body'), body, 'utf8') await fileWriter(
ExportedAppRouteFiles.BODY,
htmlFilepath.replace(/\.html$/, '.body'),
body,
'utf8'
)
// Write the request metadata to a file. // Write the request metadata to a file.
const meta = { status: response.status, headers } const meta = { status: response.status, headers }
await fs.writeFile( await fileWriter(
ExportedAppRouteFiles.META,
htmlFilepath.replace(/\.html$/, '.meta'), htmlFilepath.replace(/\.html$/, '.meta'),
JSON.stringify(meta) JSON.stringify(meta)
) )
return { return {
fromBuildExportRevalidate: revalidate, revalidate: revalidate,
fromBuildExportMeta: meta, metadata: meta,
} }
} catch (err) { } catch (err) {
if (!isDynamicUsageError(err)) { if (!isDynamicUsageError(err)) {
throw err throw err
} }
return { fromBuildExportRevalidate: 0 } return { revalidate: 0 }
} }
} }
import type { ExportPageResult } from '../types' import type { ExportRouteResult, FileWriter } from '../types'
import type { PagesRender, RenderOpts } from '../../server/render' import type { RenderOpts } from '../../server/render'
import type { LoadComponentsReturnType } from '../../server/load-components' import type { LoadComponentsReturnType } from '../../server/load-components'
import type { AmpValidation } from '../types' import type { AmpValidation } from '../types'
import type { NextParsedUrlQuery } from '../../server/request-meta' import type { NextParsedUrlQuery } from '../../server/request-meta'
import fs from 'fs/promises'
import RenderResult from '../../server/render-result' import RenderResult from '../../server/render-result'
import { dirname, join } from 'path' import { join } from 'path'
import { MockedRequest, MockedResponse } from '../../server/lib/mock-request' import { MockedRequest, MockedResponse } from '../../server/lib/mock-request'
import { isInAmpMode } from '../../shared/lib/amp-mode' import { isInAmpMode } from '../../shared/lib/amp-mode'
import { SERVER_PROPS_EXPORT_ERROR } from '../../lib/constants' import { SERVER_PROPS_EXPORT_ERROR } from '../../lib/constants'
import { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error' import { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error'
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator' import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import { FileType, fileExists } from '../../lib/file-exists' import { FileType, fileExists } from '../../lib/file-exists'
import { lazyRenderPagesPage } from '../../server/future/route-modules/pages/module.render'
/** export const enum ExportedPagesFiles {
* Lazily loads and runs the app page render function. HTML = 'HTML',
*/ DATA = 'DATA',
const render: PagesRender = (...args) => { AMP_HTML = 'AMP_HTML',
return require('../../server/future/route-modules/pages/module.compiled').renderToHTML( AMP_DATA = 'AMP_PAGE_DATA',
...args
)
} }
export async function exportPages( export async function exportPages(
...@@ -40,8 +38,9 @@ export async function exportPages( ...@@ -40,8 +38,9 @@ export async function exportPages(
isDynamic: boolean, isDynamic: boolean,
hasOrigQueryValues: boolean, hasOrigQueryValues: boolean,
renderOpts: RenderOpts, renderOpts: RenderOpts,
components: LoadComponentsReturnType components: LoadComponentsReturnType,
): Promise<ExportPageResult> { fileWriter: FileWriter
): Promise<ExportRouteResult | undefined> {
const ampState = { const ampState = {
ampFirst: components.pageConfig?.amp === true, ampFirst: components.pageConfig?.amp === true,
hasQuery: Boolean(query.amp), hasQuery: Boolean(query.amp),
...@@ -58,7 +57,7 @@ export async function exportPages( ...@@ -58,7 +57,7 @@ export async function exportPages(
// for non-dynamic SSG pages we should have already // for non-dynamic SSG pages we should have already
// prerendered the file // prerendered the file
if (!buildExport && components.getStaticProps && !isDynamic) { if (!buildExport && components.getStaticProps && !isDynamic) {
return {} return
} }
if (components.getStaticProps && !htmlFilepath.endsWith('.html')) { if (components.getStaticProps && !htmlFilepath.endsWith('.html')) {
...@@ -93,7 +92,13 @@ export async function exportPages( ...@@ -93,7 +92,13 @@ export async function exportPages(
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true) process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
} }
try { try {
renderResult = await render(req, res, page, query, renderOpts) renderResult = await lazyRenderPagesPage(
req,
res,
page,
query,
renderOpts
)
} catch (err: any) { } catch (err: any) {
if (err.digest !== NEXT_DYNAMIC_NO_SSR_CODE) { if (err.digest !== NEXT_DYNAMIC_NO_SSR_CODE) {
throw err throw err
...@@ -140,13 +145,12 @@ export async function exportPages( ...@@ -140,13 +145,12 @@ export async function exportPages(
? join(ampPath, 'index.html') ? join(ampPath, 'index.html')
: `${ampPath}.html` : `${ampPath}.html`
const ampBaseDir = join(outDir, dirname(ampHtmlFilename))
const ampHtmlFilepath = join(outDir, ampHtmlFilename) const ampHtmlFilepath = join(outDir, ampHtmlFilename)
const exists = await fileExists(ampHtmlFilepath, FileType.File) const exists = await fileExists(ampHtmlFilepath, FileType.File)
if (!exists) { if (!exists) {
try { try {
ampRenderResult = await render( ampRenderResult = await lazyRenderPagesPage(
req, req,
res, res,
page, page,
...@@ -166,8 +170,13 @@ export async function exportPages( ...@@ -166,8 +170,13 @@ export async function exportPages(
if (!renderOpts.ampSkipValidation) { if (!renderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + '?amp=1') await validateAmp(ampHtml, page + '?amp=1')
} }
await fs.mkdir(ampBaseDir, { recursive: true })
await fs.writeFile(ampHtmlFilepath, ampHtml, 'utf8') await fileWriter(
ExportedPagesFiles.AMP_HTML,
ampHtmlFilepath,
ampHtml,
'utf8'
)
} }
} }
...@@ -178,11 +187,16 @@ export async function exportPages( ...@@ -178,11 +187,16 @@ export async function exportPages(
htmlFilename.replace(/\.html$/, '.json') htmlFilename.replace(/\.html$/, '.json')
) )
await fs.mkdir(dirname(dataFile), { recursive: true }) await fileWriter(
await fs.writeFile(dataFile, JSON.stringify(metadata.pageData), 'utf8') ExportedPagesFiles.DATA,
dataFile,
JSON.stringify(metadata.pageData),
'utf8'
)
if (hybridAmp) { if (hybridAmp) {
await fs.writeFile( await fileWriter(
ExportedPagesFiles.AMP_DATA,
dataFile.replace(/\.json$/, '.amp.json'), dataFile.replace(/\.json$/, '.amp.json'),
JSON.stringify(metadata.pageData), JSON.stringify(metadata.pageData),
'utf8' 'utf8'
...@@ -192,12 +206,12 @@ export async function exportPages( ...@@ -192,12 +206,12 @@ export async function exportPages(
if (!ssgNotFound) { if (!ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found // don't attempt writing to disk if getStaticProps returned not found
await fs.writeFile(htmlFilepath, html, 'utf8') await fileWriter(ExportedPagesFiles.HTML, htmlFilepath, html, 'utf8')
} }
return { return {
ampValidations, ampValidations,
fromBuildExportRevalidate: metadata.revalidate, revalidate: metadata.revalidate,
ssgNotFound, ssgNotFound,
} }
} }
import type { WriteFileOptions } from 'fs'
import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-render/types' import type { RenderOptsPartial as AppRenderOptsPartial } from '../server/app-render/types'
import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render' import type { RenderOptsPartial as PagesRenderOptsPartial } from '../server/render'
import type { LoadComponentsReturnType } from '../server/load-components' import type { LoadComponentsReturnType } from '../server/load-components'
import type { OutgoingHttpHeaders } from 'http' import type { OutgoingHttpHeaders } from 'http'
import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator' import type AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import type { FontConfig } from '../server/font-utils'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { Span } from '../trace'
export interface AmpValidation { export interface AmpValidation {
page: string page: string
...@@ -12,15 +16,66 @@ export interface AmpValidation { ...@@ -12,15 +16,66 @@ export interface AmpValidation {
} }
} }
export interface ExportPageResult { /**
ampValidations?: AmpValidation[] * Writes a file to the filesystem (and also records the file that was written).
fromBuildExportRevalidate?: number | false */
fromBuildExportMeta?: { export type FileWriter = (
status?: number type: string,
headers?: OutgoingHttpHeaders path: string,
} content: any,
error?: boolean encodingOptions?: WriteFileOptions
ssgNotFound?: boolean ) => Promise<void>
type PathMap = ExportPathMap[keyof ExportPathMap]
export interface ExportPageInput {
path: string
pathMap: PathMap
distDir: string
outDir: string
pagesDataDir: string
renderOpts: WorkerRenderOptsPartial
ampValidatorPath?: string
trailingSlash?: boolean
buildExport?: boolean
serverRuntimeConfig: { [key: string]: any }
subFolders?: boolean
optimizeFonts: FontConfig
optimizeCss: any
disableOptimizedLoading: any
parentSpanId: any
httpAgentOptions: NextConfigComplete['httpAgentOptions']
debugOutput?: boolean
isrMemoryCacheSize?: NextConfigComplete['experimental']['isrMemoryCacheSize']
fetchCache?: boolean
incrementalCacheHandlerPath?: string
fetchCacheKeyPrefix?: string
nextConfigOutput?: NextConfigComplete['output']
enableExperimentalReact?: boolean
}
export type ExportedPageFile = {
type: string
path: string
}
export type ExportRouteResult =
| {
ampValidations?: AmpValidation[]
revalidate: number | false
metadata?: {
status?: number
headers?: OutgoingHttpHeaders
}
ssgNotFound?: boolean
}
| {
error: boolean
}
export type ExportPageResult = ExportRouteResult & {
files: ExportedPageFile[]
duration: number
} }
export type WorkerRenderOptsPartial = PagesRenderOptsPartial & export type WorkerRenderOptsPartial = PagesRenderOptsPartial &
...@@ -28,3 +83,70 @@ export type WorkerRenderOptsPartial = PagesRenderOptsPartial & ...@@ -28,3 +83,70 @@ export type WorkerRenderOptsPartial = PagesRenderOptsPartial &
export type WorkerRenderOpts = WorkerRenderOptsPartial & export type WorkerRenderOpts = WorkerRenderOptsPartial &
LoadComponentsReturnType LoadComponentsReturnType
export type ExportWorker = (
input: ExportPageInput
) => Promise<ExportPageResult | undefined>
export interface ExportAppOptions {
outdir: string
isInvokedFromCli: boolean
hasAppDir: boolean
silent?: boolean
threads?: number
debugOutput?: boolean
pages?: string[]
buildExport: boolean
statusMessage?: string
exportPageWorker?: ExportWorker
exportAppPageWorker?: ExportWorker
endWorker?: () => Promise<void>
nextConfig?: NextConfigComplete
hasOutdirFromCli?: boolean
}
export type ExportPageMetadata = {
revalidate: number | false
metadata:
| {
status?: number | undefined
headers?: OutgoingHttpHeaders | undefined
}
| undefined
duration: number
}
export type ExportAppResult = {
/**
* Page information keyed by path.
*/
byPath: Map<
string,
{
/**
* The revalidation time for the page in seconds.
*/
revalidate?: number | false
/**
* The metadata for the page.
*/
metadata?: { status?: number; headers?: OutgoingHttpHeaders }
}
>
/**
* Durations for each page in milliseconds.
*/
byPage: Map<string, { durationsByPath: Map<string, number> }>
/**
* The paths that were not found during SSG.
*/
ssgNotFoundPaths: Set<string>
}
export type ExportAppWorker = (
dir: string,
options: ExportAppOptions,
span: Span
) => Promise<ExportAppResult | null>
import type { FontConfig } from '../server/font-utils'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { import type {
ExportPageInput,
ExportPageResult, ExportPageResult,
ExportRouteResult,
ExportedPageFile,
FileWriter,
WorkerRenderOpts, WorkerRenderOpts,
WorkerRenderOptsPartial,
} from './types' } from './types'
// Polyfill fetch for the export worker. // Polyfill fetch for the export worker.
...@@ -14,7 +15,7 @@ import '../server/node-environment' ...@@ -14,7 +15,7 @@ import '../server/node-environment'
process.env.NEXT_IS_EXPORT_WORKER = 'true' process.env.NEXT_IS_EXPORT_WORKER = 'true'
import { extname, join, dirname, sep } from 'path' import { extname, join, dirname, sep } from 'path'
import fs from 'fs' import fs from 'fs/promises'
import { loadComponents } from '../server/load-components' import { loadComponents } from '../server/load-components'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic' import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
...@@ -41,39 +42,10 @@ const envConfig = require('../shared/lib/runtime-config.external') ...@@ -41,39 +42,10 @@ const envConfig = require('../shared/lib/runtime-config.external')
nextExport: true, nextExport: true,
} }
type PathMap = ExportPathMap[keyof ExportPathMap] async function exportPageImpl(
input: ExportPageInput,
interface ExportPageInput { fileWriter: FileWriter
path: string ): Promise<ExportRouteResult | undefined> {
pathMap: PathMap
distDir: string
outDir: string
pagesDataDir: string
renderOpts: WorkerRenderOptsPartial
ampValidatorPath?: string
trailingSlash?: boolean
buildExport?: boolean
serverRuntimeConfig: { [key: string]: any }
subFolders?: boolean
optimizeFonts: FontConfig
optimizeCss: any
disableOptimizedLoading: any
parentSpanId: any
httpAgentOptions: NextConfigComplete['httpAgentOptions']
debugOutput?: boolean
isrMemoryCacheSize?: NextConfigComplete['experimental']['isrMemoryCacheSize']
fetchCache?: boolean
incrementalCacheHandlerPath?: string
fetchCacheKeyPrefix?: string
nextConfigOutput?: NextConfigComplete['output']
enableExperimentalReact?: boolean
}
export interface ExportPageResults extends ExportPageResult {
duration: number
}
async function exportPageImpl(input: ExportPageInput) {
const { const {
path, path,
pathMap, pathMap,
...@@ -242,7 +214,7 @@ async function exportPageImpl(input: ExportPageInput) { ...@@ -242,7 +214,7 @@ async function exportPageImpl(input: ExportPageInput) {
const baseDir = join(outDir, dirname(htmlFilename)) const baseDir = join(outDir, dirname(htmlFilename))
let htmlFilepath = join(outDir, htmlFilename) let htmlFilepath = join(outDir, htmlFilename)
await fs.promises.mkdir(baseDir, { recursive: true }) await fs.mkdir(baseDir, { recursive: true })
// If the fetch cache was enabled, we need to create an incremental // If the fetch cache was enabled, we need to create an incremental
// cache instance for this page. // cache instance for this page.
...@@ -265,7 +237,8 @@ async function exportPageImpl(input: ExportPageInput) { ...@@ -265,7 +237,8 @@ async function exportPageImpl(input: ExportPageInput) {
page, page,
incrementalCache, incrementalCache,
distDir, distDir,
htmlFilepath htmlFilepath,
fileWriter
) )
} }
...@@ -310,7 +283,8 @@ async function exportPageImpl(input: ExportPageInput) { ...@@ -310,7 +283,8 @@ async function exportPageImpl(input: ExportPageInput) {
htmlFilepath, htmlFilepath,
debugOutput, debugOutput,
isDynamicError, isDynamicError,
isAppPrefetch isAppPrefetch,
fileWriter
) )
} }
...@@ -331,7 +305,8 @@ async function exportPageImpl(input: ExportPageInput) { ...@@ -331,7 +305,8 @@ async function exportPageImpl(input: ExportPageInput) {
isDynamic, isDynamic,
hasOrigQueryValues, hasOrigQueryValues,
renderOpts, renderOpts,
components components,
fileWriter
) )
} catch (err) { } catch (err) {
console.error( console.error(
...@@ -345,21 +320,48 @@ async function exportPageImpl(input: ExportPageInput) { ...@@ -345,21 +320,48 @@ async function exportPageImpl(input: ExportPageInput) {
export default async function exportPage( export default async function exportPage(
input: ExportPageInput input: ExportPageInput
): Promise<ExportPageResults> { ): Promise<ExportPageResult | undefined> {
// Configure the http agent. // Configure the http agent.
setHttpClientAndAgentOptions({ setHttpClientAndAgentOptions({
httpAgentOptions: input.httpAgentOptions, httpAgentOptions: input.httpAgentOptions,
}) })
const files: ExportedPageFile[] = []
const baseFileWriter: FileWriter = async (
type,
path,
content,
encodingOptions = 'utf-8'
) => {
await fs.mkdir(dirname(path), { recursive: true })
await fs.writeFile(path, content, encodingOptions)
files.push({ type, path })
}
const exportPageSpan = trace('export-page-worker', input.parentSpanId) const exportPageSpan = trace('export-page-worker', input.parentSpanId)
const start = Date.now() const start = Date.now()
// Export the page. // Export the page.
const results = await exportPageSpan.traceAsyncFn(async () => { const result = await exportPageSpan.traceAsyncFn(async () => {
return await exportPageImpl(input) return await exportPageImpl(input, baseFileWriter)
}) })
// Return it's results. // If there was no result, then we can exit early.
return { ...results, duration: Date.now() - start } if (!result) return
// If there was an error, then we can exit early.
if ('error' in result) {
return { error: result.error, duration: Date.now() - start, files: [] }
}
// Otherwise we can return the result.
return {
duration: Date.now() - start,
files,
ampValidations: result.ampValidations,
revalidate: result.revalidate,
metadata: result.metadata,
ssgNotFound: result.ssgNotFound,
}
} }
import { ChildProcess } from 'child_process' import { ChildProcess } from 'child_process'
import { Worker as JestWorker } from 'next/dist/compiled/jest-worker' import { Worker as JestWorker } from 'next/dist/compiled/jest-worker'
import { getNodeOptionsWithoutInspect } from '../server/lib/utils' import { getNodeOptionsWithoutInspect } from '../server/lib/utils'
// We need this as we're using `Promise.withResolvers` which is not available in the node typings
import '../server/node-environment'
type FarmOptions = ConstructorParameters<typeof JestWorker>[1] type FarmOptions = ConstructorParameters<typeof JestWorker>[1]
const RESTARTED = Symbol('restarted') const RESTARTED = Symbol('restarted')
...@@ -13,45 +17,55 @@ const cleanupWorkers = (worker: JestWorker) => { ...@@ -13,45 +17,55 @@ const cleanupWorkers = (worker: JestWorker) => {
} }
} }
export class Worker { type Options<T extends object = object> = FarmOptions & {
private _worker: JestWorker | undefined timeout?: number
onRestart?: (method: string, args: any[], attempts: number) => void
exposedMethods: ReadonlyArray<keyof T>
enableWorkerThreads?: boolean
}
export class Worker<T extends object = object> {
private _worker?: JestWorker
constructor( /**
* Creates a new worker with the correct typings associated with the selected
* methods.
*/
public static create<T extends object>(
workerPath: string, workerPath: string,
options: FarmOptions & { options: Options<T>
timeout?: number ): Worker<T> & T {
onRestart?: (method: string, args: any[], attempts: number) => void return new Worker(workerPath, options) as Worker<T> & T
exposedMethods: ReadonlyArray<string> }
enableWorkerThreads?: boolean
} constructor(workerPath: string, options: Options<T>) {
) {
let { timeout, onRestart, ...farmOptions } = options let { timeout, onRestart, ...farmOptions } = options
let restartPromise: Promise<typeof RESTARTED> let restartPromise: Promise<typeof RESTARTED>
let resolveRestartPromise: (arg: typeof RESTARTED) => void let resolveRestartPromise: (arg: typeof RESTARTED) => void
let activeTasks = 0 let activeTasks = 0
this._worker = undefined
const createWorker = () => { const createWorker = () => {
this._worker = new JestWorker(workerPath, { const worker = new JestWorker(workerPath, {
...farmOptions, ...farmOptions,
forkOptions: { forkOptions: {
...farmOptions.forkOptions, ...farmOptions.forkOptions,
env: { env: {
...((farmOptions.forkOptions?.env || {}) as any), ...farmOptions.forkOptions?.env,
...process.env, ...process.env,
// we don't pass down NODE_OPTIONS as it can // We don't pass down NODE_OPTIONS as it can lead to extra memory
// extra memory usage // usage,
NODE_OPTIONS: getNodeOptionsWithoutInspect() NODE_OPTIONS: getNodeOptionsWithoutInspect()
.replace(/--max-old-space-size=[\d]{1,}/, '') .replace(/--max-old-space-size=[\d]{1,}/, '')
.trim(), .trim(),
} as any, },
stdio: 'inherit',
}, },
}) as JestWorker })
restartPromise = new Promise(
(resolve) => (resolveRestartPromise = resolve) const { promise, resolve } = Promise.withResolvers<typeof RESTARTED>()
) restartPromise = promise
resolveRestartPromise = resolve
/** /**
* Jest Worker has two worker types, ChildProcessWorker (uses child_process) and NodeThreadWorker (uses worker_threads) * Jest Worker has two worker types, ChildProcessWorker (uses child_process) and NodeThreadWorker (uses worker_threads)
...@@ -63,11 +77,14 @@ export class Worker { ...@@ -63,11 +77,14 @@ export class Worker {
* But this property is not available in NodeThreadWorker, so we need to check if we are using ChildProcessWorker * But this property is not available in NodeThreadWorker, so we need to check if we are using ChildProcessWorker
*/ */
if (!farmOptions.enableWorkerThreads) { if (!farmOptions.enableWorkerThreads) {
for (const worker of ((this._worker as any)._workerPool?._workers || const poolWorkers: { _child?: ChildProcess }[] =
[]) as { // @ts-expect-error - we're accessing a private property
_child?: ChildProcess worker._workerPool?._workers ?? []
}[]) {
worker._child?.on('exit', (code, signal) => { for (const poolWorker of poolWorkers) {
if (!poolWorker._child) continue
poolWorker._child.once('exit', (code, signal) => {
// log unexpected exit if .end() wasn't called // log unexpected exit if .end() wasn't called
if ((code || (signal && signal !== 'SIGINT')) && this._worker) { if ((code || (signal && signal !== 'SIGINT')) && this._worker) {
console.error( console.error(
...@@ -78,16 +95,22 @@ export class Worker { ...@@ -78,16 +95,22 @@ export class Worker {
} }
} }
this._worker.getStdout().pipe(process.stdout) return worker
this._worker.getStderr().pipe(process.stderr)
} }
createWorker()
// Create the first worker.
this._worker = createWorker()
const onHanging = () => { const onHanging = () => {
const worker = this._worker const worker = this._worker
if (!worker) return if (!worker) return
// Grab the current restart promise, and create a new worker.
const resolve = resolveRestartPromise const resolve = resolveRestartPromise
createWorker() this._worker = createWorker()
// Once the old worker is ended, resolve the restart promise to signal to
// any active tasks that the worker had to be restarted.
worker.end().then(() => { worker.end().then(() => {
resolve(RESTARTED) resolve(RESTARTED)
}) })
...@@ -96,33 +119,63 @@ export class Worker { ...@@ -96,33 +119,63 @@ export class Worker {
let hangingTimer: NodeJS.Timeout | false = false let hangingTimer: NodeJS.Timeout | false = false
const onActivity = () => { const onActivity = () => {
// If there was an active hanging timer, clear it.
if (hangingTimer) clearTimeout(hangingTimer) if (hangingTimer) clearTimeout(hangingTimer)
hangingTimer = activeTasks > 0 && setTimeout(onHanging, timeout)
// If there are no active tasks, we don't need to start a new hanging
// timer.
if (activeTasks === 0) return
hangingTimer = setTimeout(onHanging, timeout)
} }
for (const method of farmOptions.exposedMethods) { const wrapMethodWithTimeout =
if (method.startsWith('_')) continue <M extends (...args: unknown[]) => Promise<unknown> | unknown>(
;(this as any)[method] = timeout method: M
? // eslint-disable-next-line no-loop-func ) =>
async (...args: any[]) => { async (...args: Parameters<M>) => {
activeTasks++ activeTasks++
try {
let attempts = 0 try {
for (;;) { let attempts = 0
onActivity() for (;;) {
const result = await Promise.race([ // Mark that we're doing work, we want to ensure that if the worker
(this._worker as any)[method](...args), // halts for any reason, we restart it.
restartPromise, onActivity()
])
if (result !== RESTARTED) return result const result = await Promise.race([
if (onRestart) onRestart(method, args, ++attempts) // Either we'll get the result from the worker, or we'll get the
} // restart promise to fire.
} finally { method(...args),
activeTasks-- restartPromise,
onActivity() ])
// If the result anything besides `RESTARTED`, we can return it, as
// it's the actual result from the worker.
if (result !== RESTARTED) {
return result
} }
// Otherwise, we'll need to restart the worker, and try again.
if (onRestart) onRestart(method.name, args, ++attempts)
} }
: (this._worker as any)[method].bind(this._worker) } finally {
activeTasks--
onActivity()
}
}
for (const name of farmOptions.exposedMethods) {
if (name.startsWith('_')) continue
// @ts-expect-error - we're grabbing a dynamic method on the worker
let method = this._worker[name].bind(this._worker)
if (timeout) {
method = wrapMethodWithTimeout(method)
}
// @ts-expect-error - we're dynamically creating methods
this[name] = method
} }
} }
......
...@@ -10,7 +10,6 @@ import type { ...@@ -10,7 +10,6 @@ import type {
RenderOpts, RenderOpts,
Segment, Segment,
} from './types' } from './types'
import type { StaticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external' import type { StaticGenerationAsyncStorage } from '../../client/components/static-generation-async-storage.external'
import type { StaticGenerationBailout } from '../../client/components/static-generation-bailout' import type { StaticGenerationBailout } from '../../client/components/static-generation-bailout'
import type { RequestAsyncStorage } from '../../client/components/request-async-storage.external' import type { RequestAsyncStorage } from '../../client/components/request-async-storage.external'
......
...@@ -7,7 +7,8 @@ import type { Params } from '../shared/lib/router/utils/route-matcher' ...@@ -7,7 +7,8 @@ import type { Params } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig, NextConfigComplete } from './config-shared' import type { NextConfig, NextConfigComplete } from './config-shared'
import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta' import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { RenderOpts, RenderOptsPartial } from './render' import type { RenderOptsPartial as PagesRenderOptsPartial } from './render'
import type { RenderOptsPartial as AppRenderOptsPartial } from './app-render/types'
import type { ResponseCacheBase, ResponseCacheEntry } from './response-cache' import type { ResponseCacheBase, ResponseCacheEntry } from './response-cache'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import { import {
...@@ -37,6 +38,7 @@ import type { ...@@ -37,6 +38,7 @@ import type {
AppRouteRouteHandlerContext, AppRouteRouteHandlerContext,
AppRouteRouteModule, AppRouteRouteModule,
} from './future/route-modules/app-route/module' } from './future/route-modules/app-route/module'
import type { Server as HTTPServer } from 'http'
import { format as formatUrl, parse as parseUrl } from 'url' import { format as formatUrl, parse as parseUrl } from 'url'
import { formatHostname } from './lib/format-hostname' import { formatHostname } from './lib/format-hostname'
...@@ -192,11 +194,57 @@ export interface Options { ...@@ -192,11 +194,57 @@ export interface Options {
/** /**
* The HTTP Server that Next.js is running behind * The HTTP Server that Next.js is running behind
*/ */
httpServer?: import('http').Server httpServer?: HTTPServer
isNodeDebugging?: 'brk' | boolean isNodeDebugging?: 'brk' | boolean
} }
export type RenderOpts = PagesRenderOptsPartial & AppRenderOptsPartial
export type LoadedRenderOpts = RenderOpts & LoadComponentsReturnType
type BaseRenderOpts = {
deploymentId?: string
poweredByHeader: boolean
buildId: string
generateEtags: boolean
runtimeConfig?: { [key: string]: any }
assetPrefix?: string
canonicalBase: string
dev?: boolean
previewProps: __ApiPreviewProps
customServer?: boolean
ampOptimizerConfig?: { [key: string]: any }
basePath: string
optimizeFonts: FontConfig
images: ImageConfigComplete
fontManifest?: FontManifest
disableOptimizedLoading?: boolean
optimizeCss: any
nextConfigOutput: 'standalone' | 'export'
nextScriptWorkers: any
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocale[]
distDir: string
runtime?: ServerRuntime
serverComponents?: boolean
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined
supportsDynamicHTML?: boolean
isBot?: boolean
clientReferenceManifest?: ClientReferenceManifest
serverActionsBodySizeLimit?: SizeLimit
serverActionsManifest?: any
nextFontManifest?: NextFontManifest
renderServerComponentData?: boolean
serverComponentProps?: any
largePageDataBytes?: number
appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean
isExperimentalCompile?: boolean
}
export interface BaseRequestHandler { export interface BaseRequestHandler {
( (
req: BaseNextRequest, req: BaseNextRequest,
...@@ -210,7 +258,7 @@ export type RequestContext = { ...@@ -210,7 +258,7 @@ export type RequestContext = {
res: BaseNextResponse res: BaseNextResponse
pathname: string pathname: string
query: NextParsedUrlQuery query: NextParsedUrlQuery
renderOpts: RenderOptsPartial renderOpts: RenderOpts
} }
export type FallbackMode = false | undefined | 'blocking' | 'static' export type FallbackMode = false | undefined | 'blocking' | 'static'
...@@ -249,47 +297,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -249,47 +297,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected readonly appPathsManifest?: PagesManifest protected readonly appPathsManifest?: PagesManifest
protected readonly buildId: string protected readonly buildId: string
protected readonly minimalMode: boolean protected readonly minimalMode: boolean
protected readonly renderOpts: { protected readonly renderOpts: BaseRenderOpts
deploymentId?: string
poweredByHeader: boolean
buildId: string
generateEtags: boolean
runtimeConfig?: { [key: string]: any }
assetPrefix?: string
canonicalBase: string
dev?: boolean
previewProps: __ApiPreviewProps
customServer?: boolean
ampOptimizerConfig?: { [key: string]: any }
basePath: string
optimizeFonts: FontConfig
images: ImageConfigComplete
fontManifest?: FontManifest
disableOptimizedLoading?: boolean
optimizeCss: any
nextConfigOutput: 'standalone' | 'export'
nextScriptWorkers: any
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocale[]
distDir: string
runtime?: ServerRuntime
serverComponents?: boolean
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined
supportsDynamicHTML?: boolean
isBot?: boolean
clientReferenceManifest?: ClientReferenceManifest
serverActionsBodySizeLimit?: SizeLimit
serverActionsManifest?: any
nextFontManifest?: NextFontManifest
renderServerComponentData?: boolean
serverComponentProps?: any
largePageDataBytes?: number
appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean
isExperimentalCompile?: boolean
}
protected readonly serverOptions: Readonly<ServerOptions> protected readonly serverOptions: Readonly<ServerOptions>
protected readonly appPathRoutes?: Record<string, string[]> protected readonly appPathRoutes?: Record<string, string[]>
protected readonly clientReferenceManifest?: ClientReferenceManifest protected readonly clientReferenceManifest?: ClientReferenceManifest
...@@ -348,7 +356,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -348,7 +356,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
res: BaseNextResponse, res: BaseNextResponse,
pathname: string, pathname: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: RenderOpts renderOpts: LoadedRenderOpts
): Promise<RenderResult> ): Promise<RenderResult>
protected abstract getPrefetchRsc(pathname: string): Promise<string | null> protected abstract getPrefetchRsc(pathname: string): Promise<string | null>
...@@ -1624,6 +1632,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1624,6 +1632,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
let hasFallback = false let hasFallback = false
const isDynamic = isDynamicRoute(components.page) const isDynamic = isDynamicRoute(components.page)
const prerenderManifest = this.getPrerenderManifest()
if (isAppPath && isDynamic) { if (isAppPath && isDynamic) {
const pathsResult = await this.getStaticPaths({ const pathsResult = await this.getStaticPaths({
pathname, pathname,
...@@ -1666,8 +1676,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1666,8 +1676,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) { ) {
isSSG = true isSSG = true
} else if (!this.renderOpts.dev) { } else if (!this.renderOpts.dev) {
const manifest = this.getPrerenderManifest() isSSG ||=
isSSG = isSSG || !!manifest.routes[pathname === '/index' ? '/' : pathname] !!prerenderManifest.routes[pathname === '/index' ? '/' : pathname]
} }
// Toggle whether or not this is a Data request // Toggle whether or not this is a Data request
...@@ -1982,7 +1992,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1982,7 +1992,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
query: origQuery, query: origQuery,
}) })
const renderOpts: RenderOpts = { const renderOpts: LoadedRenderOpts = {
...components, ...components,
...opts, ...opts,
...(isAppPath ...(isAppPath
...@@ -2027,8 +2037,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2027,8 +2037,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const context: AppRouteRouteHandlerContext = { const context: AppRouteRouteHandlerContext = {
params: opts.params, params: opts.params,
prerenderManifest: this.getPrerenderManifest(), prerenderManifest,
staticGenerationContext: { renderOpts: {
originalPathname: components.ComponentMod.originalPathname, originalPathname: components.ComponentMod.originalPathname,
supportsDynamicHTML, supportsDynamicHTML,
incrementalCache, incrementalCache,
...@@ -2044,11 +2054,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2044,11 +2054,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const response = await routeModule.handle(request, context) const response = await routeModule.handle(request, context)
;(req as any).fetchMetrics = ( ;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics
context.staticGenerationContext as any
).fetchMetrics
const cacheTags = (context.staticGenerationContext as any).fetchTags const cacheTags = (context.renderOpts as any).fetchTags
// If the request is for a static response, we can cache it so long // If the request is for a static response, we can cache it so long
// as it's not edge. // as it's not edge.
...@@ -2066,8 +2074,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2066,8 +2074,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
headers['content-type'] = blob.type headers['content-type'] = blob.type
} }
const revalidate = const revalidate = context.renderOpts.store?.revalidate ?? false
context.staticGenerationContext.store?.revalidate ?? false
// Create the cache entry for the response. // Create the cache entry for the response.
const cacheEntry: ResponseCacheEntry = { const cacheEntry: ResponseCacheEntry = {
...@@ -2084,12 +2091,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2084,12 +2091,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
// Send the response now that we have copied it into the cache. // Send the response now that we have copied it into the cache.
await sendResponse( await sendResponse(req, res, response, context.renderOpts.waitUntil)
req,
res,
response,
context.staticGenerationContext.waitUntil
)
return null return null
} catch (err) { } catch (err) {
// If this is during static generation, throw the error again. // If this is during static generation, throw the error again.
......
import type { AppPageRender } from '../../../app-render/app-render'
export const lazyRenderAppPage: AppPageRender = (...args) => {
if (process.env.NEXT_MINIMAL) {
throw new Error("Can't use lazyRenderAppPage in minimal mode")
} else {
const render: AppPageRender =
require('./module.compiled').renderToHTMLOrFlight
return render(...args)
}
}
...@@ -49,7 +49,7 @@ import * as sharedModules from './shared-modules' ...@@ -49,7 +49,7 @@ import * as sharedModules from './shared-modules'
* handler for app routes. * handler for app routes.
*/ */
export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext { export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
staticGenerationContext: StaticGenerationContext['renderOpts'] renderOpts: StaticGenerationContext['renderOpts']
prerenderManifest: PrerenderManifest prerenderManifest: PrerenderManifest
} }
...@@ -260,13 +260,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -260,13 +260,7 @@ export class AppRouteRouteModule extends RouteModule<
// Get the context for the static generation. // Get the context for the static generation.
const staticGenerationContext: StaticGenerationContext = { const staticGenerationContext: StaticGenerationContext = {
urlPathname: request.nextUrl.pathname, urlPathname: request.nextUrl.pathname,
renderOpts: renderOpts: context.renderOpts,
// If the staticGenerationContext is not provided then we default to
// the default values.
context.staticGenerationContext ?? {
supportsDynamicHTML: false,
originalPathname: this.definition.pathname,
},
} }
// Add the fetchCache option to the renderOpts. // Add the fetchCache option to the renderOpts.
...@@ -368,15 +362,15 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -368,15 +362,15 @@ export class AppRouteRouteModule extends RouteModule<
`No response is returned from route handler '${this.resolvedPagePath}'. Ensure you return a \`Response\` or a \`NextResponse\` in all branches of your handler.` `No response is returned from route handler '${this.resolvedPagePath}'. Ensure you return a \`Response\` or a \`NextResponse\` in all branches of your handler.`
) )
} }
;(context.staticGenerationContext as any).fetchMetrics = ;(context.renderOpts as any).fetchMetrics =
staticGenerationStore.fetchMetrics staticGenerationStore.fetchMetrics
context.staticGenerationContext.waitUntil = Promise.all( context.renderOpts.waitUntil = Promise.all(
staticGenerationStore.pendingRevalidates || [] staticGenerationStore.pendingRevalidates || []
) )
addImplicitTags(staticGenerationStore) addImplicitTags(staticGenerationStore)
;(context.staticGenerationContext as any).fetchTags = ;(context.renderOpts as any).fetchTags =
staticGenerationStore.tags?.join(',') staticGenerationStore.tags?.join(',')
// It's possible cookies were set in the handler, so we need // It's possible cookies were set in the handler, so we need
......
import type { PagesRender } from '../../../render'
export const lazyRenderPagesPage: PagesRender = (...args) => {
if (process.env.NEXT_MINIMAL) {
throw new Error("Can't use lazyRenderPagesPage in minimal mode")
} else {
const render: PagesRender = require('./module.compiled').renderToHTML
return render(...args)
}
}
...@@ -60,6 +60,7 @@ import BaseServer, { ...@@ -60,6 +60,7 @@ import BaseServer, {
NoFallbackError, NoFallbackError,
RequestContext, RequestContext,
NormalizedRouteManifest, NormalizedRouteManifest,
LoadedRenderOpts,
} from './base-server' } from './base-server'
import { getMaybePagePath, getPagePath, requireFontManifest } from './require' import { getMaybePagePath, getPagePath, requireFontManifest } from './require'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
...@@ -98,6 +99,8 @@ import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers' ...@@ -98,6 +99,8 @@ import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
import { signalFromNodeResponse } from './web/spec-extension/adapters/next-request' import { signalFromNodeResponse } from './web/spec-extension/adapters/next-request'
import { RouteModuleLoader } from './future/helpers/module-loader/route-module-loader' import { RouteModuleLoader } from './future/helpers/module-loader/route-module-loader'
import { loadManifest } from './load-manifest' import { loadManifest } from './load-manifest'
import { lazyRenderAppPage } from './future/route-modules/app-page/module.render'
import { lazyRenderPagesPage } from './future/route-modules/pages/module.render'
export * from './base-server' export * from './base-server'
...@@ -459,7 +462,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -459,7 +462,7 @@ export default class NextNodeServer extends BaseServer {
res: NodeNextResponse, res: NodeNextResponse,
pathname: string, pathname: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: import('./render').RenderOpts renderOpts: LoadedRenderOpts
): Promise<RenderResult> { ): Promise<RenderResult> {
return getTracer().trace(NextNodeServerSpan.renderHTML, async () => return getTracer().trace(NextNodeServerSpan.renderHTML, async () =>
this.renderHTMLImpl(req, res, pathname, query, renderOpts) this.renderHTMLImpl(req, res, pathname, query, renderOpts)
...@@ -471,11 +474,11 @@ export default class NextNodeServer extends BaseServer { ...@@ -471,11 +474,11 @@ export default class NextNodeServer extends BaseServer {
res: NodeNextResponse, res: NodeNextResponse,
pathname: string, pathname: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: import('./render').RenderOpts renderOpts: LoadedRenderOpts
): Promise<RenderResult> { ): Promise<RenderResult> {
if (process.env.NEXT_MINIMAL) { if (process.env.NEXT_MINIMAL) {
throw new Error( throw new Error(
'invariant: renderHTML should not be called in minimal mode' 'Invariant: renderHTML should not be called in minimal mode'
) )
// the `else` branch is needed for tree-shaking // the `else` branch is needed for tree-shaking
} else { } else {
...@@ -485,9 +488,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -485,9 +488,7 @@ export default class NextNodeServer extends BaseServer {
renderOpts.nextFontManifest = this.nextFontManifest renderOpts.nextFontManifest = this.nextFontManifest
if (this.hasAppDir && renderOpts.isAppPath) { if (this.hasAppDir && renderOpts.isAppPath) {
const { renderToHTMLOrFlight: appRenderToHTMLOrFlight } = return lazyRenderAppPage(
require('./future/route-modules/app-page/module.compiled') as typeof import('./app-render/app-render')
return appRenderToHTMLOrFlight(
req.originalRequest, req.originalRequest,
res.originalResponse, res.originalResponse,
pathname, pathname,
...@@ -499,7 +500,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -499,7 +500,7 @@ export default class NextNodeServer extends BaseServer {
// TODO: re-enable this once we've refactored to use implicit matches // TODO: re-enable this once we've refactored to use implicit matches
// throw new Error('Invariant: render should have used routeModule') // throw new Error('Invariant: render should have used routeModule')
return require('./future/route-modules/pages/module.compiled').renderToHTML( return lazyRenderPagesPage(
req.originalRequest, req.originalRequest,
res.originalResponse, res.originalResponse,
pathname, pathname,
......
import type { WebNextRequest, WebNextResponse } from './base-http/web' import type { WebNextRequest, WebNextResponse } from './base-http/web'
import type { RenderOpts } from './render'
import type RenderResult from './render-result' import type RenderResult from './render-result'
import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta' import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'
import type { Params } from '../shared/lib/router/utils/route-matcher' import type { Params } from '../shared/lib/router/utils/route-matcher'
...@@ -10,6 +9,7 @@ import type { PrerenderManifest } from '../build' ...@@ -10,6 +9,7 @@ import type { PrerenderManifest } from '../build'
import { byteLength } from './api-utils/web' import { byteLength } from './api-utils/web'
import BaseServer, { import BaseServer, {
LoadedRenderOpts,
MiddlewareRoutingItem, MiddlewareRoutingItem,
NoFallbackError, NoFallbackError,
NormalizedRouteManifest, NormalizedRouteManifest,
...@@ -200,7 +200,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -200,7 +200,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
res: WebNextResponse, res: WebNextResponse,
pathname: string, pathname: string,
query: NextParsedUrlQuery, query: NextParsedUrlQuery,
renderOpts: RenderOpts renderOpts: LoadedRenderOpts
): Promise<RenderResult> { ): Promise<RenderResult> {
const { renderToHTML } = this.serverOptions.webServerConfig const { renderToHTML } = this.serverOptions.webServerConfig
if (!renderToHTML) { if (!renderToHTML) {
......
...@@ -106,7 +106,7 @@ export class EdgeRouteModuleWrapper { ...@@ -106,7 +106,7 @@ export class EdgeRouteModuleWrapper {
}, },
notFoundRoutes: [], notFoundRoutes: [],
}, },
staticGenerationContext: { renderOpts: {
supportsDynamicHTML: true, supportsDynamicHTML: true,
}, },
} }
...@@ -114,8 +114,8 @@ export class EdgeRouteModuleWrapper { ...@@ -114,8 +114,8 @@ export class EdgeRouteModuleWrapper {
// Get the response from the handler. // Get the response from the handler.
const res = await this.routeModule.handle(request, context) const res = await this.routeModule.handle(request, context)
if (context.staticGenerationContext.waitUntil) { if (context.renderOpts.waitUntil) {
evt.waitUntil(context.staticGenerationContext.waitUntil) evt.waitUntil(context.renderOpts.waitUntil)
} }
return res return res
} }
......
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