/
worker.ts
365 lines (312 loc) · 10.1 KB
/
worker.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
import type { FontConfig } from '../server/font-utils'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type {
ExportPageResult,
WorkerRenderOpts,
WorkerRenderOptsPartial,
} from './types'
// Polyfill fetch for the export worker.
import '../server/node-polyfill-fetch'
import '../server/node-polyfill-web-streams'
import '../server/node-environment'
process.env.NEXT_IS_EXPORT_WORKER = 'true'
import { extname, join, dirname, sep } from 'path'
import fs from 'fs'
import { loadComponents } from '../server/load-components'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { requireFontManifest } from '../server/require'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { trace } from '../trace'
import { setHttpClientAndAgentOptions } from '../server/setup-http-agent-env'
import isError from '../lib/is-error'
import { addRequestMeta } from '../server/request-meta'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { createRequestResponseMocks } from '../server/lib/mock-request'
import { isAppRouteRoute } from '../lib/is-app-route-route'
import { hasNextSupport } from '../telemetry/ci-info'
import { exportAppRoute } from './routes/app-route'
import { exportAppPage } from './routes/app-page'
import { exportPages } from './routes/pages'
import { getParams } from './helpers/get-params'
import { createIncrementalCache } from './helpers/create-incremental-cache'
const envConfig = require('../shared/lib/runtime-config.external')
;(globalThis as any).__NEXT_DATA__ = {
nextExport: true,
}
type PathMap = ExportPathMap[keyof ExportPathMap]
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 interface ExportPageResults extends ExportPageResult {
duration: number
}
async function exportPageImpl(input: ExportPageInput) {
const {
path,
pathMap,
distDir,
pagesDataDir,
buildExport = false,
serverRuntimeConfig,
subFolders = false,
optimizeFonts,
optimizeCss,
disableOptimizedLoading,
debugOutput = false,
isrMemoryCacheSize,
fetchCache,
fetchCacheKeyPrefix,
incrementalCacheHandlerPath,
enableExperimentalReact,
ampValidatorPath,
trailingSlash,
} = input
if (input.renderOpts.deploymentId) {
process.env.NEXT_DEPLOYMENT_ID = input.renderOpts.deploymentId
}
if (enableExperimentalReact) {
process.env.__NEXT_EXPERIMENTAL_REACT = 'true'
}
const {
page,
// Check if this is an `app/` page.
_isAppDir: isAppDir = false,
// Check if this is an `app/` prefix request.
_isAppPrefetch: isAppPrefetch = false,
// Check if this should error when dynamic usage is detected.
_isDynamicError: isDynamicError = false,
// Pull the original query out.
query: originalQuery = {},
} = pathMap
try {
let query = { ...originalQuery }
const pathname = normalizeAppPath(page)
const isDynamic = isDynamicRoute(page)
const outDir = isAppDir ? join(distDir, 'server/app') : input.outDir
let params: { [key: string]: string | string[] } | undefined
const filePath = normalizePagePath(path)
const ampPath = `${filePath}.amp`
let renderAmpPath = ampPath
let updatedPath = query.__nextSsgPath || path
delete query.__nextSsgPath
let locale = query.__nextLocale || input.renderOpts.locale
delete query.__nextLocale
if (input.renderOpts.locale) {
const localePathResult = normalizeLocalePath(
path,
input.renderOpts.locales
)
if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname
locale = localePathResult.detectedLocale
if (locale === input.renderOpts.defaultLocale) {
renderAmpPath = `${normalizePagePath(updatedPath)}.amp`
}
}
}
// We need to show a warning if they try to provide query values
// for an auto-exported page since they won't be available
const hasOrigQueryValues = Object.keys(originalQuery).length > 0
// Check if the page is a specified dynamic route
const { pathname: nonLocalizedPath } = normalizeLocalePath(
path,
input.renderOpts.locales
)
if (isDynamic && page !== nonLocalizedPath) {
const normalizedPage = isAppDir ? normalizeAppPath(page) : page
params = getParams(normalizedPage, updatedPath)
if (params) {
query = {
...query,
...params,
}
}
}
const { req, res } = createRequestResponseMocks({ url: updatedPath })
// If this is a status code page, then set the response code.
for (const statusCode of [404, 500]) {
if (
[
`/${statusCode}`,
`/${statusCode}.html`,
`/${statusCode}/index.html`,
].some((p) => p === updatedPath || `/${locale}${p}` === updatedPath)
) {
res.statusCode = statusCode
}
}
// Ensure that the URL has a trailing slash if it's configured.
if (trailingSlash && !req.url?.endsWith('/')) {
req.url += '/'
}
if (
locale &&
buildExport &&
input.renderOpts.domainLocales &&
input.renderOpts.domainLocales.some(
(dl) =>
dl.defaultLocale === locale || dl.locales?.includes(locale || '')
)
) {
addRequestMeta(req, '__nextIsLocaleDomain', true)
}
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig: input.renderOpts.runtimeConfig,
})
const getHtmlFilename = (p: string) =>
subFolders ? `${p}${sep}index.html` : `${p}.html`
let htmlFilename = getHtmlFilename(filePath)
// dynamic routes can provide invalid extensions e.g. /blog/[...slug] returns an
// extension of `.slug]`
const pageExt = isDynamic || isAppDir ? '' : extname(page)
const pathExt = isDynamic || isAppDir ? '' : extname(path)
// force output 404.html for backwards compat
if (path === '/404.html') {
htmlFilename = path
}
// Make sure page isn't a folder with a dot in the name e.g. `v1.2`
else if (pageExt !== pathExt && pathExt !== '') {
const isBuiltinPaths = ['/500', '/404'].some(
(p) => p === path || p === path + '.html'
)
// If the ssg path has .html extension, and it's not builtin paths, use it directly
// Otherwise, use that as the filename instead
const isHtmlExtPath = !isBuiltinPaths && path.endsWith('.html')
htmlFilename = isHtmlExtPath ? getHtmlFilename(path) : path
} else if (path === '/') {
// If the path is the root, just use index.html
htmlFilename = 'index.html'
}
const baseDir = join(outDir, dirname(htmlFilename))
let htmlFilepath = join(outDir, htmlFilename)
await fs.promises.mkdir(baseDir, { recursive: true })
// If the fetch cache was enabled, we need to create an incremental
// cache instance for this page.
const incrementalCache =
isAppDir && fetchCache
? createIncrementalCache(
incrementalCacheHandlerPath,
isrMemoryCacheSize,
fetchCacheKeyPrefix,
distDir
)
: undefined
// Handle App Routes.
if (isAppDir && isAppRouteRoute(page)) {
return await exportAppRoute(
req,
res,
params,
page,
incrementalCache,
distDir,
htmlFilepath
)
}
const components = await loadComponents({
distDir,
page,
isAppPath: isAppDir,
})
const renderOpts: WorkerRenderOpts = {
...components,
...input.renderOpts,
ampPath: renderAmpPath,
params,
optimizeFonts,
optimizeCss,
disableOptimizedLoading,
fontManifest: optimizeFonts ? requireFontManifest(distDir) : null,
locale,
supportsDynamicHTML: false,
originalPathname: page,
}
if (hasNextSupport) {
renderOpts.isRevalidate = true
}
// Handle App Pages
if (isAppDir) {
// Set the incremental cache on the renderOpts, that's how app page's
// consume it.
renderOpts.incrementalCache = incrementalCache
return await exportAppPage(
req,
res,
page,
path,
pathname,
query,
renderOpts,
htmlFilepath,
debugOutput,
isDynamicError,
isAppPrefetch
)
}
return await exportPages(
req,
res,
path,
page,
query,
htmlFilepath,
htmlFilename,
ampPath,
subFolders,
outDir,
ampValidatorPath,
pagesDataDir,
buildExport,
isDynamic,
hasOrigQueryValues,
renderOpts,
components
)
} catch (err) {
console.error(
`\nError occurred prerendering page "${path}". Read more: https://nextjs.org/docs/messages/prerender-error\n` +
(isError(err) && err.stack ? err.stack : err)
)
return { error: true }
}
}
export default async function exportPage(
input: ExportPageInput
): Promise<ExportPageResults> {
// Configure the http agent.
setHttpClientAndAgentOptions({
httpAgentOptions: input.httpAgentOptions,
})
const exportPageSpan = trace('export-page-worker', input.parentSpanId)
const start = Date.now()
// Export the page.
const results = await exportPageSpan.traceAsyncFn(async () => {
return await exportPageImpl(input)
})
// Return it's results.
return { ...results, duration: Date.now() - start }
}