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
...@@ -4,14 +4,15 @@ import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin' ...@@ -4,14 +4,15 @@ import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared' import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin' import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin' import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin'
import type { ExportOptions } from '../export' import type { ExportAppOptions, ExportAppWorker } from '../export/types'
import '../lib/setup-exception-listeners' import '../lib/setup-exception-listeners'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { bold, yellow, green } from '../lib/picocolors' import { bold, yellow, green } from '../lib/picocolors'
import crypto from 'crypto' import crypto from 'crypto'
import { isMatch, makeRe } from 'next/dist/compiled/micromatch' import { isMatch, makeRe } from 'next/dist/compiled/micromatch'
import { promises as fs, existsSync as fsExistsSync } from 'fs' import fs from 'fs/promises'
import os from 'os' import os from 'os'
import { Worker } from '../lib/worker' import { Worker } from '../lib/worker'
import { defaultConfig } from '../server/config-shared' import { defaultConfig } from '../server/config-shared'
...@@ -148,22 +149,31 @@ import { initialize as initializeIncrementalCache } from '../server/lib/incremen ...@@ -148,22 +149,31 @@ import { initialize as initializeIncrementalCache } from '../server/lib/incremen
import { nodeFs } from '../server/lib/node-fs-methods' import { nodeFs } from '../server/lib/node-fs-methods'
import { collectBuildTraces } from './collect-build-traces' import { collectBuildTraces } from './collect-build-traces'
import { BuildTraceContext } from './webpack/plugins/next-trace-entrypoints-plugin' import { BuildTraceContext } from './webpack/plugins/next-trace-entrypoints-plugin'
import { formatManifest } from './manifests/formatter/format-manifest'
interface ExperimentalBypassForInfo {
experimentalBypassFor?: RouteHas[]
}
export type SsgRoute = { interface DataRouteRouteInfo {
dataRoute: string | null
}
export interface SsgRoute
extends ExperimentalBypassForInfo,
DataRouteRouteInfo {
initialRevalidateSeconds: number | false initialRevalidateSeconds: number | false
srcRoute: string | null srcRoute: string | null
dataRoute: string | null
initialStatus?: number initialStatus?: number
initialHeaders?: Record<string, string> initialHeaders?: Record<string, string>
experimentalBypassFor?: RouteHas[]
} }
export type DynamicSsgRoute = { export interface DynamicSsgRoute
extends ExperimentalBypassForInfo,
DataRouteRouteInfo {
routeRegex: string routeRegex: string
fallback: string | null | false fallback: string | null | false
dataRoute: string | null
dataRouteRegex: string | null dataRouteRegex: string | null
experimentalBypassFor?: RouteHas[]
} }
export type PrerenderManifest = { export type PrerenderManifest = {
...@@ -880,7 +890,7 @@ export default async function build( ...@@ -880,7 +890,7 @@ export default async function build(
.traceAsyncFn(() => .traceAsyncFn(() =>
fs.writeFile( fs.writeFile(
routesManifestPath, routesManifestPath,
JSON.stringify(routesManifest), formatManifest(routesManifest),
'utf8' 'utf8'
) )
) )
...@@ -1147,7 +1157,8 @@ export default async function build( ...@@ -1147,7 +1157,8 @@ export default async function build(
}) })
await fs.writeFile( await fs.writeFile(
path.join(distDir, APP_PATH_ROUTES_MANIFEST), path.join(distDir, APP_PATH_ROUTES_MANIFEST),
JSON.stringify(appPathRoutes, null, 2) formatManifest(appPathRoutes),
'utf-8'
) )
} }
...@@ -1172,7 +1183,15 @@ export default async function build( ...@@ -1172,7 +1183,15 @@ export default async function build(
) { ) {
let infoPrinted = false let infoPrinted = false
return new Worker(staticWorkerPath, { return Worker.create<
Pick<
typeof import('./worker'),
| 'hasCustomGetInitialProps'
| 'isPageStatic'
| 'getDefinedNamedExports'
| 'exportPage'
>
>(staticWorkerPath, {
timeout: timeout * 1000, timeout: timeout * 1000,
onRestart: (method, [arg], attempts) => { onRestart: (method, [arg], attempts) => {
if (method === 'exportPage') { if (method === 'exportPage') {
...@@ -1219,14 +1238,7 @@ export default async function build( ...@@ -1219,14 +1238,7 @@ export default async function build(
'getDefinedNamedExports', 'getDefinedNamedExports',
'exportPage', 'exportPage',
], ],
}) as Worker & })
Pick<
typeof import('./worker'),
| 'hasCustomGetInitialProps'
| 'isPageStatic'
| 'getDefinedNamedExports'
| 'exportPage'
>
} }
let CacheHandler: any let CacheHandler: any
...@@ -1809,7 +1821,8 @@ export default async function build( ...@@ -1809,7 +1821,8 @@ export default async function build(
await fs.writeFile( await fs.writeFile(
path.join(distDir, SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST), path.join(distDir, SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST),
JSON.stringify(manifest, null, 2) formatManifest(manifest),
'utf8'
) )
} }
...@@ -1843,7 +1856,7 @@ export default async function build( ...@@ -1843,7 +1856,7 @@ export default async function build(
await fs.writeFile( await fs.writeFile(
routesManifestPath, routesManifestPath,
JSON.stringify(routesManifest), formatManifest(routesManifest),
'utf8' 'utf8'
) )
} }
...@@ -1918,7 +1931,7 @@ export default async function build( ...@@ -1918,7 +1931,7 @@ export default async function build(
await fs.writeFile( await fs.writeFile(
path.join(distDir, SERVER_FILES_MANIFEST), path.join(distDir, SERVER_FILES_MANIFEST),
JSON.stringify(requiredServerFiles), formatManifest(requiredServerFiles),
'utf8' 'utf8'
) )
...@@ -1977,15 +1990,10 @@ export default async function build( ...@@ -1977,15 +1990,10 @@ export default async function build(
ssgPages, ssgPages,
additionalSsgPaths additionalSsgPaths
) )
const exportApp: typeof import('../export').default = const exportApp: ExportAppWorker = require('../export').default
require('../export').default
const exportConfig: NextConfigComplete = { const exportConfig: NextConfigComplete = {
...config, ...config,
initialPageRevalidationMap: {},
initialPageMetaMap: {},
pageDurationMap: {},
ssgNotFoundPaths: [] as string[],
// Default map will be the collection of automatic statically exported // Default map will be the collection of automatic statically exported
// pages and incremental pages. // pages and incremental pages.
// n.b. we cannot handle this above in combinedPages because the dynamic // n.b. we cannot handle this above in combinedPages because the dynamic
...@@ -2107,7 +2115,7 @@ export default async function build( ...@@ -2107,7 +2115,7 @@ export default async function build(
}, },
} }
const exportOptions: ExportOptions = { const exportOptions: ExportAppOptions = {
isInvokedFromCli: false, isInvokedFromCli: false,
nextConfig: exportConfig, nextConfig: exportConfig,
hasAppDir, hasAppDir,
...@@ -2118,19 +2126,26 @@ export default async function build( ...@@ -2118,19 +2126,26 @@ export default async function build(
pages: combinedPages, pages: combinedPages,
outdir: path.join(distDir, 'export'), outdir: path.join(distDir, 'export'),
statusMessage: 'Generating static pages', statusMessage: 'Generating static pages',
exportAppPageWorker: // The worker already explicitly binds `this` to each of the
appStaticWorkers?.exportPage.bind(appStaticWorkers), // exposed methods.
exportPageWorker: exportAppPageWorker: appStaticWorkers?.exportPage,
pagesStaticWorkers.exportPage.bind(pagesStaticWorkers), exportPageWorker: pagesStaticWorkers?.exportPage,
endWorker: async () => { endWorker: async () => {
await pagesStaticWorkers.end() await pagesStaticWorkers.end()
await appStaticWorkers?.end() await appStaticWorkers?.end()
}, },
} }
await exportApp(dir, exportOptions, nextBuildSpan) const exportResult = await exportApp(
dir,
exportOptions,
nextBuildSpan
)
// If there was no result, there's nothing more to do.
if (!exportResult) return
ssgNotFoundPaths = exportConfig.ssgNotFoundPaths ssgNotFoundPaths = Array.from(exportResult.ssgNotFoundPaths)
// remove server bundles that were exported // remove server bundles that were exported
for (const page of staticPages) { for (const page of staticPages) {
...@@ -2143,8 +2158,9 @@ export default async function build( ...@@ -2143,8 +2158,9 @@ export default async function build(
const appConfig = appDefaultConfigs.get(originalAppPath) || {} const appConfig = appDefaultConfigs.get(originalAppPath) || {}
let hasDynamicData = let hasDynamicData =
appConfig.revalidate === 0 || appConfig.revalidate === 0 ||
exportConfig.initialPageRevalidationMap[page] === 0 exportResult.byPath.get(page)?.revalidate === 0
// TODO: (wyattjoh) maybe change behavior for postpone?
if (hasDynamicData && pageInfos.get(page)?.static) { if (hasDynamicData && pageInfos.get(page)?.static) {
// if the page was marked as being static, but it contains dynamic data // if the page was marked as being static, but it contains dynamic data
// (ie, in the case of a static generation bailout), then it should be marked dynamic // (ie, in the case of a static generation bailout), then it should be marked dynamic
...@@ -2172,22 +2188,10 @@ export default async function build( ...@@ -2172,22 +2188,10 @@ export default async function build(
if (isDynamicRoute(page) && route === page) return if (isDynamicRoute(page) && route === page) return
if (route === '/_not-found') return if (route === '/_not-found') return
let revalidate = exportConfig.initialPageRevalidationMap[route] const {
revalidate = appConfig.revalidate ?? false,
if (typeof revalidate === 'undefined') { metadata = {},
revalidate = } = exportResult.byPath.get(route) ?? {}
typeof appConfig.revalidate !== 'undefined'
? appConfig.revalidate
: false
}
// ensure revalidate is normalized correctly
if (
typeof revalidate !== 'number' &&
typeof revalidate !== 'boolean'
) {
revalidate = false
}
if (revalidate !== 0) { if (revalidate !== 0) {
const normalizedRoute = normalizePagePath(route) const normalizedRoute = normalizePagePath(route)
...@@ -2197,15 +2201,11 @@ export default async function build( ...@@ -2197,15 +2201,11 @@ export default async function build(
const routeMeta: Partial<SsgRoute> = {} const routeMeta: Partial<SsgRoute> = {}
const exportRouteMeta: { if (metadata.status !== 200) {
status?: number routeMeta.initialStatus = metadata.status
headers?: Record<string, string>
} = exportConfig.initialPageMetaMap[route] || {}
if (exportRouteMeta.status !== 200) {
routeMeta.initialStatus = exportRouteMeta.status
} }
const exportHeaders = exportRouteMeta.headers
const exportHeaders = metadata.headers
const headerKeys = Object.keys(exportHeaders || {}) const headerKeys = Object.keys(exportHeaders || {})
if (exportHeaders && headerKeys.length) { if (exportHeaders && headerKeys.length) {
...@@ -2439,15 +2439,22 @@ export default async function build( ...@@ -2439,15 +2439,22 @@ export default async function build(
const file = normalizePagePath(page) const file = normalizePagePath(page)
const pageInfo = pageInfos.get(page) const pageInfo = pageInfos.get(page)
const durationInfo = exportConfig.pageDurationMap[page] const durationInfo = exportResult.byPage.get(page)
if (pageInfo && durationInfo) { if (pageInfo && durationInfo) {
// Set Build Duration // Set Build Duration
if (pageInfo.ssgPageRoutes) { if (pageInfo.ssgPageRoutes) {
pageInfo.ssgPageDurations = pageInfo.ssgPageRoutes.map( pageInfo.ssgPageDurations = pageInfo.ssgPageRoutes.map(
(pagePath) => durationInfo[pagePath] (pagePath) => {
const duration = durationInfo.durationsByPath.get(pagePath)
if (typeof duration === 'undefined') {
throw new Error("Invariant: page wasn't built")
}
return duration
}
) )
} }
pageInfo.pageDuration = durationInfo[page] pageInfo.pageDuration = durationInfo.durationsByPath.get(page)
} }
// The dynamic version of SSG pages are only prerendered if the // The dynamic version of SSG pages are only prerendered if the
...@@ -2481,7 +2488,8 @@ export default async function build( ...@@ -2481,7 +2488,8 @@ export default async function build(
finalPrerenderRoutes[localePage] = { finalPrerenderRoutes[localePage] = {
initialRevalidateSeconds: initialRevalidateSeconds:
exportConfig.initialPageRevalidationMap[localePage], exportResult.byPath.get(localePage)?.revalidate ??
false,
srcRoute: null, srcRoute: null,
dataRoute: path.posix.join( dataRoute: path.posix.join(
'/_next/data', '/_next/data',
...@@ -2493,7 +2501,7 @@ export default async function build( ...@@ -2493,7 +2501,7 @@ export default async function build(
} else { } else {
finalPrerenderRoutes[page] = { finalPrerenderRoutes[page] = {
initialRevalidateSeconds: initialRevalidateSeconds:
exportConfig.initialPageRevalidationMap[page], exportResult.byPath.get(page)?.revalidate ?? false,
srcRoute: null, srcRoute: null,
dataRoute: path.posix.join( dataRoute: path.posix.join(
'/_next/data', '/_next/data',
...@@ -2505,7 +2513,7 @@ export default async function build( ...@@ -2505,7 +2513,7 @@ export default async function build(
// Set Page Revalidation Interval // Set Page Revalidation Interval
if (pageInfo) { if (pageInfo) {
pageInfo.initialRevalidateSeconds = pageInfo.initialRevalidateSeconds =
exportConfig.initialPageRevalidationMap[page] exportResult.byPath.get(page)?.revalidate ?? false
} }
} else { } else {
// For a dynamic SSG page, we did not copy its data exports and only // For a dynamic SSG page, we did not copy its data exports and only
...@@ -2552,9 +2560,15 @@ export default async function build( ...@@ -2552,9 +2560,15 @@ export default async function build(
) )
} }
const initialRevalidateSeconds =
exportResult.byPath.get(route)?.revalidate ?? false
if (typeof initialRevalidateSeconds === 'undefined') {
throw new Error("Invariant: page wasn't built")
}
finalPrerenderRoutes[route] = { finalPrerenderRoutes[route] = {
initialRevalidateSeconds: initialRevalidateSeconds,
exportConfig.initialPageRevalidationMap[route],
srcRoute: page, srcRoute: page,
dataRoute: path.posix.join( dataRoute: path.posix.join(
'/_next/data', '/_next/data',
...@@ -2565,8 +2579,7 @@ export default async function build( ...@@ -2565,8 +2579,7 @@ export default async function build(
// Set route Revalidation Interval // Set route Revalidation Interval
if (pageInfo) { if (pageInfo) {
pageInfo.initialRevalidateSeconds = pageInfo.initialRevalidateSeconds = initialRevalidateSeconds
exportConfig.initialPageRevalidationMap[route]
} }
} }
} }
...@@ -2577,7 +2590,7 @@ export default async function build( ...@@ -2577,7 +2590,7 @@ export default async function build(
await fs.rm(exportOptions.outdir, { recursive: true, force: true }) await fs.rm(exportOptions.outdir, { recursive: true, force: true })
await fs.writeFile( await fs.writeFile(
manifestPath, manifestPath,
JSON.stringify(pagesManifest, null, 2), formatManifest(pagesManifest),
'utf8' 'utf8'
) )
}) })
...@@ -2669,7 +2682,7 @@ export default async function build( ...@@ -2669,7 +2682,7 @@ export default async function build(
await fs.writeFile( await fs.writeFile(
path.join(distDir, PRERENDER_MANIFEST), path.join(distDir, PRERENDER_MANIFEST),
JSON.stringify(prerenderManifest), formatManifest(prerenderManifest),
'utf8' 'utf8'
) )
await fs.writeFile( await fs.writeFile(
...@@ -2694,7 +2707,7 @@ export default async function build( ...@@ -2694,7 +2707,7 @@ export default async function build(
} }
await fs.writeFile( await fs.writeFile(
path.join(distDir, PRERENDER_MANIFEST), path.join(distDir, PRERENDER_MANIFEST),
JSON.stringify(prerenderManifest), formatManifest(prerenderManifest),
'utf8' 'utf8'
) )
await fs.writeFile( await fs.writeFile(
...@@ -2721,7 +2734,7 @@ export default async function build( ...@@ -2721,7 +2734,7 @@ export default async function build(
await fs.writeFile( await fs.writeFile(
path.join(distDir, IMAGES_MANIFEST), path.join(distDir, IMAGES_MANIFEST),
JSON.stringify({ formatManifest({
version: 1, version: 1,
images, images,
}), }),
...@@ -2729,7 +2742,7 @@ export default async function build( ...@@ -2729,7 +2742,7 @@ export default async function build(
) )
await fs.writeFile( await fs.writeFile(
path.join(distDir, EXPORT_MARKER), path.join(distDir, EXPORT_MARKER),
JSON.stringify({ formatManifest({
version: 1, version: 1,
hasExportPathMap: typeof config.exportPathMap === 'function', hasExportPathMap: typeof config.exportPathMap === 'function',
exportTrailingSlash: config.trailingSlash === true, exportTrailingSlash: config.trailingSlash === true,
...@@ -2788,7 +2801,7 @@ export default async function build( ...@@ -2788,7 +2801,7 @@ export default async function build(
incrementalCacheIpcValidationKey incrementalCacheIpcValidationKey
) )
const options: ExportOptions = { const options: ExportAppOptions = {
isInvokedFromCli: false, isInvokedFromCli: false,
buildExport: false, buildExport: false,
nextConfig: config, nextConfig: config,
...@@ -2796,8 +2809,10 @@ export default async function build( ...@@ -2796,8 +2809,10 @@ export default async function build(
silent: true, silent: true,
threads: config.experimental.cpus, threads: config.experimental.cpus,
outdir: path.join(dir, configOutDir), outdir: path.join(dir, configOutDir),
exportAppPageWorker: appWorker.exportPage.bind(appWorker), // The worker already explicitly binds `this` to each of the
exportPageWorker: pagesWorker.exportPage.bind(pagesWorker), // exposed methods.
exportAppPageWorker: appWorker?.exportPage,
exportPageWorker: pagesWorker?.exportPage,
endWorker: async () => { endWorker: async () => {
await pagesWorker.end() await pagesWorker.end()
await appWorker.end() await appWorker.end()
...@@ -2867,7 +2882,7 @@ export default async function build( ...@@ -2867,7 +2882,7 @@ export default async function build(
SERVER_DIRECTORY, SERVER_DIRECTORY,
'app' 'app'
) )
if (fsExistsSync(originalServerApp)) { if (await fileExists(originalServerApp)) {
await recursiveCopy( await recursiveCopy(
originalServerApp, originalServerApp,
path.join( path.join(
......
/**
* 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'),
......
import type { WorkerRenderOptsPartial } from './types' import type {
ExportAppResult,
ExportAppOptions,
ExportWorker,
WorkerRenderOptsPartial,
} from './types'
import type { PrerenderManifest } from '../build'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { bold, yellow } from '../lib/picocolors' import { bold, yellow } from '../lib/picocolors'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { import fs from 'fs/promises'
promises,
existsSync,
exists as existsOrig,
readFileSync,
writeFileSync,
} from 'fs'
import '../server/require-hook' import '../server/require-hook'
import { Worker } from '../lib/worker' import { Worker } from '../lib/worker'
import { dirname, join, resolve, sep } from 'path' import { dirname, join, resolve, sep } from 'path'
import { promisify } from 'util'
import { AmpPageStatus, formatAmpMessages } from '../build/output/index' import { AmpPageStatus, formatAmpMessages } 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'
...@@ -43,8 +43,6 @@ import { Telemetry } from '../telemetry/storage' ...@@ -43,8 +43,6 @@ import { Telemetry } from '../telemetry/storage'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import { PrerenderManifest } from '../build'
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { isAPIRoute } from '../lib/is-api-route' import { isAPIRoute } from '../lib/is-api-route'
import { getPagePath } from '../server/require' import { getPagePath } from '../server/require'
import { Span } from '../trace' import { Span } from '../trace'
...@@ -54,8 +52,8 @@ import { isAppRouteRoute } from '../lib/is-app-route-route' ...@@ -54,8 +52,8 @@ import { isAppRouteRoute } from '../lib/is-app-route-route'
import { isAppPageRoute } from '../lib/is-app-page-route' import { isAppPageRoute } from '../lib/is-app-page-route'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { needsExperimentalReact } from '../lib/needs-experimental-react' import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { fileExists } from '../lib/file-exists'
const exists = promisify(existsOrig) import { formatManifest } from '../build/manifests/formatter/format-manifest'
function divideSegments(number: number, segments: number): number[] { function divideSegments(number: number, segments: number): number[] {
const result = [] const result = []
...@@ -148,746 +146,764 @@ export class ExportError extends Error { ...@@ -148,746 +146,764 @@ export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR' code = 'NEXT_EXPORT_ERROR'
} }
export interface ExportOptions { type ExportWorkers = {
outdir: string pages: ExportWorker
isInvokedFromCli: boolean app?: ExportWorker
hasAppDir: boolean end: () => Promise<void>
silent?: boolean
threads?: number
debugOutput?: boolean
pages?: string[]
buildExport: boolean
statusMessage?: string
exportPageWorker?: typeof import('./worker').default
exportAppPageWorker?: typeof import('./worker').default
endWorker?: () => Promise<void>
nextConfig?: NextConfigComplete
hasOutdirFromCli?: boolean
} }
export default async function exportApp( function setupWorkers(
dir: string, options: ExportAppOptions,
options: ExportOptions, nextConfig: NextConfigComplete
span: Span ): ExportWorkers {
): Promise<void> { if (options.exportPageWorker) {
const nextExportSpan = span.traceChild('next-export') return {
pages: options.exportPageWorker,
app: options.exportAppPageWorker,
end: options.endWorker || (() => Promise.resolve()),
}
}
return nextExportSpan.traceAsyncFn(async () => { const threads = options.threads || nextConfig.experimental.cpus
dir = resolve(dir) if (!options.silent && !options.buildExport) {
Log.info(`Launching ${threads} workers`)
// attempt to load global env values so they are available in next.config.js }
nextExportSpan
.traceChild('load-dotenv') const timeout = nextConfig?.staticPageGenerationTimeout || 0
.traceFn(() => loadEnvConfig(dir, false, Log))
let infoPrinted = false
const nextConfig =
options.nextConfig || const worker = Worker.create<typeof import('./worker')>(
(await nextExportSpan require.resolve('./worker'),
.traceChild('load-next-config') {
.traceAsyncFn(() => loadConfig(PHASE_EXPORT, dir))) timeout: timeout * 1000,
onRestart: (_method, [{ path }], attempts) => {
const threads = options.threads || nextConfig.experimental.cpus if (attempts >= 3) {
const distDir = join(dir, nextConfig.distDir)
const isExportOutput = nextConfig.output === 'export'
// Running 'next export'
if (options.isInvokedFromCli) {
if (isExportOutput) {
if (options.hasOutdirFromCli) {
throw new ExportError( throw new ExportError(
'"next export -o <dir>" cannot be used when "output: export" is configured in next.config.js. Instead add "distDir" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export' `Static page generation for ${path} is still timing out after 3 attempts. See more info here https://nextjs.org/docs/messages/static-page-generation-timeout`
) )
} }
Log.warn( Log.warn(
'"next export" is no longer needed when "output: export" is configured in next.config.js https://nextjs.org/docs/advanced-features/static-html-export' `Restarted static page generation for ${path} because it took more than ${timeout} seconds`
) )
return if (!infoPrinted) {
} Log.warn(
if (existsSync(join(distDir, 'server', 'app'))) { 'See more info here https://nextjs.org/docs/messages/static-page-generation-timeout'
)
infoPrinted = true
}
},
maxRetries: 0,
numWorkers: threads,
enableWorkerThreads: nextConfig.experimental.workerThreads,
exposedMethods: ['default'],
}
)
return {
pages: worker.default,
end: async () => {
await worker.end()
},
}
}
export async function exportAppImpl(
dir: string,
options: Readonly<ExportAppOptions>,
span: Span
): Promise<ExportAppResult | null> {
dir = resolve(dir)
// attempt to load global env values so they are available in next.config.js
span.traceChild('load-dotenv').traceFn(() => loadEnvConfig(dir, false, Log))
const nextConfig =
options.nextConfig ||
(await span
.traceChild('load-next-config')
.traceAsyncFn(() => loadConfig(PHASE_EXPORT, dir)))
const distDir = join(dir, nextConfig.distDir)
const isExportOutput = nextConfig.output === 'export'
// Running 'next export'
if (options.isInvokedFromCli) {
if (isExportOutput) {
if (options.hasOutdirFromCli) {
throw new ExportError( throw new ExportError(
'"next export" does not work with App Router. Please use "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export' '"next export -o <dir>" cannot be used when "output: export" is configured in next.config.js. Instead add "distDir" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
) )
} }
Log.warn( Log.warn(
'"next export" is deprecated in favor of "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export' '"next export" is no longer needed when "output: export" is configured in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
) )
return null
} }
// Running 'next export' or output is set to 'export' if (await fileExists(join(distDir, 'server', 'app'))) {
if (options.isInvokedFromCli || isExportOutput) { throw new ExportError(
if (nextConfig.experimental.serverActions) { '"next export" does not work with App Router. Please use "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
throw new ExportError( )
`Server Actions are not supported with static export.`
)
}
} }
Log.warn(
'"next export" is deprecated in favor of "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
)
}
const telemetry = options.buildExport ? null : new Telemetry({ distDir }) // Running 'next export' or output is set to 'export'
if (options.isInvokedFromCli || isExportOutput) {
if (telemetry) { if (nextConfig.experimental.serverActions) {
telemetry.record( throw new ExportError(
eventCliSession(distDir, nextConfig, { `Server Actions are not supported with static export.`
webpackVersion: null,
cliCommand: 'export',
isSrcDir: null,
hasNowJson: !!(await findUp('now.json', { cwd: dir })),
isCustomServer: null,
turboFlag: false,
pagesDir: null,
appDir: null,
})
) )
} }
}
const subFolders = nextConfig.trailingSlash && !options.buildExport const telemetry = options.buildExport ? null : new Telemetry({ distDir })
if (telemetry) {
telemetry.record(
eventCliSession(distDir, nextConfig, {
webpackVersion: null,
cliCommand: 'export',
isSrcDir: null,
hasNowJson: !!(await findUp('now.json', { cwd: dir })),
isCustomServer: null,
turboFlag: false,
pagesDir: null,
appDir: null,
})
)
}
if (!options.silent && !options.buildExport) { const subFolders = nextConfig.trailingSlash && !options.buildExport
Log.info(`using build directory: ${distDir}`)
}
const buildIdFile = join(distDir, BUILD_ID_FILE) if (!options.silent && !options.buildExport) {
Log.info(`using build directory: ${distDir}`)
}
if (!existsSync(buildIdFile)) { const buildIdFile = join(distDir, BUILD_ID_FILE)
throw new ExportError(
`Could not find a production build in the '${distDir}' directory. Try building your app with 'next build' before starting the static export. https://nextjs.org/docs/messages/next-export-no-build-id`
)
}
const customRoutesDetected = ['rewrites', 'redirects', 'headers'].filter( if (!(await fileExists(buildIdFile))) {
(config) => typeof nextConfig[config] === 'function' throw new ExportError(
`Could not find a production build in the '${distDir}' directory. Try building your app with 'next build' before starting the static export. https://nextjs.org/docs/messages/next-export-no-build-id`
) )
}
const customRoutes = ['rewrites', 'redirects', 'headers'].filter(
(config) => typeof nextConfig[config] === 'function'
)
if (!hasNextSupport && !options.buildExport && customRoutes.length > 0) {
Log.warn(
`rewrites, redirects, and headers are not applied when exporting your application, detected (${customRoutes.join(
', '
)}). See more info here: https://nextjs.org/docs/messages/export-no-custom-routes`
)
}
const buildId = await fs.readFile(buildIdFile, 'utf8')
const pagesManifest =
!options.pages &&
(require(join(distDir, SERVER_DIRECTORY, PAGES_MANIFEST)) as PagesManifest)
let prerenderManifest: PrerenderManifest | undefined
try {
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
} catch {}
let appRoutePathManifest: Record<string, string> | undefined
try {
appRoutePathManifest = require(join(distDir, APP_PATH_ROUTES_MANIFEST))
} catch (err) {
if ( if (
!hasNextSupport && isError(err) &&
!options.buildExport && (err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND')
customRoutesDetected.length > 0
) { ) {
Log.warn( // the manifest doesn't exist which will happen when using
`rewrites, redirects, and headers are not applied when exporting your application, detected (${customRoutesDetected.join( // "pages" dir instead of "app" dir.
', ' appRoutePathManifest = undefined
)}). See more info here: https://nextjs.org/docs/messages/export-no-custom-routes` } else {
) // the manifest is malformed (invalid json)
throw err
} }
}
const buildId = readFileSync(buildIdFile, 'utf8') const excludedPrerenderRoutes = new Set<string>()
const pagesManifest = const pages = options.pages || Object.keys(pagesManifest)
!options.pages && const defaultPathMap: ExportPathMap = {}
(require(join(
distDir,
SERVER_DIRECTORY,
PAGES_MANIFEST
)) as PagesManifest)
let prerenderManifest: PrerenderManifest | undefined = undefined let hasApiRoutes = false
try { for (const page of pages) {
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST)) // _document and _app are not real pages
} catch {} // _error is exported as 404.html later on
// API Routes are Node.js functions
let appRoutePathManifest: Record<string, string> | undefined = undefined if (isAPIRoute(page)) {
try { hasApiRoutes = true
appRoutePathManifest = require(join(distDir, APP_PATH_ROUTES_MANIFEST)) continue
} catch (err) { }
if (page === '/_document' || page === '/_app' || page === '/_error') {
continue
}
// iSSG pages that are dynamic should not export templated version by
// default. In most cases, this would never work. There is no server that
// could run `getStaticProps`. If users make their page work lazily, they
// can manually add it to the `exportPathMap`.
if (prerenderManifest?.dynamicRoutes[page]) {
excludedPrerenderRoutes.add(page)
continue
}
defaultPathMap[page] = { page }
}
const mapAppRouteToPage = new Map<string, string>()
if (!options.buildExport && appRoutePathManifest) {
for (const [pageName, routePath] of Object.entries(appRoutePathManifest)) {
mapAppRouteToPage.set(routePath, pageName)
if ( if (
isError(err) && isAppPageRoute(pageName) &&
(err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND') !prerenderManifest?.routes[routePath] &&
!prerenderManifest?.dynamicRoutes[routePath]
) { ) {
// the manifest doesn't exist which will happen when using defaultPathMap[routePath] = {
// "pages" dir instead of "app" dir. page: pageName,
appRoutePathManifest = undefined _isAppDir: true,
} else { }
// the manifest is malformed (invalid json)
throw err
} }
} }
}
const excludedPrerenderRoutes = new Set<string>() // Initialize the output directory
const pages = options.pages || Object.keys(pagesManifest) const outDir = options.outdir
const defaultPathMap: ExportPathMap = {}
let hasApiRoutes = false
for (const page of pages) { if (outDir === join(dir, 'public')) {
// _document and _app are not real pages throw new ExportError(
// _error is exported as 404.html later on `The 'public' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-public`
// API Routes are Node.js functions )
}
if (isAPIRoute(page)) { if (outDir === join(dir, 'static')) {
hasApiRoutes = true throw new ExportError(
continue `The 'static' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-static`
} )
}
if (page === '/_document' || page === '/_app' || page === '/_error') { await fs.rm(outDir, { recursive: true, force: true })
continue await fs.mkdir(join(outDir, '_next', buildId), { recursive: true })
}
await fs.writeFile(
join(distDir, EXPORT_DETAIL),
formatManifest({
version: 1,
outDirectory: outDir,
success: false,
}),
'utf8'
)
// Copy static directory
if (!options.buildExport && (await fileExists(join(dir, 'static')))) {
if (!options.silent) {
Log.info('Copying "static" directory')
}
await span
.traceChild('copy-static-directory')
.traceAsyncFn(() =>
recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
)
}
// iSSG pages that are dynamic should not export templated version by // Copy .next/static directory
// default. In most cases, this would never work. There is no server that if (
// could run `getStaticProps`. If users make their page work lazily, they !options.buildExport &&
// can manually add it to the `exportPathMap`. (await fileExists(join(distDir, CLIENT_STATIC_FILES_PATH)))
if (prerenderManifest?.dynamicRoutes[page]) { ) {
excludedPrerenderRoutes.add(page) if (!options.silent) {
continue Log.info('Copying "static build" directory')
} }
await span
.traceChild('copy-next-static-directory')
.traceAsyncFn(() =>
recursiveCopy(
join(distDir, CLIENT_STATIC_FILES_PATH),
join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
)
)
}
defaultPathMap[page] = { page } // Get the exportPathMap from the config file
if (typeof nextConfig.exportPathMap !== 'function') {
nextConfig.exportPathMap = async (defaultMap) => {
return defaultMap
} }
}
const mapAppRouteToPage = new Map<string, string>() const {
if (!options.buildExport && appRoutePathManifest) { i18n,
for (const [pageName, routePath] of Object.entries( images: { loader = 'default', unoptimized },
appRoutePathManifest } = nextConfig
)) {
mapAppRouteToPage.set(routePath, pageName)
if (
isAppPageRoute(pageName) &&
!prerenderManifest?.routes[routePath] &&
!prerenderManifest?.dynamicRoutes[routePath]
) {
defaultPathMap[routePath] = {
page: pageName,
_isAppDir: true,
}
}
}
}
// Initialize the output directory if (i18n && !options.buildExport) {
const outDir = options.outdir throw new ExportError(
`i18n support is not compatible with next export. See here for more info on deploying: https://nextjs.org/docs/messages/export-no-custom-routes`
)
}
if (outDir === join(dir, 'public')) { if (!options.buildExport) {
throw new ExportError( const { isNextImageImported } = await span
`The 'public' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-public` .traceChild('is-next-image-imported')
.traceAsyncFn(() =>
fs
.readFile(join(distDir, EXPORT_MARKER), 'utf8')
.then((text) => JSON.parse(text))
.catch(() => ({}))
) )
}
if (outDir === join(dir, 'static')) { if (
isNextImageImported &&
loader === 'default' &&
!unoptimized &&
!hasNextSupport
) {
throw new ExportError( throw new ExportError(
`The 'static' directory is reserved in Next.js and can not be used as the export out directory. https://nextjs.org/docs/messages/can-not-output-to-static` `Image Optimization using the default loader is not compatible with export.
Possible solutions:
- Use \`next start\` to run a server, which includes the Image Optimization API.
- Configure \`images.unoptimized = true\` in \`next.config.js\` to disable the Image Optimization API.
Read more: https://nextjs.org/docs/messages/export-image-api`
) )
} }
}
await promises.rm(outDir, { recursive: true, force: true }) // Start the rendering process
await promises.mkdir(join(outDir, '_next', buildId), { recursive: true }) const renderOpts: WorkerRenderOptsPartial = {
previewProps: prerenderManifest?.preview,
writeFileSync( buildId,
join(distDir, EXPORT_DETAIL), nextExport: true,
JSON.stringify({ assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
version: 1, distDir,
outDirectory: outDir, dev: false,
success: false, basePath: nextConfig.basePath,
}), canonicalBase: nextConfig.amp?.canonicalBase || '',
'utf8' ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
) ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
locales: i18n?.locales,
locale: i18n?.defaultLocale,
defaultLocale: i18n?.defaultLocale,
domainLocales: i18n?.domains,
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading,
// Exported pages do not currently support dynamic HTML.
supportsDynamicHTML: false,
crossOrigin: nextConfig.crossOrigin || '',
optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
optimizeFonts: nextConfig.optimizeFonts as FontConfig,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverComponents: options.hasAppDir,
serverActionsBodySizeLimit:
nextConfig.experimental.serverActionsBodySizeLimit,
nextFontManifest: require(join(
distDir,
'server',
`${NEXT_FONT_MANIFEST}.json`
)),
images: nextConfig.images,
...(options.hasAppDir
? {
serverActionsManifest: require(join(
distDir,
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json'
)),
}
: {}),
strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId,
}
// Copy static directory const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
if (!options.buildExport && existsSync(join(dir, 'static'))) {
if (!options.silent) { if (Object.keys(publicRuntimeConfig).length > 0) {
Log.info('Copying "static" directory') ;(renderOpts as any).runtimeConfig = publicRuntimeConfig
} }
await nextExportSpan
.traceChild('copy-static-directory') // We need this for server rendering the Link component.
.traceAsyncFn(() => ;(globalThis as any).__NEXT_DATA__ = {
recursiveCopy(join(dir, 'static'), join(outDir, 'static')) nextExport: true,
) }
const exportPathMap = await span
.traceChild('run-export-path-map')
.traceAsyncFn(async () => {
const exportMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false,
dir,
outDir,
distDir,
buildId,
})
return exportMap
})
// only add missing 404 page when `buildExport` is false
if (!options.buildExport) {
// only add missing /404 if not specified in `exportPathMap`
if (!exportPathMap['/404']) {
exportPathMap['/404'] = { page: '/_error' }
} }
// Copy .next/static directory /**
if ( * exports 404.html for backwards compat
!options.buildExport && * E.g. GitHub Pages, GitLab Pages, Cloudflare Pages, Netlify
existsSync(join(distDir, CLIENT_STATIC_FILES_PATH)) */
) { if (!exportPathMap['/404.html']) {
if (!options.silent) { // alias /404.html to /404 to be compatible with custom 404 / _error page
Log.info('Copying "static build" directory') exportPathMap['/404.html'] = exportPathMap['/404']
}
await nextExportSpan
.traceChild('copy-next-static-directory')
.traceAsyncFn(() =>
recursiveCopy(
join(distDir, CLIENT_STATIC_FILES_PATH),
join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
)
)
} }
}
// make sure to prevent duplicates
const exportPaths = [
...new Set(
Object.keys(exportPathMap).map((path) =>
denormalizePagePath(normalizePagePath(path))
)
),
]
const filteredPaths = exportPaths.filter(
// Remove API routes
(route) =>
exportPathMap[route]._isAppDir || !isAPIRoute(exportPathMap[route].page)
)
if (filteredPaths.length !== exportPaths.length) {
hasApiRoutes = true
}
if (filteredPaths.length === 0) {
return null
}
if (prerenderManifest && !options.buildExport) {
const fallbackEnabledPages = new Set()
for (const path of Object.keys(exportPathMap)) {
const page = exportPathMap[path].page
const prerenderInfo = prerenderManifest.dynamicRoutes[page]
// Get the exportPathMap from the config file if (prerenderInfo && prerenderInfo.fallback !== false) {
if (typeof nextConfig.exportPathMap !== 'function') { fallbackEnabledPages.add(page)
nextConfig.exportPathMap = async (defaultMap) => {
return defaultMap
} }
} }
const { if (fallbackEnabledPages.size > 0) {
i18n,
images: { loader = 'default', unoptimized },
} = nextConfig
if (i18n && !options.buildExport) {
throw new ExportError( throw new ExportError(
`i18n support is not compatible with next export. See here for more info on deploying: https://nextjs.org/docs/messages/export-no-custom-routes` `Found pages with \`fallback\` enabled:\n${[
...fallbackEnabledPages,
].join('\n')}\n${SSG_FALLBACK_EXPORT_ERROR}\n`
) )
} }
}
let hasMiddleware = false
if (!options.buildExport) { if (!options.buildExport) {
const { isNextImageImported } = await nextExportSpan try {
.traceChild('is-next-image-imported') const middlewareManifest = require(join(
.traceAsyncFn(() => distDir,
promises SERVER_DIRECTORY,
.readFile(join(distDir, EXPORT_MARKER), 'utf8') MIDDLEWARE_MANIFEST
.then((text) => JSON.parse(text)) )) as MiddlewareManifest
.catch(() => ({}))
)
if ( hasMiddleware = Object.keys(middlewareManifest.middleware).length > 0
isNextImageImported && } catch {}
loader === 'default' &&
!unoptimized && // Warn if the user defines a path for an API page
!hasNextSupport if (hasApiRoutes || hasMiddleware) {
) { if (!options.silent) {
throw new ExportError( Log.warn(
`Image Optimization using the default loader is not compatible with export. yellow(
Possible solutions: `Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`
- Use \`next start\` to run a server, which includes the Image Optimization API. ) +
- Configure \`images.unoptimized = true\` in \`next.config.js\` to disable the Image Optimization API. `\n` +
Read more: https://nextjs.org/docs/messages/export-image-api` yellow(
`This command is meant for static-only hosts, and is` +
' ' +
bold(`not necessary to make your application static.`)
) +
`\n` +
yellow(
`Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`
) +
`\n` +
yellow(
`Learn more: https://nextjs.org/docs/messages/api-routes-static-export`
)
) )
} }
} }
}
// Start the rendering process const progress =
const renderOpts: WorkerRenderOptsPartial = { !options.silent &&
previewProps: prerenderManifest?.preview, createProgress(
buildId, filteredPaths.length,
nextExport: true, `${options.statusMessage || 'Exporting'}`
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''), )
distDir, const pagesDataDir = options.buildExport
dev: false, ? outDir
basePath: nextConfig.basePath, : join(outDir, '_next/data', buildId)
canonicalBase: nextConfig.amp?.canonicalBase || '',
ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false, const ampValidations: AmpPageStatus = {}
ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
locales: i18n?.locales, const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
locale: i18n?.defaultLocale, // Copy public directory
defaultLocale: i18n?.defaultLocale, if (!options.buildExport && (await fileExists(publicDir))) {
domainLocales: i18n?.domains, if (!options.silent) {
disableOptimizedLoading: nextConfig.experimental.disableOptimizedLoading, Log.info('Copying "public" directory')
// Exported pages do not currently support dynamic HTML. }
supportsDynamicHTML: false, await span.traceChild('copy-public-directory').traceAsyncFn(() =>
crossOrigin: nextConfig.crossOrigin || '', recursiveCopy(publicDir, outDir, {
optimizeCss: nextConfig.experimental.optimizeCss, filter(path) {
nextConfigOutput: nextConfig.output, // Exclude paths used by pages
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers, return !exportPathMap[path]
optimizeFonts: nextConfig.optimizeFonts as FontConfig, },
largePageDataBytes: nextConfig.experimental.largePageDataBytes, })
serverComponents: options.hasAppDir, )
serverActionsBodySizeLimit: }
nextConfig.experimental.serverActionsBodySizeLimit,
nextFontManifest: require(join(
distDir,
'server',
`${NEXT_FONT_MANIFEST}.json`
)),
images: nextConfig.images,
...(options.hasAppDir
? {
serverActionsManifest: require(join(
distDir,
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json'
)),
}
: {}),
strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId,
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const workers = setupWorkers(options, nextConfig)
if (Object.keys(publicRuntimeConfig).length > 0) { const results = await Promise.all(
;(renderOpts as any).runtimeConfig = publicRuntimeConfig filteredPaths.map(async (path) => {
} const pathMap = exportPathMap[path]
const exportPage = workers[pathMap._isAppDir ? 'app' : 'pages']
if (!exportPage) {
throw new Error(
'Invariant: Undefined export worker for app dir, this is a bug in Next.js.'
)
}
// We need this for server rendering the Link component. const pageExportSpan = span.traceChild('export-page')
;(globalThis as any).__NEXT_DATA__ = { pageExportSpan.setAttribute('path', path)
nextExport: true,
}
if (!options.silent && !options.buildExport) { const result = await pageExportSpan.traceAsyncFn(async () => {
Log.info(`Launching ${threads} workers`) return await exportPage({
} path,
const exportPathMap = await nextExportSpan pathMap,
.traceChild('run-export-path-map')
.traceAsyncFn(async () => {
const exportMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false,
dir,
outDir,
distDir, distDir,
buildId, outDir,
pagesDataDir,
renderOpts,
ampValidatorPath: nextConfig.experimental.amp?.validator || undefined,
trailingSlash: nextConfig.trailingSlash,
serverRuntimeConfig,
subFolders,
buildExport: options.buildExport,
optimizeFonts: nextConfig.optimizeFonts as FontConfig,
optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading:
nextConfig.experimental.disableOptimizedLoading,
parentSpanId: pageExportSpan.id,
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
isrMemoryCacheSize: nextConfig.experimental.isrMemoryCacheSize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
incrementalCacheHandlerPath:
nextConfig.experimental.incrementalCacheHandlerPath,
enableExperimentalReact: needsExperimentalReact(nextConfig),
}) })
return exportMap
}) })
// only add missing 404 page when `buildExport` is false if (progress) progress()
if (!options.buildExport) {
// only add missing /404 if not specified in `exportPathMap`
if (!exportPathMap['/404']) {
exportPathMap['/404'] = { page: '/_error' }
}
/** return { result, path }
* exports 404.html for backwards compat })
* E.g. GitHub Pages, GitLab Pages, Cloudflare Pages, Netlify )
*/
if (!exportPathMap['/404.html']) {
// alias /404.html to /404 to be compatible with custom 404 / _error page
exportPathMap['/404.html'] = exportPathMap['/404']
}
}
// make sure to prevent duplicates const errorPaths: string[] = []
const exportPaths = [ let renderError = false
...new Set( let hadValidationError = false
Object.keys(exportPathMap).map((path) =>
denormalizePagePath(normalizePagePath(path))
)
),
]
const filteredPaths = exportPaths.filter( const collector: ExportAppResult = {
// Remove API routes byPath: new Map(),
(route) => byPage: new Map(),
exportPathMap[route]._isAppDir || !isAPIRoute(exportPathMap[route].page) ssgNotFoundPaths: new Set(),
) }
if (filteredPaths.length !== exportPaths.length) { for (const { result, path } of results) {
hasApiRoutes = true if (!result) continue
}
const { page } = exportPathMap[path]
if (filteredPaths.length === 0) { // Capture any render errors.
return if ('error' in result) {
renderError = true
errorPaths.push(page !== path ? `${page}: ${path}` : path)
continue
} }
if (prerenderManifest && !options.buildExport) { // Capture any amp validations.
const fallbackEnabledPages = new Set() if (result.ampValidations) {
for (const validation of result.ampValidations) {
ampValidations[validation.page] = validation.result
hadValidationError ||= validation.result.errors.length > 0
}
}
for (const path of Object.keys(exportPathMap)) { if (options.buildExport) {
const page = exportPathMap[path].page // Update path info by path.
const prerenderInfo = prerenderManifest.dynamicRoutes[page] const info = collector.byPath.get(path) ?? {}
if (typeof result.revalidate !== 'undefined') {
info.revalidate = result.revalidate
}
if (typeof result.metadata !== 'undefined') {
info.metadata = result.metadata
}
collector.byPath.set(path, info)
if (prerenderInfo && prerenderInfo.fallback !== false) { // Update not found.
fallbackEnabledPages.add(page) if (result.ssgNotFound === true) {
} collector.ssgNotFoundPaths.add(path)
} }
if (fallbackEnabledPages.size) { // Update durations.
throw new ExportError( const durations = collector.byPage.get(page) ?? {
`Found pages with \`fallback\` enabled:\n${[ durationsByPath: new Map<string, number>(),
...fallbackEnabledPages,
].join('\n')}\n${SSG_FALLBACK_EXPORT_ERROR}\n`
)
} }
durations.durationsByPath.set(path, result.duration)
collector.byPage.set(page, durations)
} }
let hasMiddleware = false }
if (!options.buildExport) {
try {
const middlewareManifest = require(join(
distDir,
SERVER_DIRECTORY,
MIDDLEWARE_MANIFEST
)) as MiddlewareManifest
hasMiddleware = Object.keys(middlewareManifest.middleware).length > 0 const endWorkerPromise = workers.end()
} catch {}
// Warn if the user defines a path for an API page // copy prerendered routes to outDir
if (hasApiRoutes || hasMiddleware) { if (!options.buildExport && prerenderManifest) {
if (!options.silent) { await Promise.all(
Log.warn( Object.keys(prerenderManifest.routes).map(async (route) => {
yellow( const { srcRoute } = prerenderManifest!.routes[route]
`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.` const appPageName = mapAppRouteToPage.get(srcRoute || '')
) + const pageName = appPageName || srcRoute || route
`\n` + const isAppPath = Boolean(appPageName)
yellow( const isAppRouteHandler = appPageName && isAppRouteRoute(appPageName)
`This command is meant for static-only hosts, and is` +
' ' + // returning notFound: true from getStaticProps will not
bold(`not necessary to make your application static.`) // output html/json files during the build
) + if (prerenderManifest!.notFoundRoutes.includes(route)) {
`\n` + return
yellow(
`Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`
) +
`\n` +
yellow(
`Learn more: https://nextjs.org/docs/messages/api-routes-static-export`
)
)
} }
} route = normalizePagePath(route)
}
const pagePath = getPagePath(pageName, distDir, undefined, isAppPath)
const distPagesDir = join(
pagePath,
// strip leading / and then recurse number of nested dirs
// to place from base folder
pageName
.slice(1)
.split('/')
.map(() => '..')
.join('/')
)
const progress = const orig = join(distPagesDir, route)
!options.silent && const handlerSrc = `${orig}.body`
createProgress( const handlerDest = join(outDir, route)
filteredPaths.length,
`${options.statusMessage || 'Exporting'}`
)
const pagesDataDir = options.buildExport
? outDir
: join(outDir, '_next/data', buildId)
const ampValidations: AmpPageStatus = {} if (isAppRouteHandler && (await fileExists(handlerSrc))) {
let hadValidationError = false await fs.mkdir(dirname(handlerDest), { recursive: true })
await fs.copyFile(handlerSrc, handlerDest)
return
}
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH) const htmlDest = join(
// Copy public directory outDir,
if (!options.buildExport && existsSync(publicDir)) { `${route}${
if (!options.silent) { subFolders && route !== '/index' ? `${sep}index` : ''
Log.info('Copying "public" directory') }.html`
}
await nextExportSpan
.traceChild('copy-public-directory')
.traceAsyncFn(() =>
recursiveCopy(publicDir, outDir, {
filter(path) {
// Exclude paths used by pages
return !exportPathMap[path]
},
})
) )
} const ampHtmlDest = join(
outDir,
const timeout = nextConfig?.staticPageGenerationTimeout || 0 `${route}.amp${subFolders ? `${sep}index` : ''}.html`
let infoPrinted = false )
let exportPage: typeof import('./worker').default const jsonDest = isAppPath
let exportAppPage: undefined | typeof import('./worker').default ? join(
let endWorker: () => Promise<void> outDir,
if (options.exportPageWorker) { `${route}${
exportPage = options.exportPageWorker subFolders && route !== '/index' ? `${sep}index` : ''
exportAppPage = options.exportAppPageWorker }.txt`
endWorker = options.endWorker || (() => Promise.resolve())
} else {
const worker = new Worker(require.resolve('./worker'), {
timeout: timeout * 1000,
onRestart: (_method, [{ path }], attempts) => {
if (attempts >= 3) {
throw new ExportError(
`Static page generation for ${path} is still timing out after 3 attempts. See more info here https://nextjs.org/docs/messages/static-page-generation-timeout`
)
}
Log.warn(
`Restarted static page generation for ${path} because it took more than ${timeout} seconds`
)
if (!infoPrinted) {
Log.warn(
'See more info here https://nextjs.org/docs/messages/static-page-generation-timeout'
) )
infoPrinted = true : join(pagesDataDir, `${route}.json`)
}
},
maxRetries: 0,
numWorkers: threads,
enableWorkerThreads: nextConfig.experimental.workerThreads,
exposedMethods: ['default'],
}) as Worker & typeof import('./worker')
exportPage = worker.default.bind(worker)
endWorker = async () => {
await worker.end()
}
}
let renderError = false await fs.mkdir(dirname(htmlDest), { recursive: true })
const errorPaths: string[] = [] await fs.mkdir(dirname(jsonDest), { recursive: true })
await Promise.all( const htmlSrc = `${orig}.html`
filteredPaths.map(async (path) => { const jsonSrc = `${orig}${isAppPath ? '.rsc' : '.json'}`
const pageExportSpan = nextExportSpan.traceChild('export-page')
pageExportSpan.setAttribute('path', path) await fs.copyFile(htmlSrc, htmlDest)
await fs.copyFile(jsonSrc, jsonDest)
return pageExportSpan.traceAsyncFn(async () => {
const pathMap = exportPathMap[path] if (await fileExists(`${orig}.amp.html`)) {
const exportPageOrApp = pathMap._isAppDir ? exportAppPage : exportPage await fs.mkdir(dirname(ampHtmlDest), { recursive: true })
if (!exportPageOrApp) { await fs.copyFile(`${orig}.amp.html`, ampHtmlDest)
throw new Error( }
'invariant: Undefined export worker for app dir, this is a bug in Next.js.'
)
}
const result = await exportPageOrApp({
path,
pathMap,
distDir,
outDir,
pagesDataDir,
renderOpts,
ampValidatorPath:
nextConfig.experimental.amp?.validator || undefined,
trailingSlash: nextConfig.trailingSlash,
serverRuntimeConfig,
subFolders,
buildExport: options.buildExport,
optimizeFonts: nextConfig.optimizeFonts as FontConfig,
optimizeCss: nextConfig.experimental.optimizeCss,
disableOptimizedLoading:
nextConfig.experimental.disableOptimizedLoading,
parentSpanId: pageExportSpan.id,
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
isrMemoryCacheSize: nextConfig.experimental.isrMemoryCacheSize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
incrementalCacheHandlerPath:
nextConfig.experimental.incrementalCacheHandlerPath,
enableExperimentalReact: needsExperimentalReact(nextConfig),
})
if (result.ampValidations) {
for (const validation of result.ampValidations) {
const { page, result: ampValidationResult } = validation
ampValidations[page] = ampValidationResult
hadValidationError =
hadValidationError ||
(Array.isArray(ampValidationResult?.errors) &&
ampValidationResult.errors.length > 0)
}
}
renderError = renderError || !!result.error
if (!!result.error) {
const { page } = pathMap
errorPaths.push(page !== path ? `${page}: ${path}` : path)
}
if (options.buildExport) {
if (typeof result.fromBuildExportRevalidate !== 'undefined') {
nextConfig.initialPageRevalidationMap[path] =
result.fromBuildExportRevalidate
}
if (typeof result.fromBuildExportMeta !== 'undefined') {
nextConfig.initialPageMetaMap[path] = result.fromBuildExportMeta
}
if (result.ssgNotFound === true) {
nextConfig.ssgNotFoundPaths.push(path)
}
const durations = (nextConfig.pageDurationMap[pathMap.page] =
nextConfig.pageDurationMap[pathMap.page] || {})
durations[path] = result.duration
}
if (progress) progress()
})
}) })
) )
}
const endWorkerPromise = endWorker() if (Object.keys(ampValidations).length) {
console.log(formatAmpMessages(ampValidations))
// copy prerendered routes to outDir }
if (!options.buildExport && prerenderManifest) { if (hadValidationError) {
await Promise.all( throw new ExportError(
Object.keys(prerenderManifest.routes).map(async (route) => { `AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation`
const { srcRoute } = prerenderManifest!.routes[route] )
const appPageName = mapAppRouteToPage.get(srcRoute || '') }
const pageName = appPageName || srcRoute || route
const isAppPath = Boolean(appPageName)
const isAppRouteHandler = appPageName && isAppRouteRoute(appPageName)
// returning notFound: true from getStaticProps will not
// output html/json files during the build
if (prerenderManifest!.notFoundRoutes.includes(route)) {
return
}
route = normalizePagePath(route)
const pagePath = getPagePath(pageName, distDir, undefined, isAppPath)
const distPagesDir = join(
pagePath,
// strip leading / and then recurse number of nested dirs
// to place from base folder
pageName
.slice(1)
.split('/')
.map(() => '..')
.join('/')
)
const orig = join(distPagesDir, route) if (renderError) {
const handlerSrc = `${orig}.body` throw new ExportError(
const handlerDest = join(outDir, route) `Export encountered errors on following paths:\n\t${errorPaths
.sort()
if (isAppRouteHandler && (await exists(handlerSrc))) { .join('\n\t')}`
await promises.mkdir(dirname(handlerDest), { recursive: true }) )
await promises.copyFile(handlerSrc, handlerDest) }
return
}
const htmlDest = join(
outDir,
`${route}${
subFolders && route !== '/index' ? `${sep}index` : ''
}.html`
)
const ampHtmlDest = join(
outDir,
`${route}.amp${subFolders ? `${sep}index` : ''}.html`
)
const jsonDest = isAppPath
? join(
outDir,
`${route}${
subFolders && route !== '/index' ? `${sep}index` : ''
}.txt`
)
: join(pagesDataDir, `${route}.json`)
await promises.mkdir(dirname(htmlDest), { recursive: true })
await promises.mkdir(dirname(jsonDest), { recursive: true })
const htmlSrc = `${orig}.html`
const jsonSrc = `${orig}${isAppPath ? '.rsc' : '.json'}`
await promises.copyFile(htmlSrc, htmlDest)
await promises.copyFile(jsonSrc, jsonDest)
if (await exists(`${orig}.amp.html`)) {
await promises.mkdir(dirname(ampHtmlDest), { recursive: true })
await promises.copyFile(`${orig}.amp.html`, ampHtmlDest)
}
})
)
}
if (Object.keys(ampValidations).length) { await fs.writeFile(
console.log(formatAmpMessages(ampValidations)) join(distDir, EXPORT_DETAIL),
} formatManifest({
if (hadValidationError) { version: 1,
throw new ExportError( outDirectory: outDir,
`AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation` success: true,
) }),
} 'utf8'
)
if (telemetry) {
await telemetry.flush()
}
if (renderError) { await endWorkerPromise
throw new ExportError(
`Export encountered errors on following paths:\n\t${errorPaths
.sort()
.join('\n\t')}`
)
}
writeFileSync( return collector
join(distDir, EXPORT_DETAIL), }
JSON.stringify({
version: 1,
outDirectory: outDir,
success: true,
}),
'utf8'
)
if (telemetry) { export default async function exportApp(
await telemetry.flush() dir: string,
} options: ExportAppOptions,
span: Span
): Promise<ExportAppResult | null> {
const nextExportSpan = span.traceChild('next-export')
await endWorkerPromise return nextExportSpan.traceAsyncFn(async () => {
return await exportAppImpl(dir, options, nextExportSpan)
}) })
} }
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