-
Notifications
You must be signed in to change notification settings - Fork 28k
/
Copy pathindex.ts
821 lines (717 loc) · 26 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
import type {
ExportAppResult,
ExportAppOptions,
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 findUp from 'next/dist/compiled/find-up'
import { existsSync, promises as fs } from 'fs'
import '../server/require-hook'
import { dirname, join, resolve, sep } from 'path'
import { formatAmpMessages } from '../build/output/index'
import type { AmpPageStatus } from '../build/output/index'
import * as Log from '../build/output/log'
import { RSC_SUFFIX, SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants'
import { recursiveCopy } from '../lib/recursive-copy'
import {
BUILD_ID_FILE,
CLIENT_PUBLIC_FILES_PATH,
CLIENT_STATIC_FILES_PATH,
EXPORT_DETAIL,
EXPORT_MARKER,
NEXT_FONT_MANIFEST,
MIDDLEWARE_MANIFEST,
PAGES_MANIFEST,
PHASE_EXPORT,
PRERENDER_MANIFEST,
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST,
APP_PATH_ROUTES_MANIFEST,
} from '../shared/lib/constants'
import loadConfig from '../server/config'
import type { ExportPathMap } from '../server/config-shared'
import { eventCliSession } from '../telemetry/events'
import { hasNextSupport } from '../telemetry/ci-info'
import { Telemetry } from '../telemetry/storage'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { loadEnvConfig } from '@next/env'
import { isAPIRoute } from '../lib/is-api-route'
import { getPagePath } from '../server/require'
import type { Span } from '../trace'
import type { FontConfig } from '../server/font-utils'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import { isAppRouteRoute } from '../lib/is-app-route-route'
import { isAppPageRoute } from '../lib/is-app-page-route'
import isError from '../lib/is-error'
import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { formatManifest } from '../build/manifests/formatter/format-manifest'
import { validateRevalidate } from '../server/lib/patch-fetch'
import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace'
import { createProgress } from '../build/progress'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR'
}
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 { enabledDirectories } = options
const nextConfig =
options.nextConfig ||
(await span
.traceChild('load-next-config')
.traceAsyncFn(() => loadConfig(PHASE_EXPORT, dir)))
const distDir = join(dir, nextConfig.distDir)
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,
})
)
}
const subFolders = nextConfig.trailingSlash && !options.buildExport
if (!options.silent && !options.buildExport) {
Log.info(`using build directory: ${distDir}`)
}
const buildIdFile = join(distDir, BUILD_ID_FILE)
if (!existsSync(buildIdFile)) {
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: DeepReadonly<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 (
isError(err) &&
(err.code === 'ENOENT' || err.code === 'MODULE_NOT_FOUND')
) {
// the manifest doesn't exist which will happen when using
// "pages" dir instead of "app" dir.
appRoutePathManifest = undefined
} else {
// the manifest is malformed (invalid json)
throw err
}
}
const excludedPrerenderRoutes = new Set<string>()
const pages = options.pages || Object.keys(pagesManifest)
const defaultPathMap: ExportPathMap = {}
let hasApiRoutes = false
for (const page of pages) {
// _document and _app are not real pages
// _error is exported as 404.html later on
// API Routes are Node.js functions
if (isAPIRoute(page)) {
hasApiRoutes = true
continue
}
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 (
isAppPageRoute(pageName) &&
!prerenderManifest?.routes[routePath] &&
!prerenderManifest?.dynamicRoutes[routePath]
) {
defaultPathMap[routePath] = {
page: pageName,
_isAppDir: true,
}
}
}
}
// Initialize the output directory
const outDir = options.outdir
if (outDir === join(dir, 'public')) {
throw new ExportError(
`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`
)
}
if (outDir === join(dir, 'static')) {
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`
)
}
await fs.rm(outDir, { recursive: true, force: true })
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 && existsSync(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'))
)
}
// Copy .next/static directory
if (
!options.buildExport &&
existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))
) {
if (!options.silent) {
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)
)
)
}
// Get the exportPathMap from the config file
if (typeof nextConfig.exportPathMap !== 'function') {
nextConfig.exportPathMap = async (defaultMap) => {
return defaultMap
}
}
const {
i18n,
images: { loader = 'default', unoptimized },
} = nextConfig
if (i18n && !options.buildExport) {
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 (!options.buildExport) {
const { isNextImageImported } = await span
.traceChild('is-next-image-imported')
.traceAsyncFn(() =>
fs
.readFile(join(distDir, EXPORT_MARKER), 'utf8')
.then((text) => JSON.parse(text))
.catch(() => ({}))
)
if (
isNextImageImported &&
loader === 'default' &&
!unoptimized &&
!hasNextSupport
) {
throw new ExportError(
`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`
)
}
}
let serverActionsManifest
if (enabledDirectories.app) {
serverActionsManifest = require(
join(distDir, SERVER_DIRECTORY, SERVER_REFERENCE_MANIFEST + '.json')
)
if (nextConfig.output === 'export') {
if (
Object.keys(serverActionsManifest.node).length > 0 ||
Object.keys(serverActionsManifest.edge).length > 0
) {
throw new ExportError(
`Server Actions are not supported with static export.`
)
}
}
}
// Start the rendering process
const renderOpts: WorkerRenderOptsPartial = {
previewProps: prerenderManifest?.preview,
buildId,
nextExport: true,
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
distDir,
dev: false,
basePath: nextConfig.basePath,
trailingSlash: nextConfig.trailingSlash,
canonicalBase: nextConfig.amp?.canonicalBase || '',
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.
supportsDynamicResponse: false,
crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss,
nextConfigOutput: nextConfig.output,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
optimizeFonts: nextConfig.optimizeFonts as FontConfig,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverActions: nextConfig.experimental.serverActions,
serverComponents: enabledDirectories.app,
nextFontManifest: require(
join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)
),
images: nextConfig.images,
...(enabledDirectories.app
? {
serverActionsManifest,
}
: {}),
strictNextHead: nextConfig.experimental.strictNextHead ?? true,
deploymentId: nextConfig.deploymentId,
experimental: {
clientTraceMetadata: nextConfig.experimental.clientTraceMetadata,
swrDelta: nextConfig.swrDelta,
after: nextConfig.experimental.after ?? false,
},
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
if (Object.keys(publicRuntimeConfig).length > 0) {
renderOpts.runtimeConfig = publicRuntimeConfig
}
// We need this for server rendering the Link component.
;(globalThis as any).__NEXT_DATA__ = {
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' }
}
/**
* 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 exportPaths = [
...new Set(
Object.keys(exportPathMap).map((path) =>
denormalizePagePath(normalizePagePath(path))
)
),
]
const filteredPaths = exportPaths.filter(
(route) =>
exportPathMap[route]._isAppDir ||
// Remove API routes
!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]
if (prerenderInfo && prerenderInfo.fallback !== false) {
fallbackEnabledPages.add(page)
}
}
if (fallbackEnabledPages.size > 0) {
throw new ExportError(
`Found pages with \`fallback\` enabled:\n${[
...fallbackEnabledPages,
].join('\n')}\n${SSG_FALLBACK_EXPORT_ERROR}\n`
)
}
}
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
} catch {}
// Warn if the user defines a path for an API page
if (hasApiRoutes || hasMiddleware) {
if (nextConfig.output === 'export') {
Log.warn(
yellow(
`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`
) +
`\n` +
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`
)
)
}
}
}
const progress =
!options.silent &&
createProgress(filteredPaths.length, options.statusMessage || 'Exporting')
const pagesDataDir = options.buildExport
? outDir
: join(outDir, '_next/data', buildId)
const ampValidations: AmpPageStatus = {}
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
// Copy public directory
if (!options.buildExport && existsSync(publicDir)) {
if (!options.silent) {
Log.info('Copying "public" directory')
}
await span.traceChild('copy-public-directory').traceAsyncFn(() =>
recursiveCopy(publicDir, outDir, {
filter(path) {
// Exclude paths used by pages
return !exportPathMap[path]
},
})
)
}
const failedExportAttemptsByPage: Map<string, number> = new Map()
const maxAttempts = nextConfig.experimental.staticGenerationRetryCount ?? 1
const results = await Promise.all(
filteredPaths.map(async (path) => {
const pathMap = exportPathMap[path]
const exportPage = pathMap._isAppDir
? options.exportAppPageWorker
: options.exportPageWorker
if (!exportPage) {
throw new Error(
'Invariant: Undefined export worker for app dir, this is a bug in Next.js.'
)
}
const pageExportSpan = span.traceChild('export-page')
pageExportSpan.setAttribute('path', path)
const { page } = exportPathMap[path]
const pageKey = page !== path ? `${page}: ${path}` : path
let result
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
result = await pageExportSpan.traceAsyncFn(async () => {
return await exportPage({
dir,
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.getId(),
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
cacheMaxMemorySize: nextConfig.cacheMaxMemorySize,
fetchCache: true,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
cacheHandler: nextConfig.cacheHandler,
enableExperimentalReact: needsExperimentalReact(nextConfig),
enabledDirectories,
})
})
// If there was an error in the export, throw it immediately. In the catch block, we might retry the export,
// or immediately fail the build, depending on user configuration. We might also continue on and attempt other pages.
if (result && 'error' in result) {
throw new ExportError()
}
// If the export succeeds, break out of the retry loop
break
} catch (err) {
// The only error that should be caught here is an ExportError, as `exportPage` doesn't throw and instead returns an object with an `error` property.
// This is an overly cautious check to ensure that we don't accidentally catch an unexpected error.
if (!(err instanceof ExportError)) {
throw err
}
const currentCount = failedExportAttemptsByPage.get(pageKey) ?? 0
failedExportAttemptsByPage.set(pageKey, currentCount + 1)
// We've reached the maximum number of attempts
if (attempt >= maxAttempts - 1) {
// Log a message if we've reached the maximum number of attempts.
// We only care to do this if maxAttempts was configured.
if (maxAttempts > 0) {
Log.info(
`Failed to build ${pageKey} after ${maxAttempts} attempts.`
)
}
// If prerenderEarlyExit is enabled, we'll exit the build immediately.
if (nextConfig.experimental.prerenderEarlyExit) {
throw new ExportError(
`Export encountered an error on ${pageKey}, exiting the build.`
)
} else {
// Otherwise, this is a no-op. The build will continue, and a summary of failed pages will be displayed at the end.
}
} else {
// Otherwise, we have more attempts to make. Wait before retrying
Log.info(
`Failed to build ${pageKey} (attempt ${attempt + 1} of ${maxAttempts}). Retrying again shortly.`
)
await new Promise((r) => setTimeout(r, Math.random() * 500))
}
}
}
// if we eventually succeeded, remove the page from the failed attempts map
if (
failedExportAttemptsByPage.has(pageKey) &&
result &&
!('error' in result)
) {
failedExportAttemptsByPage.delete(pageKey)
}
if (progress) progress()
return { result, path }
})
)
let hadValidationError = false
const collector: ExportAppResult = {
byPath: new Map(),
byPage: new Map(),
ssgNotFoundPaths: new Set(),
turborepoAccessTraceResults: new Map(),
}
for (const { result, path } of results) {
if (!result || 'error' in result) continue
const { page } = exportPathMap[path]
if (result.turborepoAccessTraceResult) {
collector.turborepoAccessTraceResults?.set(
path,
TurborepoAccessTraceResult.fromSerialized(
result.turborepoAccessTraceResult
)
)
}
// Capture any amp validations.
if (result.ampValidations) {
for (const validation of result.ampValidations) {
ampValidations[validation.page] = validation.result
hadValidationError ||= validation.result.errors.length > 0
}
}
if (options.buildExport) {
// Update path info by path.
const info = collector.byPath.get(path) ?? {}
if (typeof result.revalidate !== 'undefined') {
info.revalidate = validateRevalidate(result.revalidate, path)
}
if (typeof result.metadata !== 'undefined') {
info.metadata = result.metadata
}
if (typeof result.hasEmptyPrelude !== 'undefined') {
info.hasEmptyPrelude = result.hasEmptyPrelude
}
if (typeof result.hasPostponed !== 'undefined') {
info.hasPostponed = result.hasPostponed
}
collector.byPath.set(path, info)
// Update not found.
if (result.ssgNotFound === true) {
collector.ssgNotFoundPaths.add(path)
}
// Update durations.
const durations = collector.byPage.get(page) ?? {
durationsByPath: new Map<string, number>(),
}
durations.durationsByPath.set(path, result.duration)
collector.byPage.set(page, durations)
}
}
// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message
throw new Error('Invariant: PPR cannot be enabled in export mode')
}
// copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) {
await Promise.all(
Object.keys(prerenderManifest.routes).map(async (route) => {
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)
const handlerSrc = `${orig}.body`
const handlerDest = join(outDir, route)
if (isAppRouteHandler && existsSync(handlerSrc)) {
await fs.mkdir(dirname(handlerDest), { recursive: true })
await fs.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 fs.mkdir(dirname(htmlDest), { recursive: true })
await fs.mkdir(dirname(jsonDest), { recursive: true })
const htmlSrc = `${orig}.html`
const jsonSrc = `${orig}${isAppPath ? RSC_SUFFIX : '.json'}`
await fs.copyFile(htmlSrc, htmlDest)
await fs.copyFile(jsonSrc, jsonDest)
if (existsSync(`${orig}.amp.html`)) {
await fs.mkdir(dirname(ampHtmlDest), { recursive: true })
await fs.copyFile(`${orig}.amp.html`, ampHtmlDest)
}
})
)
}
if (Object.keys(ampValidations).length) {
console.log(formatAmpMessages(ampValidations))
}
if (hadValidationError) {
throw new ExportError(
`AMP Validation caused the export to fail. https://nextjs.org/docs/messages/amp-export-validation`
)
}
if (failedExportAttemptsByPage.size > 0) {
const failedPages = Array.from(failedExportAttemptsByPage.keys())
throw new ExportError(
`Export encountered errors on following paths:\n\t${failedPages
.sort()
.join('\n\t')}`
)
}
await fs.writeFile(
join(distDir, EXPORT_DETAIL),
formatManifest({
version: 1,
outDirectory: outDir,
success: true,
}),
'utf8'
)
if (telemetry) {
await telemetry.flush()
}
await options.endWorker()
return collector
}
export default async function exportApp(
dir: string,
options: ExportAppOptions,
span: Span
): Promise<ExportAppResult | null> {
const nextExportSpan = span.traceChild('next-export')
return nextExportSpan.traceAsyncFn(async () => {
return await exportAppImpl(dir, options, nextExportSpan)
})
}