index.ts 50.3 KB
Newer Older
1 2
import { loadEnvConfig } from '@next/env'
import chalk from 'chalk'
J
Joe Haddad 已提交
3
import crypto from 'crypto'
4
import { promises, writeFileSync } from 'fs'
S
Shu Ding 已提交
5
import { Worker } from 'jest-worker'
G
devalue  
Guy Bedford 已提交
6
import devalue from 'next/dist/compiled/devalue'
G
Guy Bedford 已提交
7
import escapeStringRegexp from 'next/dist/compiled/escape-string-regexp'
G
find-up  
Guy Bedford 已提交
8
import findUp from 'next/dist/compiled/find-up'
9
import { nanoid } from 'next/dist/compiled/nanoid/index.cjs'
G
Guy Bedford 已提交
10
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
J
Joe Haddad 已提交
11
import path from 'path'
J
Joe Haddad 已提交
12
import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages'
13
import {
14
  STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR,
15
  PUBLIC_DIR_MIDDLEWARE_CONFLICT,
16
} from '../lib/constants'
17
import { fileExists } from '../lib/file-exists'
J
Joe Haddad 已提交
18
import { findPagesDir } from '../lib/find-pages-dir'
19 20
import loadCustomRoutes, {
  getRedirectStatus,
21
  normalizeRouteRegex,
22 23 24
  Redirect,
  RouteType,
} from '../lib/load-custom-routes'
25
import { nonNullable } from '../lib/non-nullable'
J
Joe Haddad 已提交
26 27
import { recursiveDelete } from '../lib/recursive-delete'
import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup'
28
import {
29
  BUILD_ID_FILE,
30
  BUILD_MANIFEST,
J
Joe Haddad 已提交
31
  CLIENT_STATIC_FILES_PATH,
J
Joe Haddad 已提交
32 33
  EXPORT_DETAIL,
  EXPORT_MARKER,
34
  FONT_MANIFEST,
S
Steven 已提交
35
  IMAGES_MANIFEST,
J
Joe Haddad 已提交
36
  PAGES_MANIFEST,
37
  PHASE_PRODUCTION_BUILD,
38
  PRERENDER_MANIFEST,
39
  REACT_LOADABLE_MANIFEST,
40
  ROUTES_MANIFEST,
41
  SERVERLESS_DIRECTORY,
J
Joe Haddad 已提交
42
  SERVER_DIRECTORY,
43
  SERVER_FILES_MANIFEST,
44
  STATIC_STATUS_PAGES,
45
} from '../next-server/lib/constants'
46 47 48
import {
  getRouteRegex,
  getSortedRoutes,
49
  isDynamicRoute,
50
} from '../next-server/lib/router/utils'
J
Joe Haddad 已提交
51
import { __ApiPreviewProps } from '../next-server/server/api-utils'
52 53
import loadConfig, {
  isTargetLikeServerless,
54
} from '../next-server/server/config'
55
import { BuildManifest } from '../next-server/server/get-page-files'
56
import '../next-server/server/node-polyfill-fetch'
J
Joe Haddad 已提交
57
import { normalizePagePath } from '../next-server/server/normalize-page-path'
58
import { getPagePath } from '../next-server/server/require'
J
Joe Haddad 已提交
59
import * as ciEnvironment from '../telemetry/ci-info'
J
Joe Haddad 已提交
60
import {
61
  eventBuildCompleted,
J
Joe Haddad 已提交
62
  eventBuildOptimize,
63
  eventCliSession,
J
Joe Haddad 已提交
64
  eventNextPlugins,
J
Joe Haddad 已提交
65
} from '../telemetry/events'
J
Joe Haddad 已提交
66
import { Telemetry } from '../telemetry/storage'
67 68
import { CompilerResult, runCompiler } from './compiler'
import { createEntrypoints, createPagesMapping } from './entries'
69 70
import { generateBuildId } from './generate-build-id'
import { isWriteable } from './is-writeable'
71
import * as Log from './output/log'
J
Joe Haddad 已提交
72
import createSpinner from './spinner'
73
import { trace, setGlobal } from '../telemetry/trace'
J
Joe Haddad 已提交
74 75
import {
  collectPages,
76
  detectConflictingPaths,
77
  getJsPageSizeInKb,
78
  getNamedExports,
79
  hasCustomGetInitialProps,
80
  isPageStatic,
81
  PageInfo,
82
  printCustomRoutes,
J
Joe Haddad 已提交
83
  printTreeView,
84
  getCssFilePaths,
J
Joe Haddad 已提交
85
} from './utils'
86
import getBaseWebpackConfig from './webpack-config'
J
Jan Potoms 已提交
87
import { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
88
import { writeBuildId } from './write-build-id'
89
import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path'
90

J
JJ Kasper 已提交
91
const staticCheckWorker = require.resolve('./utils')
92

J
Joe Haddad 已提交
93
export type SsgRoute = {
J
JJ Kasper 已提交
94
  initialRevalidateSeconds: number | false
95
  srcRoute: string | null
J
Joe Haddad 已提交
96 97 98
  dataRoute: string
}

J
Joe Haddad 已提交
99
export type DynamicSsgRoute = {
J
Joe Haddad 已提交
100
  routeRegex: string
101
  fallback: string | null | false
J
Joe Haddad 已提交
102 103
  dataRoute: string
  dataRouteRegex: string
J
JJ Kasper 已提交
104 105 106
}

export type PrerenderManifest = {
107
  version: 3
J
Joe Haddad 已提交
108 109
  routes: { [route: string]: SsgRoute }
  dynamicRoutes: { [route: string]: DynamicSsgRoute }
110
  notFoundRoutes: string[]
J
Joe Haddad 已提交
111
  preview: __ApiPreviewProps
112 113
}

114 115 116
export default async function build(
  dir: string,
  conf = null,
117 118
  reactProductionProfiling = false,
  debugOutput = false
119
): Promise<void> {
120 121 122
  const nextBuildSpan = trace('next-build')

  return nextBuildSpan.traceAsyncFn(async () => {
123
    // attempt to load global env values so they are available in next.config.js
124 125 126
    const { loadedEnvFiles } = nextBuildSpan
      .traceChild('load-dotenv')
      .traceFn(() => loadEnvConfig(dir, false, Log))
127

128 129 130
    const config = await nextBuildSpan
      .traceChild('load-next-config')
      .traceAsyncFn(() => loadConfig(PHASE_PRODUCTION_BUILD, dir, conf))
131
    const { target } = config
132 133 134
    const buildId = await nextBuildSpan
      .traceChild('generate-buildid')
      .traceAsyncFn(() => generateBuildId(config.generateBuildId, nanoid))
135
    const distDir = path.join(dir, config.distDir)
J
JJ Kasper 已提交
136

137 138 139
    const { headers, rewrites, redirects } = await nextBuildSpan
      .traceChild('load-custom-routes')
      .traceAsyncFn(() => loadCustomRoutes(config))
J
Joe Haddad 已提交
140

141 142 143
    if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) {
      const cacheDir = path.join(distDir, 'cache')
      const hasCache = await fileExists(cacheDir)
J
Joe Haddad 已提交
144

145 146 147 148 149 150 151
      if (!hasCache) {
        // Intentionally not piping to stderr in case people fail in CI when
        // stderr is detected.
        console.log(
          `${Log.prefixes.warn} No build cache found. Please configure build caching for faster rebuilds. Read more: https://err.sh/next.js/no-cache`
        )
      }
J
Joe Haddad 已提交
152 153
    }

154 155
    const typeCheckingSpinner = createSpinner({
      prefixText: `${Log.prefixes.info} Checking validity of types`,
156
    })
J
Joe Haddad 已提交
157

158
    const telemetry = new Telemetry({ distDir })
159
    setGlobal('telemetry', telemetry)
J
Joe Haddad 已提交
160

161 162 163
    const publicDir = path.join(dir, 'public')
    const pagesDir = findPagesDir(dir)
    const hasPublicDir = await fileExists(publicDir)
164

165 166 167 168 169 170 171 172
    telemetry.record(
      eventCliSession(PHASE_PRODUCTION_BUILD, dir, {
        cliCommand: 'build',
        isSrcDir: path.relative(dir, pagesDir!).startsWith('src'),
        hasNowJson: !!(await findUp('now.json', { cwd: dir })),
        isCustomServer: null,
      })
    )
173

174 175 176
    eventNextPlugins(path.resolve(dir)).then((events) =>
      telemetry.record(events)
    )
177

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    if (config.eslint?.build) {
      await nextBuildSpan
        .traceChild('verify-and-lint')
        .traceAsyncFn(async () => {
          const lintWorkers = new Worker(
            require.resolve('../lib/verifyAndLint'),
            {
              numWorkers: config.experimental.cpus,
              enableWorkerThreads: config.experimental.workerThreads,
            }
          ) as Worker & {
            verifyAndLint: typeof import('../lib/verifyAndLint').verifyAndLint
          }

          lintWorkers.getStdout().pipe(process.stdout)
          lintWorkers.getStderr().pipe(process.stderr)

          const lintResults = await lintWorkers.verifyAndLint(
            dir,
            pagesDir,
            null
          )

          if (lintResults.hasErrors) {
            console.error(chalk.red('Failed to compile.'))
            console.error(lintResults.results)
            process.exit(1)
          } else if (lintResults.hasMessages) {
            console.log(lintResults.results)
          }

          lintWorkers.end()
        })
    }

213
    const ignoreTypeScriptErrors = Boolean(config.typescript?.ignoreBuildErrors)
214 215 216 217 218
    await nextBuildSpan
      .traceChild('verify-typescript-setup')
      .traceAsyncFn(() =>
        verifyTypeScriptSetup(dir, pagesDir, !ignoreTypeScriptErrors)
      )
219

220 221 222 223 224 225 226 227
    if (typeCheckingSpinner) {
      typeCheckingSpinner.stopAndPersist()
    }

    const buildSpinner = createSpinner({
      prefixText: `${Log.prefixes.info} Creating an optimized production build`,
    })

228
    const isLikeServerless = isTargetLikeServerless(target)
229

230 231 232
    const pagePaths: string[] = await nextBuildSpan
      .traceChild('collect-pages')
      .traceAsyncFn(() => collectPages(pagesDir, config.pageExtensions))
J
Joe Haddad 已提交
233

234 235 236 237
    // needed for static exporting since we want to replace with HTML
    // files
    const allStaticPages = new Set<string>()
    let allPageInfos = new Map<string, PageInfo>()
238

239 240 241 242
    const previewProps: __ApiPreviewProps = {
      previewModeId: crypto.randomBytes(16).toString('hex'),
      previewModeSigningKey: crypto.randomBytes(32).toString('hex'),
      previewModeEncryptionKey: crypto.randomBytes(32).toString('hex'),
243
    }
244

245 246 247 248 249 250 251 252 253 254 255 256 257 258
    const mappedPages = nextBuildSpan
      .traceChild('create-pages-mapping')
      .traceFn(() => createPagesMapping(pagePaths, config.pageExtensions))
    const entrypoints = nextBuildSpan
      .traceChild('create-entrypoints')
      .traceFn(() =>
        createEntrypoints(
          mappedPages,
          target,
          buildId,
          previewProps,
          config,
          loadedEnvFiles
        )
259
      )
260 261 262 263
    const pageKeys = Object.keys(mappedPages)
    const conflictingPublicFiles: string[] = []
    const hasCustomErrorPage = mappedPages['/_error'].startsWith(
      'private-next-pages'
264
    )
265 266 267 268 269 270 271 272 273 274 275 276
    const hasPages404 = Boolean(
      mappedPages['/404'] &&
        mappedPages['/404'].startsWith('private-next-pages')
    )

    if (hasPublicDir) {
      const hasPublicUnderScoreNextDir = await fileExists(
        path.join(publicDir, '_next')
      )
      if (hasPublicUnderScoreNextDir) {
        throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
      }
277
    }
278

279 280 281
    await nextBuildSpan
      .traceChild('public-dir-conflict-check')
      .traceAsyncFn(async () => {
282 283 284 285 286 287 288 289 290 291 292
        // Check if pages conflict with files in `public`
        // Only a page of public file can be served, not both.
        for (const page in mappedPages) {
          const hasPublicPageFile = await fileExists(
            path.join(publicDir, page === '/' ? '/index' : page),
            'file'
          )
          if (hasPublicPageFile) {
            conflictingPublicFiles.push(page)
          }
        }
293

294
        const numConflicting = conflictingPublicFiles.length
295

296 297 298 299 300 301 302 303 304
        if (numConflicting) {
          throw new Error(
            `Conflicting public and page file${
              numConflicting === 1 ? ' was' : 's were'
            } found. https://err.sh/vercel/next.js/conflicting-public-file-page\n${conflictingPublicFiles.join(
              '\n'
            )}`
          )
        }
305
      })
306

307 308 309 310
    const nestedReservedPages = pageKeys.filter((page) => {
      return (
        page.match(/\/(_app|_document|_error)$/) && path.dirname(page) !== '/'
      )
311 312
    })

313 314 315 316 317 318
    if (nestedReservedPages.length) {
      Log.warn(
        `The following reserved Next.js pages were detected not directly under the pages directory:\n` +
          nestedReservedPages.join('\n') +
          `\nSee more info here: https://err.sh/next.js/nested-reserved-page\n`
      )
319
    }
320

321 322 323 324 325 326 327 328 329 330 331
    const buildCustomRoute = (
      r: {
        source: string
        locale?: false
        basePath?: false
        statusCode?: number
        destination?: string
      },
      type: RouteType
    ) => {
      const keys: any[] = []
332

333 334 335 336 337
      const routeRegex = pathToRegexp(r.source, keys, {
        strict: true,
        sensitive: false,
        delimiter: '/', // default is `/#?`, but Next does not pass query info
      })
338

339 340 341 342 343 344 345 346 347
      return {
        ...r,
        ...(type === 'redirect'
          ? {
              statusCode: getRedirectStatus(r as Redirect),
              permanent: undefined,
            }
          : {}),
        regex: normalizeRouteRegex(routeRegex.source),
348
      }
349
    }
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

    const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)
    const routesManifest: {
      version: number
      pages404: boolean
      basePath: string
      redirects: Array<ReturnType<typeof buildCustomRoute>>
      rewrites: Array<ReturnType<typeof buildCustomRoute>>
      headers: Array<ReturnType<typeof buildCustomRoute>>
      dynamicRoutes: Array<{
        page: string
        regex: string
        namedRegex?: string
        routeKeys?: { [key: string]: string }
      }>
      dataRoutes: Array<{
        page: string
        routeKeys?: { [key: string]: string }
        dataRouteRegex: string
        namedDataRouteRegex?: string
      }>
      i18n?: {
        domains?: Array<{
          http?: true
          domain: string
          locales?: string[]
          defaultLocale: string
        }>
        locales: string[]
        defaultLocale: string
        localeDetection?: false
      }
382
    } = nextBuildSpan.traceChild('generate-routes-manifest').traceFn(() => ({
383 384 385
      version: 3,
      pages404: true,
      basePath: config.basePath,
386 387 388
      redirects: redirects.map((r: any) => buildCustomRoute(r, 'redirect')),
      rewrites: rewrites.map((r: any) => buildCustomRoute(r, 'rewrite')),
      headers: headers.map((r: any) => buildCustomRoute(r, 'header')),
389 390 391 392 393 394 395 396 397 398 399 400 401
      dynamicRoutes: getSortedRoutes(pageKeys)
        .filter(isDynamicRoute)
        .map((page) => {
          const routeRegex = getRouteRegex(page)
          return {
            page,
            regex: normalizeRouteRegex(routeRegex.re.source),
            routeKeys: routeRegex.routeKeys,
            namedRegex: routeRegex.namedRegex,
          }
        }),
      dataRoutes: [],
      i18n: config.i18n || undefined,
402
    }))
403

404 405 406
    const distDirCreated = await nextBuildSpan
      .traceChild('create-dist-dir')
      .traceAsyncFn(async () => {
407 408 409 410 411 412 413 414 415
        try {
          await promises.mkdir(distDir, { recursive: true })
          return true
        } catch (err) {
          if (err.code === 'EPERM') {
            return false
          }
          throw err
        }
416
      })
417 418 419 420 421 422 423

    if (!distDirCreated || !(await isWriteable(distDir))) {
      throw new Error(
        '> Build directory is not writeable. https://err.sh/vercel/next.js/build-dir-not-writeable'
      )
    }

424 425
    // We need to write the manifest with rewrites before build
    // so serverless can import the manifest
426 427 428 429 430 431 432 433
    await nextBuildSpan
      .traceChild('write-routes-manifest')
      .traceAsyncFn(() =>
        promises.writeFile(
          routesManifestPath,
          JSON.stringify(routesManifest),
          'utf8'
        )
434
      )
435

436 437 438 439 440 441
    const manifestPath = path.join(
      distDir,
      isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
      PAGES_MANIFEST
    )

442 443 444
    const requiredServerFiles = nextBuildSpan
      .traceChild('generate-required-server-files')
      .traceFn(() => ({
445 446 447 448 449 450
        version: 1,
        config: {
          ...config,
          compress: false,
          configFile: undefined,
        },
451
        appDir: dir,
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        files: [
          ROUTES_MANIFEST,
          path.relative(distDir, manifestPath),
          BUILD_MANIFEST,
          PRERENDER_MANIFEST,
          REACT_LOADABLE_MANIFEST,
          config.experimental.optimizeFonts
            ? path.join(
                isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
                FONT_MANIFEST
              )
            : null,
          BUILD_ID_FILE,
        ]
          .filter(nonNullable)
          .map((file) => path.join(config.distDir, file)),
468
        ignore: [] as string[],
469
      }))
470

471 472 473
    const configs = await nextBuildSpan
      .traceChild('generate-webpack-config')
      .traceAsyncFn(() =>
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
        Promise.all([
          getBaseWebpackConfig(dir, {
            buildId,
            reactProductionProfiling,
            isServer: false,
            config,
            target,
            pagesDir,
            entrypoints: entrypoints.client,
            rewrites,
          }),
          getBaseWebpackConfig(dir, {
            buildId,
            reactProductionProfiling,
            isServer: true,
            config,
            target,
            pagesDir,
            entrypoints: entrypoints.server,
            rewrites,
          }),
        ])
496
      )
497 498

    const clientConfig = configs[0]
499

500
    if (
501 502 503 504
      clientConfig.optimization &&
      (clientConfig.optimization.minimize !== true ||
        (clientConfig.optimization.minimizer &&
          clientConfig.optimization.minimizer.length === 0))
505
    ) {
506 507
      Log.warn(
        `Production code optimization has been disabled in your project. Read more: https://err.sh/vercel/next.js/minification-disabled`
J
Joe Haddad 已提交
508
      )
509
    }
510

511 512 513
    const webpackBuildStart = process.hrtime()

    let result: CompilerResult = { warnings: [], errors: [] }
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    // We run client and server compilation separately when configured for
    // memory constraint and for serverless to be able to load manifests
    // produced in the client build
    if (isLikeServerless || config.experimental.serialWebpackBuild) {
      await nextBuildSpan
        .traceChild('run-webpack-compiler')
        .traceAsyncFn(async () => {
          const clientResult = await runCompiler(clientConfig)
          // Fail build if clientResult contains errors
          if (clientResult.errors.length > 0) {
            result = {
              warnings: [...clientResult.warnings],
              errors: [...clientResult.errors],
            }
          } else {
            const serverResult = await runCompiler(configs[1])
            result = {
              warnings: [...clientResult.warnings, ...serverResult.warnings],
              errors: [...clientResult.errors, ...serverResult.errors],
            }
          }
        })
536
    } else {
537 538 539
      result = await nextBuildSpan
        .traceChild('run-webpack-compiler')
        .traceAsyncFn(() => runCompiler(configs))
540
    }
541

542 543 544 545
    const webpackBuildEnd = process.hrtime(webpackBuildStart)
    if (buildSpinner) {
      buildSpinner.stopAndPersist()
    }
546

547 548 549
    result = nextBuildSpan
      .traceChild('format-webpack-messages')
      .traceFn(() => formatWebpackMessages(result))
550

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    if (result.errors.length > 0) {
      // Only keep the first error. Others are often indicative
      // of the same problem, but confuse the reader with noise.
      if (result.errors.length > 1) {
        result.errors.length = 1
      }
      const error = result.errors.join('\n\n')

      console.error(chalk.red('Failed to compile.\n'))

      if (
        error.indexOf('private-next-pages') > -1 &&
        error.indexOf('does not contain a default export') > -1
      ) {
        const page_name_regex = /'private-next-pages\/(?<page_name>[^']*)'/
        const parsed = page_name_regex.exec(error)
        const page_name = parsed && parsed.groups && parsed.groups.page_name
        throw new Error(
          `webpack build failed: found page without a React Component as default export in pages/${page_name}\n\nSee https://err.sh/vercel/next.js/page-without-valid-component for more info.`
        )
      }

      console.error(error)
      console.error()
J
JJ Kasper 已提交
575

576 577 578 579 580 581 582 583 584 585 586 587 588 589
      if (
        error.indexOf('private-next-pages') > -1 ||
        error.indexOf('__next_polyfill__') > -1
      ) {
        throw new Error(
          '> webpack config.resolve.alias was incorrectly overridden. https://err.sh/vercel/next.js/invalid-resolve-alias'
        )
      }
      throw new Error('> Build failed because of webpack errors')
    } else {
      telemetry.record(
        eventBuildCompleted(pagePaths, {
          durationInSeconds: webpackBuildEnd[0],
        })
590
      )
591

592 593 594 595 596 597 598 599
      if (result.warnings.length > 0) {
        Log.warn('Compiled with warnings\n')
        console.warn(result.warnings.join('\n\n'))
        console.warn()
      } else {
        Log.info('Compiled successfully')
      }
    }
600

601 602 603
    const postCompileSpinner = createSpinner({
      prefixText: `${Log.prefixes.info} Collecting page data`,
    })
604

605 606 607 608 609 610 611 612 613 614
    const buildManifestPath = path.join(distDir, BUILD_MANIFEST)

    const ssgPages = new Set<string>()
    const ssgStaticFallbackPages = new Set<string>()
    const ssgBlockingFallbackPages = new Set<string>()
    const staticPages = new Set<string>()
    const invalidPages = new Set<string>()
    const hybridAmpPages = new Set<string>()
    const serverPropsPages = new Set<string>()
    const additionalSsgPaths = new Map<string, Array<string>>()
615
    const additionalSsgPathsEncoded = new Map<string, Array<string>>()
616 617 618 619 620 621 622 623 624 625 626 627
    const pageInfos = new Map<string, PageInfo>()
    const pagesManifest = JSON.parse(
      await promises.readFile(manifestPath, 'utf8')
    ) as PagesManifest
    const buildManifest = JSON.parse(
      await promises.readFile(buildManifestPath, 'utf8')
    ) as BuildManifest

    let customAppGetInitialProps: boolean | undefined
    let namedExports: Array<string> | undefined
    let isNextImageImported: boolean | undefined
    const analysisBegin = process.hrtime()
628
    let hasSsrAmpPages = false
629

630 631
    const staticCheckSpan = nextBuildSpan.traceChild('static-check')
    const { hasNonStaticErrorPage } = await staticCheckSpan.traceAsyncFn(
632 633
      async () => {
        process.env.NEXT_PHASE = PHASE_PRODUCTION_BUILD
J
JJ Kasper 已提交
634

635 636 637 638
        const staticCheckWorkers = new Worker(staticCheckWorker, {
          numWorkers: config.experimental.cpus,
          enableWorkerThreads: config.experimental.workerThreads,
        }) as Worker & { isPageStatic: typeof isPageStatic }
639

640 641
        staticCheckWorkers.getStdout().pipe(process.stdout)
        staticCheckWorkers.getStderr().pipe(process.stderr)
642

643 644 645 646
        const runtimeEnvConfig = {
          publicRuntimeConfig: config.publicRuntimeConfig,
          serverRuntimeConfig: config.serverRuntimeConfig,
        }
647

648 649 650 651
        const nonStaticErrorPageSpan = staticCheckSpan.traceChild(
          'check-static-error-page'
        )
        const nonStaticErrorPage = await nonStaticErrorPageSpan.traceAsyncFn(
652 653 654
          async () =>
            hasCustomErrorPage &&
            (await hasCustomGetInitialProps(
655 656 657
              '/_error',
              distDir,
              isLikeServerless,
658
              runtimeEnvConfig,
659 660 661
              false
            ))
        )
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        // we don't output _app in serverless mode so use _app export
        // from _error instead
        const appPageToCheck = isLikeServerless ? '/_error' : '/_app'

        customAppGetInitialProps = await hasCustomGetInitialProps(
          appPageToCheck,
          distDir,
          isLikeServerless,
          runtimeEnvConfig,
          true
        )

        namedExports = await getNamedExports(
          appPageToCheck,
          distDir,
          isLikeServerless,
          runtimeEnvConfig
        )

        if (customAppGetInitialProps) {
          console.warn(
            chalk.bold.yellow(`Warning: `) +
              chalk.yellow(
                `You have opted-out of Automatic Static Optimization due to \`getInitialProps\` in \`pages/_app\`. This does not opt-out pages with \`getStaticProps\``
              )
          )
          console.warn(
            'Read more: https://err.sh/next.js/opt-out-auto-static-optimization\n'
          )
        }
J
JJ Kasper 已提交
692

693 694
        await Promise.all(
          pageKeys.map(async (page) => {
695 696 697 698 699 700 701 702 703 704
            const checkPageSpan = staticCheckSpan.traceChild('check-page', {
              page,
            })
            return checkPageSpan.traceAsyncFn(async () => {
              const actualPage = normalizePagePath(page)
              const [selfSize, allSize] = await getJsPageSizeInKb(
                actualPage,
                distDir,
                buildManifest
              )
705

706 707 708 709
              let isSsg = false
              let isStatic = false
              let isHybridAmp = false
              let ssgPageRoutes: string[] | null = null
710

711 712 713
              const nonReservedPage = !page.match(
                /^\/(_app|_error|_document|api(\/|$))/
              )
714

715 716 717 718 719 720 721 722 723 724 725 726 727 728
              if (nonReservedPage) {
                try {
                  let isPageStaticSpan = checkPageSpan.traceChild(
                    'is-page-static'
                  )
                  let workerResult = await isPageStaticSpan.traceAsyncFn(() => {
                    return staticCheckWorkers.isPageStatic(
                      page,
                      distDir,
                      isLikeServerless,
                      runtimeEnvConfig,
                      config.i18n?.locales,
                      config.i18n?.defaultLocale,
                      isPageStaticSpan.id
729
                    )
730
                  })
731

732 733 734 735 736 737
                  if (
                    workerResult.isStatic === false &&
                    (workerResult.isHybridAmp || workerResult.isAmpOnly)
                  ) {
                    hasSsrAmpPages = true
                  }
738

739 740 741 742
                  if (workerResult.isHybridAmp) {
                    isHybridAmp = true
                    hybridAmpPages.add(page)
                  }
743

744 745 746
                  if (workerResult.isNextImageImported) {
                    isNextImageImported = true
                  }
747

748 749 750
                  if (workerResult.hasStaticProps) {
                    ssgPages.add(page)
                    isSsg = true
751

752 753 754
                    if (
                      workerResult.prerenderRoutes &&
                      workerResult.encodedPrerenderRoutes
755
                    ) {
756 757 758 759 760 761
                      additionalSsgPaths.set(page, workerResult.prerenderRoutes)
                      additionalSsgPathsEncoded.set(
                        page,
                        workerResult.encodedPrerenderRoutes
                      )
                      ssgPageRoutes = workerResult.prerenderRoutes
762 763
                    }

764 765 766 767
                    if (workerResult.prerenderFallback === 'blocking') {
                      ssgBlockingFallbackPages.add(page)
                    } else if (workerResult.prerenderFallback === true) {
                      ssgStaticFallbackPages.add(page)
768
                    }
769 770 771 772 773 774 775 776 777
                  } else if (workerResult.hasServerProps) {
                    serverPropsPages.add(page)
                  } else if (
                    workerResult.isStatic &&
                    customAppGetInitialProps === false
                  ) {
                    staticPages.add(page)
                    isStatic = true
                  }
778

779
                  if (hasPages404 && page === '/404') {
780 781 782 783 784
                    if (
                      !workerResult.isStatic &&
                      !workerResult.hasStaticProps
                    ) {
                      throw new Error(
785
                        `\`pages/404\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`
786 787
                      )
                    }
788 789 790 791 792 793 794 795
                    // we need to ensure the 404 lambda is present since we use
                    // it when _app has getInitialProps
                    if (
                      customAppGetInitialProps &&
                      !workerResult.hasStaticProps
                    ) {
                      staticPages.delete(page)
                    }
796
                  }
797

798 799 800 801 802 803 804 805 806 807 808 809 810
                  if (
                    STATIC_STATUS_PAGES.includes(page) &&
                    !workerResult.isStatic &&
                    !workerResult.hasStaticProps
                  ) {
                    throw new Error(
                      `\`pages${page}\` ${STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR}`
                    )
                  }
                } catch (err) {
                  if (err.message !== 'INVALID_DEFAULT_EXPORT') throw err
                  invalidPages.add(page)
                }
811
              }
812 813 814 815 816 817 818 819 820 821 822

              pageInfos.set(page, {
                size: selfSize,
                totalSize: allSize,
                static: isStatic,
                isSsg,
                isHybridAmp,
                ssgPageRoutes,
                initialRevalidateSeconds: false,
              })
            })
823 824 825
          })
        )
        staticCheckWorkers.end()
J
JJ Kasper 已提交
826

827 828
        return { hasNonStaticErrorPage: nonStaticErrorPage }
      }
829
    )
830

831 832 833 834 835
    if (!hasSsrAmpPages) {
      requiredServerFiles.ignore.push(
        path.relative(
          dir,
          path.join(
J
JJ Kasper 已提交
836 837 838 839 840
            path.dirname(
              require.resolve(
                'next/dist/compiled/@ampproject/toolbox-optimizer'
              )
            ),
841 842
            '**/*'
          )
843 844
        )
      )
845
    }
846

847 848 849 850 851 852 853 854 855 856 857 858 859
    if (serverPropsPages.size > 0 || ssgPages.size > 0) {
      // We update the routes manifest after the build with the
      // data routes since we can't determine these until after build
      routesManifest.dataRoutes = getSortedRoutes([
        ...serverPropsPages,
        ...ssgPages,
      ]).map((page) => {
        const pagePath = normalizePagePath(page)
        const dataRoute = path.posix.join(
          '/_next/data',
          buildId,
          `${pagePath}.json`
        )
860

861 862 863
        let dataRouteRegex: string
        let namedDataRouteRegex: string | undefined
        let routeKeys: { [named: string]: string } | undefined
864

865 866
        if (isDynamicRoute(page)) {
          const routeRegex = getRouteRegex(dataRoute.replace(/\.json$/, ''))
867

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
          dataRouteRegex = normalizeRouteRegex(
            routeRegex.re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$')
          )
          namedDataRouteRegex = routeRegex.namedRegex!.replace(
            /\(\?:\/\)\?\$$/,
            '\\.json$'
          )
          routeKeys = routeRegex.routeKeys
        } else {
          dataRouteRegex = normalizeRouteRegex(
            new RegExp(
              `^${path.posix.join(
                '/_next/data',
                escapeStringRegexp(buildId),
                `${pagePath}.json`
              )}$`
            ).source
          )
        }
887

888 889 890 891 892 893 894
        return {
          page,
          routeKeys,
          dataRouteRegex,
          namedDataRouteRegex,
        }
      })
895

896 897 898 899 900 901
      await promises.writeFile(
        routesManifestPath,
        JSON.stringify(routesManifest),
        'utf8'
      )
    }
902

903 904 905 906
    // Since custom _app.js can wrap the 404 page we have to opt-out of static optimization if it has getInitialProps
    // Only export the static 404 when there is no /_error present
    const useStatic404 =
      !customAppGetInitialProps && (!hasNonStaticErrorPage || hasPages404)
907

908 909 910 911 912 913 914 915 916 917
    if (invalidPages.size > 0) {
      throw new Error(
        `Build optimization failed: found page${
          invalidPages.size === 1 ? '' : 's'
        } without a React Component as default export in \n${[...invalidPages]
          .map((pg) => `pages${pg}`)
          .join(
            '\n'
          )}\n\nSee https://err.sh/vercel/next.js/page-without-valid-component for more info.\n`
      )
J
JJ Kasper 已提交
918
    }
919

920 921
    await writeBuildId(distDir, buildId)

922 923 924 925 926 927 928 929
    if (config.experimental.optimizeCss) {
      const cssFilePaths = getCssFilePaths(buildManifest)

      requiredServerFiles.files.push(
        ...cssFilePaths.map((filePath) => path.join(config.distDir, filePath))
      )
    }

930 931 932 933 934 935 936 937 938 939 940 941
    await promises.writeFile(
      path.join(distDir, SERVER_FILES_MANIFEST),
      JSON.stringify(requiredServerFiles),
      'utf8'
    )

    const finalPrerenderRoutes: { [route: string]: SsgRoute } = {}
    const tbdPrerenderRoutes: string[] = []
    let ssgNotFoundPaths: string[] = []

    if (postCompileSpinner) postCompileSpinner.stopAndPersist()

942 943
    const { i18n } = config

944 945 946 947 948 949 950 951 952 953 954
    const usedStaticStatusPages = STATIC_STATUS_PAGES.filter(
      (page) =>
        mappedPages[page] && mappedPages[page].startsWith('private-next-pages')
    )
    usedStaticStatusPages.forEach((page) => {
      if (!ssgPages.has(page)) {
        staticPages.add(page)
      }
    })

    const hasPages500 = usedStaticStatusPages.includes('/500')
955
    const useDefaultStatic500 = !hasPages500 && !hasNonStaticErrorPage
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    const combinedPages = [...staticPages, ...ssgPages]

    if (combinedPages.length > 0 || useStatic404 || useDefaultStatic500) {
      const staticGenerationSpan = nextBuildSpan.traceChild('static-generation')
      await staticGenerationSpan.traceAsyncFn(async () => {
        detectConflictingPaths(
          [
            ...combinedPages,
            ...pageKeys.filter((page) => !combinedPages.includes(page)),
          ],
          ssgPages,
          additionalSsgPaths
        )
        const exportApp = require('../export').default
        const exportOptions = {
          silent: false,
          buildExport: true,
          threads: config.experimental.cpus,
          pages: combinedPages,
          outdir: path.join(distDir, 'export'),
          statusMessage: 'Generating static pages',
        }
        const exportConfig: any = {
          ...config,
          initialPageRevalidationMap: {},
          ssgNotFoundPaths: [] as string[],
          // Default map will be the collection of automatic statically exported
          // pages and incremental pages.
          // n.b. we cannot handle this above in combinedPages because the dynamic
          // page must be in the `pages` array, but not in the mapping.
          exportPathMap: (defaultMap: any) => {
            // Dynamically routed pages should be prerendered to be used as
            // a client-side skeleton (fallback) while data is being fetched.
            // This ensures the end-user never sees a 500 or slow response from the
            // server.
            //
            // Note: prerendering disables automatic static optimization.
            ssgPages.forEach((page) => {
              if (isDynamicRoute(page)) {
                tbdPrerenderRoutes.push(page)

                if (ssgStaticFallbackPages.has(page)) {
                  // Override the rendering for the dynamic page to be treated as a
                  // fallback render.
                  if (i18n) {
                    defaultMap[`/${i18n.defaultLocale}${page}`] = {
                      page,
                      query: { __nextFallback: true },
                    }
                  } else {
                    defaultMap[page] = { page, query: { __nextFallback: true } }
1007 1008
                  }
                } else {
1009 1010 1011
                  // Remove dynamically routed pages from the default path map when
                  // fallback behavior is disabled.
                  delete defaultMap[page]
1012
                }
1013
              }
1014
            })
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
            // Append the "well-known" routes we should prerender for, e.g. blog
            // post slugs.
            additionalSsgPaths.forEach((routes, page) => {
              const encodedRoutes = additionalSsgPathsEncoded.get(page)

              routes.forEach((route, routeIdx) => {
                defaultMap[route] = {
                  page,
                  query: { __nextSsgPath: encodedRoutes?.[routeIdx] },
                }
              })
            })
1027

1028 1029 1030 1031
            if (useStatic404) {
              defaultMap['/404'] = {
                page: hasPages404 ? '/404' : '/_error',
              }
1032
            }
1033

1034 1035 1036 1037
            if (useDefaultStatic500) {
              defaultMap['/500'] = {
                page: '/_error',
              }
1038
            }
1039

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
            if (i18n) {
              for (const page of [
                ...staticPages,
                ...ssgPages,
                ...(useStatic404 ? ['/404'] : []),
                ...(useDefaultStatic500 ? ['/500'] : []),
              ]) {
                const isSsg = ssgPages.has(page)
                const isDynamic = isDynamicRoute(page)
                const isFallback = isSsg && ssgStaticFallbackPages.has(page)

                for (const locale of i18n.locales) {
                  // skip fallback generation for SSG pages without fallback mode
                  if (isSsg && isDynamic && !isFallback) continue
                  const outputPath = `/${locale}${page === '/' ? '' : page}`

                  defaultMap[outputPath] = {
                    page: defaultMap[page]?.page || page,
                    query: { __nextLocale: locale },
                  }
1060

1061 1062 1063
                  if (isFallback) {
                    defaultMap[outputPath].query.__nextFallback = true
                  }
1064
                }
1065

1066 1067 1068 1069
                if (isSsg) {
                  // remove non-locale prefixed variant from defaultMap
                  delete defaultMap[page]
                }
1070 1071
              }
            }
1072 1073 1074
            return defaultMap
          },
        }
1075

1076
        await exportApp(dir, exportOptions, exportConfig)
J
JJ Kasper 已提交
1077

1078 1079 1080 1081
        const postBuildSpinner = createSpinner({
          prefixText: `${Log.prefixes.info} Finalizing page optimization`,
        })
        ssgNotFoundPaths = exportConfig.ssgNotFoundPaths
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091
        // remove server bundles that were exported
        for (const page of staticPages) {
          const serverBundle = getPagePath(page, distDir, isLikeServerless)
          await promises.unlink(serverBundle)
        }
        const serverOutputDir = path.join(
          distDir,
          isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
        )
1092

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
        const moveExportedPage = async (
          originPage: string,
          page: string,
          file: string,
          isSsg: boolean,
          ext: 'html' | 'json',
          additionalSsgFile = false
        ) => {
          return staticGenerationSpan
            .traceChild('move-exported-page')
            .traceAsyncFn(async () => {
              file = `${file}.${ext}`
              const orig = path.join(exportOptions.outdir, file)
              const pagePath = getPagePath(
                originPage,
                distDir,
                isLikeServerless
              )

              const relativeDest = path
                .relative(
                  serverOutputDir,
1115
                  path.join(
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
                    path.join(
                      pagePath,
                      // strip leading / and then recurse number of nested dirs
                      // to place from base folder
                      originPage
                        .substr(1)
                        .split('/')
                        .map(() => '..')
                        .join('/')
                    ),
                    file
                  )
1128
                )
1129 1130 1131 1132 1133 1134
                .replace(/\\/g, '/')

              const dest = path.join(
                distDir,
                isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
                relativeDest
1135
              )
1136

1137 1138 1139 1140 1141 1142 1143 1144 1145
              if (
                !isSsg &&
                !(
                  // don't add static status page to manifest if it's
                  // the default generated version e.g. no pages/500
                  (
                    STATIC_STATUS_PAGES.includes(page) &&
                    !usedStaticStatusPages.includes(page)
                  )
1146
                )
1147 1148 1149
              ) {
                pagesManifest[page] = relativeDest
              }
1150

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
              const isNotFound = ssgNotFoundPaths.includes(page)

              // for SSG files with i18n the non-prerendered variants are
              // output with the locale prefixed so don't attempt moving
              // without the prefix
              if ((!i18n || additionalSsgFile) && !isNotFound) {
                await promises.mkdir(path.dirname(dest), { recursive: true })
                await promises.rename(orig, dest)
              } else if (i18n && !isSsg) {
                // this will be updated with the locale prefixed variant
                // since all files are output with the locale prefix
                delete pagesManifest[page]
              }
1164

1165 1166
              if (i18n) {
                if (additionalSsgFile) return
1167

1168 1169 1170 1171 1172 1173
                for (const locale of i18n.locales) {
                  const curPath = `/${locale}${page === '/' ? '' : page}`
                  const localeExt = page === '/' ? path.extname(file) : ''
                  const relativeDestNoPages = relativeDest.substr(
                    'pages/'.length
                  )
1174

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
                  if (isSsg && ssgNotFoundPaths.includes(curPath)) {
                    continue
                  }

                  const updatedRelativeDest = path
                    .join(
                      'pages',
                      locale + localeExt,
                      // if it's the top-most index page we want it to be locale.EXT
                      // instead of locale/index.html
                      page === '/' ? '' : relativeDestNoPages
                    )
                    .replace(/\\/g, '/')
1188

1189 1190
                  const updatedOrig = path.join(
                    exportOptions.outdir,
1191
                    locale + localeExt,
1192 1193 1194 1195 1196 1197
                    page === '/' ? '' : file
                  )
                  const updatedDest = path.join(
                    distDir,
                    isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
                    updatedRelativeDest
1198
                  )
1199

1200 1201 1202 1203 1204 1205 1206
                  if (!isSsg) {
                    pagesManifest[curPath] = updatedRelativeDest
                  }
                  await promises.mkdir(path.dirname(updatedDest), {
                    recursive: true,
                  })
                  await promises.rename(updatedOrig, updatedDest)
1207 1208
                }
              }
1209 1210
            })
        }
1211

1212 1213 1214 1215
        // Only move /404 to /404 when there is no custom 404 as in that case we don't know about the 404 page
        if (!hasPages404 && useStatic404) {
          await moveExportedPage('/_error', '/404', '/404', false, 'html')
        }
J
JJ Kasper 已提交
1216

1217 1218 1219
        if (useDefaultStatic500) {
          await moveExportedPage('/_error', '/500', '/500', false, 'html')
        }
1220

1221 1222 1223 1224 1225 1226
        for (const page of combinedPages) {
          const isSsg = ssgPages.has(page)
          const isStaticSsgFallback = ssgStaticFallbackPages.has(page)
          const isDynamic = isDynamicRoute(page)
          const hasAmp = hybridAmpPages.has(page)
          const file = normalizePagePath(page)
1227

1228 1229 1230 1231
          // The dynamic version of SSG pages are only prerendered if the
          // fallback is enabled. Below, we handle the specific prerenders
          // of these.
          const hasHtmlOutput = !(isSsg && isDynamic && !isStaticSsgFallback)
1232

1233 1234 1235
          if (hasHtmlOutput) {
            await moveExportedPage(page, page, file, isSsg, 'html')
          }
1236

1237 1238 1239
          if (hasAmp && (!isSsg || (isSsg && !isDynamic))) {
            const ampPage = `${file}.amp`
            await moveExportedPage(page, ampPage, ampPage, isSsg, 'html')
J
JJ Kasper 已提交
1240

1241 1242 1243
            if (isSsg) {
              await moveExportedPage(page, ampPage, ampPage, isSsg, 'json')
            }
1244 1245
          }

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
          if (isSsg) {
            // For a non-dynamic SSG page, we must copy its data file
            // from export, we already moved the HTML file above
            if (!isDynamic) {
              await moveExportedPage(page, page, file, isSsg, 'json')

              if (i18n) {
                // TODO: do we want to show all locale variants in build output
                for (const locale of i18n.locales) {
                  const localePage = `/${locale}${page === '/' ? '' : page}`

                  if (!ssgNotFoundPaths.includes(localePage)) {
                    finalPrerenderRoutes[localePage] = {
                      initialRevalidateSeconds:
                        exportConfig.initialPageRevalidationMap[localePage],
                      srcRoute: null,
                      dataRoute: path.posix.join(
                        '/_next/data',
                        buildId,
                        `${file}.json`
                      ),
                    }
1268 1269
                  }
                }
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
              } else {
                finalPrerenderRoutes[page] = {
                  initialRevalidateSeconds:
                    exportConfig.initialPageRevalidationMap[page],
                  srcRoute: null,
                  dataRoute: path.posix.join(
                    '/_next/data',
                    buildId,
                    `${file}.json`
                  ),
                }
1281
              }
1282 1283 1284 1285 1286 1287
              // Set Page Revalidation Interval
              const pageInfo = pageInfos.get(page)
              if (pageInfo) {
                pageInfo.initialRevalidateSeconds =
                  exportConfig.initialPageRevalidationMap[page]
                pageInfos.set(page, pageInfo)
1288
              }
1289 1290 1291 1292 1293 1294 1295 1296
            } else {
              // For a dynamic SSG page, we did not copy its data exports and only
              // copy the fallback HTML file (if present).
              // We must also copy specific versions of this page as defined by
              // `getStaticPaths` (additionalSsgPaths).
              const extraRoutes = additionalSsgPaths.get(page) || []
              for (const route of extraRoutes) {
                const pageFile = normalizePagePath(route)
1297 1298
                await moveExportedPage(
                  page,
1299 1300
                  route,
                  pageFile,
1301
                  isSsg,
1302 1303 1304 1305 1306
                  'html',
                  true
                )
                await moveExportedPage(
                  page,
1307 1308
                  route,
                  pageFile,
1309
                  isSsg,
1310 1311 1312 1313
                  'json',
                  true
                )

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
                if (hasAmp) {
                  const ampPage = `${pageFile}.amp`
                  await moveExportedPage(
                    page,
                    ampPage,
                    ampPage,
                    isSsg,
                    'html',
                    true
                  )
                  await moveExportedPage(
                    page,
                    ampPage,
                    ampPage,
                    isSsg,
                    'json',
                    true
                  )
                }
1333

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
                finalPrerenderRoutes[route] = {
                  initialRevalidateSeconds:
                    exportConfig.initialPageRevalidationMap[route],
                  srcRoute: page,
                  dataRoute: path.posix.join(
                    '/_next/data',
                    buildId,
                    `${normalizePagePath(route)}.json`
                  ),
                }

                // Set route Revalidation Interval
                const pageInfo = pageInfos.get(route)
                if (pageInfo) {
                  pageInfo.initialRevalidateSeconds =
                    exportConfig.initialPageRevalidationMap[route]
                  pageInfos.set(route, pageInfo)
                }
1352
              }
1353
            }
J
JJ Kasper 已提交
1354 1355
          }
        }
1356

1357 1358 1359 1360 1361 1362 1363 1364
        // remove temporary export folder
        await recursiveDelete(exportOptions.outdir)
        await promises.rmdir(exportOptions.outdir)
        await promises.writeFile(
          manifestPath,
          JSON.stringify(pagesManifest, null, 2),
          'utf8'
        )
1365

1366 1367 1368 1369
        if (postBuildSpinner) postBuildSpinner.stopAndPersist()
        console.log()
      })
    }
1370

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
    const analysisEnd = process.hrtime(analysisBegin)
    telemetry.record(
      eventBuildOptimize(pagePaths, {
        durationInSeconds: analysisEnd[0],
        staticPageCount: staticPages.size,
        staticPropsPageCount: ssgPages.size,
        serverPropsPageCount: serverPropsPages.size,
        ssrPageCount:
          pagePaths.length -
          (staticPages.size + ssgPages.size + serverPropsPages.size),
        hasStatic404: useStatic404,
        hasReportWebVitals: namedExports?.includes('reportWebVitals') ?? false,
        rewritesCount: rewrites.length,
        headersCount: headers.length,
        redirectsCount: redirects.length - 1, // reduce one for trailing slash
J
JJ Kasper 已提交
1386 1387 1388
        headersWithHasCount: headers.filter((r: any) => !!r.has).length,
        rewritesWithHasCount: rewrites.filter((r: any) => !!r.has).length,
        redirectsWithHasCount: redirects.filter((r: any) => !!r.has).length,
1389
      })
1390
    )
J
JJ Kasper 已提交
1391

1392 1393 1394 1395 1396 1397 1398 1399 1400
    if (ssgPages.size > 0) {
      const finalDynamicRoutes: PrerenderManifest['dynamicRoutes'] = {}
      tbdPrerenderRoutes.forEach((tbdRoute) => {
        const normalizedRoute = normalizePagePath(tbdRoute)
        const dataRoute = path.posix.join(
          '/_next/data',
          buildId,
          `${normalizedRoute}.json`
        )
J
Joe Haddad 已提交
1401

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
        finalDynamicRoutes[tbdRoute] = {
          routeRegex: normalizeRouteRegex(getRouteRegex(tbdRoute).re.source),
          dataRoute,
          fallback: ssgBlockingFallbackPages.has(tbdRoute)
            ? null
            : ssgStaticFallbackPages.has(tbdRoute)
            ? `${normalizedRoute}.html`
            : false,
          dataRouteRegex: normalizeRouteRegex(
            getRouteRegex(dataRoute.replace(/\.json$/, '')).re.source.replace(
              /\(\?:\\\/\)\?\$$/,
              '\\.json$'
            )
          ),
        }
      })
      const prerenderManifest: PrerenderManifest = {
1419
        version: 3,
1420 1421 1422 1423 1424
        routes: finalPrerenderRoutes,
        dynamicRoutes: finalDynamicRoutes,
        notFoundRoutes: ssgNotFoundPaths,
        preview: previewProps,
      }
J
Joe Haddad 已提交
1425

1426 1427 1428 1429 1430 1431 1432 1433
      await promises.writeFile(
        path.join(distDir, PRERENDER_MANIFEST),
        JSON.stringify(prerenderManifest),
        'utf8'
      )
      await generateClientSsgManifest(prerenderManifest, {
        distDir,
        buildId,
1434
        locales: config.i18n?.locales || [],
1435 1436 1437
      })
    } else {
      const prerenderManifest: PrerenderManifest = {
1438
        version: 3,
1439 1440 1441 1442
        routes: {},
        dynamicRoutes: {},
        preview: previewProps,
        notFoundRoutes: [],
J
Joe Haddad 已提交
1443
      }
1444 1445 1446 1447 1448
      await promises.writeFile(
        path.join(distDir, PRERENDER_MANIFEST),
        JSON.stringify(prerenderManifest),
        'utf8'
      )
J
JJ Kasper 已提交
1449 1450
    }

1451 1452 1453 1454
    const images = { ...config.images }
    const { deviceSizes, imageSizes } = images
    images.sizes = [...deviceSizes, ...imageSizes]

1455
    await promises.writeFile(
1456 1457 1458 1459 1460
      path.join(distDir, IMAGES_MANIFEST),
      JSON.stringify({
        version: 1,
        images,
      }),
1461 1462
      'utf8'
    )
1463
    await promises.writeFile(
1464 1465 1466 1467 1468 1469 1470
      path.join(distDir, EXPORT_MARKER),
      JSON.stringify({
        version: 1,
        hasExportPathMap: typeof config.exportPathMap === 'function',
        exportTrailingSlash: config.trailingSlash === true,
        isNextImageImported: isNextImageImported === true,
      }),
1471 1472
      'utf8'
    )
1473 1474 1475 1476 1477 1478
    await promises.unlink(path.join(distDir, EXPORT_DETAIL)).catch((err) => {
      if (err.code === 'ENOENT') {
        return Promise.resolve()
      }
      return Promise.reject(err)
    })
1479

1480 1481 1482 1483
    staticPages.forEach((pg) => allStaticPages.add(pg))
    pageInfos.forEach((info: PageInfo, key: string) => {
      allPageInfos.set(key, info)
    })
1484

1485
    await nextBuildSpan.traceChild('print-tree-view').traceAsyncFn(() =>
1486
      printTreeView(Object.keys(mappedPages), allPageInfos, isLikeServerless, {
1487 1488 1489 1490 1491 1492
        distPath: distDir,
        buildId: buildId,
        pagesDir,
        useStatic404,
        pageExtensions: config.pageExtensions,
        buildManifest,
1493
      })
1494
    )
S
Steven 已提交
1495

1496
    if (debugOutput) {
1497 1498 1499
      nextBuildSpan
        .traceChild('print-custom-routes')
        .traceFn(() => printCustomRoutes({ redirects, rewrites, headers }))
J
Joe Haddad 已提交
1500
    }
L
Luc 已提交
1501

1502 1503 1504 1505 1506 1507 1508
    if (config.analyticsId) {
      console.log(
        chalk.bold.green('Next.js Analytics') +
          ' is enabled for this production build. ' +
          "You'll receive a Real Experience Score computed by all of your visitors."
      )
      console.log('')
J
Joe Haddad 已提交
1509
    }
1510

1511 1512 1513
    await nextBuildSpan
      .traceChild('telemetry-flush')
      .traceAsyncFn(() => telemetry.flush())
1514
  })
1515
}
J
Joe Haddad 已提交
1516

J
Joe Haddad 已提交
1517 1518
export type ClientSsgManifest = Set<string>

J
Joe Haddad 已提交
1519 1520
function generateClientSsgManifest(
  prerenderManifest: PrerenderManifest,
1521 1522 1523 1524 1525
  {
    buildId,
    distDir,
    locales,
  }: { buildId: string; distDir: string; locales: string[] }
J
Joe Haddad 已提交
1526
) {
J
Joe Haddad 已提交
1527
  const ssgPages: ClientSsgManifest = new Set<string>([
J
Joe Haddad 已提交
1528 1529 1530
    ...Object.entries(prerenderManifest.routes)
      // Filter out dynamic routes
      .filter(([, { srcRoute }]) => srcRoute == null)
1531
      .map(([route]) => normalizeLocalePath(route, locales).pathname),
J
Joe Haddad 已提交
1532 1533 1534 1535 1536 1537
    ...Object.keys(prerenderManifest.dynamicRoutes),
  ])

  const clientSsgManifestContent = `self.__SSG_MANIFEST=${devalue(
    ssgPages
  )};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`
1538 1539 1540 1541

  writeFileSync(
    path.join(distDir, CLIENT_STATIC_FILES_PATH, buildId, '_ssgManifest.js'),
    clientSsgManifestContent
J
Joe Haddad 已提交
1542 1543
  )
}