forked from vercel/next.js
/
worker.ts
462 lines (419 loc) · 15.4 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
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
import url from 'url'
import { extname, join, dirname, sep } from 'path'
import { renderToHTML } from '../next-server/server/render'
import { promises } from 'fs'
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import { loadComponents } from '../next-server/server/load-components'
import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
import { getRouteMatcher } from '../next-server/lib/router/utils/route-matcher'
import { getRouteRegex } from '../next-server/lib/router/utils/route-regex'
import { normalizePagePath } from '../next-server/server/normalize-page-path'
import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants'
import 'next/dist/next-server/server/node-polyfill-fetch'
import { IncomingMessage, ServerResponse } from 'http'
import { ComponentType } from 'react'
import { GetStaticProps } from '../types'
import { requireFontManifest } from '../next-server/server/require'
import { FontManifest } from '../next-server/server/font-utils'
import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-path'
import { tracer, traceAsyncFn } from '../build/tracer'
import opentelemetryApi from '@opentelemetry/api'
const envConfig = require('../next-server/lib/runtime-config')
;(global as any).__NEXT_DATA__ = {
nextExport: true,
}
interface AmpValidation {
page: string
result: {
errors: AmpHtmlValidator.ValidationError[]
warnings: AmpHtmlValidator.ValidationError[]
}
}
interface PathMap {
page: string
query?: { [key: string]: string | string[] }
}
interface ExportPageInput {
path: string
pathMap: PathMap
distDir: string
outDir: string
pagesDataDir: string
renderOpts: RenderOpts
buildExport?: boolean
serverRuntimeConfig: string
subFolders?: boolean
serverless: boolean
optimizeFonts: boolean
optimizeImages: boolean
optimizeCss: any
spanContext: any
}
interface ExportPageResults {
ampValidations: AmpValidation[]
fromBuildExportRevalidate?: number
error?: boolean
ssgNotFound?: boolean
}
interface RenderOpts {
runtimeConfig?: { [key: string]: any }
params?: { [key: string]: string | string[] }
ampPath?: string
ampValidatorPath?: string
ampSkipValidation?: boolean
hybridAmp?: boolean
inAmpMode?: boolean
optimizeFonts?: boolean
optimizeImages?: boolean
optimizeCss?: any
fontManifest?: FontManifest
locales?: string[]
locale?: string
defaultLocale?: string
}
type ComponentModule = ComponentType<{}> & {
renderReqToHTML: typeof renderToHTML
getStaticProps?: GetStaticProps
}
export default async function exportPage({
spanContext,
path,
pathMap,
distDir,
outDir,
pagesDataDir,
renderOpts,
buildExport,
serverRuntimeConfig,
subFolders,
serverless,
optimizeFonts,
optimizeImages,
optimizeCss,
}: ExportPageInput): Promise<ExportPageResults> {
return opentelemetryApi.context.with(
opentelemetryApi.propagation.extract(
opentelemetryApi.context.active(),
spanContext
),
() => {
return traceAsyncFn(tracer.startSpan('export-page-worker'), async () => {
let results: ExportPageResults = {
ampValidations: [],
}
try {
const { query: originalQuery = {} } = pathMap
const { page } = pathMap
const filePath = normalizePagePath(path)
const isDynamic = isDynamicRoute(page)
const ampPath = `${filePath}.amp`
let renderAmpPath = ampPath
let query = { ...originalQuery }
let params: { [key: string]: string | string[] } | undefined
let updatedPath = (query.__nextSsgPath as string) || path
let locale = query.__nextLocale || renderOpts.locale
delete query.__nextLocale
delete query.__nextSsgPath
if (renderOpts.locale) {
const localePathResult = normalizeLocalePath(
path,
renderOpts.locales
)
if (localePathResult.detectedLocale) {
updatedPath = localePathResult.pathname
locale = localePathResult.detectedLocale
if (locale === 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
const queryWithAutoExportWarn = () => {
if (hasOrigQueryValues) {
throw new Error(
`\nError: you provided query values for ${path} which is an auto-exported page. These can not be applied since the page can no longer be re-rendered on the server. To disable auto-export for this page add \`getInitialProps\`\n`
)
}
}
// Check if the page is a specified dynamic route
if (isDynamic && page !== path) {
params =
getRouteMatcher(getRouteRegex(page))(updatedPath) || undefined
if (params) {
// we have to pass these separately for serverless
if (!serverless) {
query = {
...query,
...params,
}
}
} else {
throw new Error(
`The provided export path '${updatedPath}' doesn't match the '${page}' page.\nRead more: https://err.sh/vercel/next.js/export-path-mismatch`
)
}
}
const headerMocks = {
headers: {},
getHeader: () => ({}),
setHeader: () => {},
hasHeader: () => false,
removeHeader: () => {},
getHeaderNames: () => [],
}
const req = ({
url: updatedPath,
...headerMocks,
} as unknown) as IncomingMessage
const res = ({
...headerMocks,
} as unknown) as ServerResponse
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig: renderOpts.runtimeConfig,
})
let htmlFilename = `${filePath}${sep}index.html`
if (!subFolders) htmlFilename = `${filePath}.html`
const pageExt = extname(page)
const pathExt = extname(path)
// Make sure page isn't a folder with a dot in the name e.g. `v1.2`
if (pageExt !== pathExt && pathExt !== '') {
// If the path has an extension, use that as the filename instead
htmlFilename = 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 promises.mkdir(baseDir, { recursive: true })
let html
let curRenderOpts: RenderOpts = {}
let renderMethod = renderToHTML
const renderedDuringBuild = (getStaticProps: any) => {
return !buildExport && getStaticProps && !isDynamicRoute(path)
}
if (serverless) {
const curUrl = url.parse(req.url!, true)
req.url = url.format({
...curUrl,
query: {
...curUrl.query,
...query,
},
})
const { Component: mod, getServerSideProps } = await loadComponents(
distDir,
page,
serverless
)
if (getServerSideProps) {
throw new Error(
`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`
)
}
// if it was auto-exported the HTML is loaded here
if (typeof mod === 'string') {
html = mod
queryWithAutoExportWarn()
} else {
// for non-dynamic SSG pages we should have already
// prerendered the file
if (renderedDuringBuild((mod as ComponentModule).getStaticProps))
return results
if (
(mod as ComponentModule).getStaticProps &&
!htmlFilepath.endsWith('.html')
) {
// make sure it ends with .html if the name contains a dot
htmlFilename += '.html'
htmlFilepath += '.html'
}
renderMethod = (mod as ComponentModule).renderReqToHTML
const result = await renderMethod(
req,
res,
'export',
{
ampPath: renderAmpPath,
/// @ts-ignore
optimizeFonts,
/// @ts-ignore
optimizeImages,
/// @ts-ignore
optimizeCss,
distDir,
fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless)
: null,
locale: locale!,
locales: renderOpts.locales!,
},
// @ts-ignore
params
)
curRenderOpts = (result as any).renderOpts || {}
html = (result as any).html
}
if (!html && !(curRenderOpts as any).isNotFound) {
throw new Error(`Failed to render serverless page`)
}
} else {
const components = await loadComponents(distDir, page, serverless)
if (components.getServerSideProps) {
throw new Error(
`Error for page ${page}: ${SERVER_PROPS_EXPORT_ERROR}`
)
}
// for non-dynamic SSG pages we should have already
// prerendered the file
if (renderedDuringBuild(components.getStaticProps)) {
return results
}
// TODO: de-dupe the logic here between serverless and server mode
if (components.getStaticProps && !htmlFilepath.endsWith('.html')) {
// make sure it ends with .html if the name contains a dot
htmlFilepath += '.html'
htmlFilename += '.html'
}
if (typeof components.Component === 'string') {
html = components.Component
queryWithAutoExportWarn()
} else {
/**
* This sets environment variable to be used at the time of static export by head.tsx.
* Using this from process.env allows targeting both serverless and SSR by calling
* `process.env.__NEXT_OPTIMIZE_FONTS`.
* TODO(prateekbh@): Remove this when experimental.optimizeFonts are being cleaned up.
*/
if (optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
}
if (optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
}
if (optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
curRenderOpts = {
...components,
...renderOpts,
ampPath: renderAmpPath,
params,
optimizeFonts,
optimizeImages,
optimizeCss,
fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless)
: null,
locale: locale as string,
}
// @ts-ignore
html = await renderMethod(req, res, page, query, curRenderOpts)
}
}
results.ssgNotFound = (curRenderOpts as any).isNotFound
const validateAmp = async (
rawAmpHtml: string,
ampPageName: string,
validatorPath?: string
) => {
const validator = await AmpHtmlValidator.getInstance(validatorPath)
const result = validator.validateString(rawAmpHtml)
const errors = result.errors.filter((e) => e.severity === 'ERROR')
const warnings = result.errors.filter((e) => e.severity !== 'ERROR')
if (warnings.length || errors.length) {
results.ampValidations.push({
page: ampPageName,
result: {
errors,
warnings,
},
})
}
}
if (curRenderOpts.inAmpMode && !curRenderOpts.ampSkipValidation) {
if (!results.ssgNotFound) {
await validateAmp(html, path, curRenderOpts.ampValidatorPath)
}
} else if (curRenderOpts.hybridAmp) {
// we need to render the AMP version
let ampHtmlFilename = `${ampPath}${sep}index.html`
if (!subFolders) {
ampHtmlFilename = `${ampPath}.html`
}
const ampBaseDir = join(outDir, dirname(ampHtmlFilename))
const ampHtmlFilepath = join(outDir, ampHtmlFilename)
try {
await promises.access(ampHtmlFilepath)
} catch (_) {
// make sure it doesn't exist from manual mapping
let ampHtml
if (serverless) {
req.url += (req.url!.includes('?') ? '&' : '?') + 'amp=1'
// @ts-ignore
ampHtml = (
await (renderMethod as any)(
req,
res,
'export',
curRenderOpts,
params
)
).html
} else {
ampHtml = await renderMethod(
req,
res,
page,
// @ts-ignore
{ ...query, amp: '1' },
curRenderOpts as any
)
}
if (!curRenderOpts.ampSkipValidation) {
await validateAmp(ampHtml, page + '?amp=1')
}
await promises.mkdir(ampBaseDir, { recursive: true })
await promises.writeFile(ampHtmlFilepath, ampHtml, 'utf8')
}
}
if ((curRenderOpts as any).pageData) {
const dataFile = join(
pagesDataDir,
htmlFilename.replace(/\.html$/, '.json')
)
await promises.mkdir(dirname(dataFile), { recursive: true })
await promises.writeFile(
dataFile,
JSON.stringify((curRenderOpts as any).pageData),
'utf8'
)
if (curRenderOpts.hybridAmp) {
await promises.writeFile(
dataFile.replace(/\.json$/, '.amp.json'),
JSON.stringify((curRenderOpts as any).pageData),
'utf8'
)
}
}
results.fromBuildExportRevalidate = (curRenderOpts as any).revalidate
if (results.ssgNotFound) {
// don't attempt writing to disk if getStaticProps returned not found
return results
}
await promises.writeFile(htmlFilepath, html, 'utf8')
return results
} catch (error) {
console.error(
`\nError occurred prerendering page "${path}". Read more: https://err.sh/next.js/prerender-error\n` +
error.stack
)
return { ...results, error: true }
}
})
}
)
}