forked from vercel/next.js
/
next-serverless-loader.ts
343 lines (313 loc) · 10.8 KB
/
next-serverless-loader.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
import { loader } from 'webpack'
import { join } from 'path'
import { parse } from 'querystring'
import {
BUILD_MANIFEST,
ROUTES_MANIFEST,
REACT_LOADABLE_MANIFEST,
} from '../../../next-server/lib/constants'
import { isDynamicRoute } from '../../../next-server/lib/router/utils'
import { API_ROUTE } from '../../../lib/constants'
import escapeRegexp from 'escape-string-regexp'
export type ServerlessLoaderQuery = {
page: string
distDir: string
absolutePagePath: string
absoluteAppPath: string
absoluteDocumentPath: string
absoluteErrorPath: string
buildId: string
assetPrefix: string
generateEtags: string
canonicalBase: string
basePath: string
}
const nextServerlessLoader: loader.Loader = function() {
const {
distDir,
absolutePagePath,
page,
buildId,
canonicalBase,
assetPrefix,
absoluteAppPath,
absoluteDocumentPath,
absoluteErrorPath,
generateEtags,
basePath,
}: ServerlessLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
/\\/g,
'/'
)
const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, '/')
const escapedBuildId = escapeRegexp(buildId)
const pageIsDynamicRoute = isDynamicRoute(page)
const dynamicRouteImports = pageIsDynamicRoute
? `
import { getRouteMatcher } from 'next/dist/next-server/lib/router/utils/route-matcher';
import { getRouteRegex } from 'next/dist/next-server/lib/router/utils/route-regex';
`
: ''
const dynamicRouteMatcher = pageIsDynamicRoute
? `
const dynamicRouteMatcher = getRouteMatcher(getRouteRegex("${page}"))
`
: ''
const rewriteImports = `
import { rewrites } from '${routesManifest}'
import pathMatch, { pathToRegexp } from 'next/dist/next-server/server/lib/path-match'
`
const handleRewrites = `
const getCustomRouteMatcher = pathMatch(true)
function handleRewrites(parsedUrl) {
for (const rewrite of rewrites) {
const matcher = getCustomRouteMatcher(rewrite.source)
const params = matcher(parsedUrl.pathname)
if (params) {
parsedUrl.query = {
...parsedUrl.query,
...params
}
const parsedDest = parse(rewrite.destination)
const destCompiler = pathToRegexp.compile(
\`\${parsedDest.pathname}\${parsedDest.hash || ''}\`
)
const newUrl = destCompiler(params)
const parsedNewUrl = parse(newUrl)
parsedUrl.pathname = parsedNewUrl.pathname
parsedUrl.hash = parsedNewUrl.hash
if (parsedUrl.pathname === '${page}'){
break
}
${
pageIsDynamicRoute
? `
const dynamicParams = dynamicRouteMatcher(parsedUrl.pathname);\
if (dynamicParams) {
parsedUrl.query = {
...parsedUrl.query,
...dynamicParams
}
break
}
`
: ''
}
}
}
return parsedUrl
}
`
if (page.match(API_ROUTE)) {
return `
${dynamicRouteImports}
import { parse } from 'url'
import { apiResolver } from 'next/dist/next-server/server/api-utils'
import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!'
${rewriteImports}
${dynamicRouteMatcher}
${handleRewrites}
export default async (req, res) => {
try {
await initServer()
${
basePath
? `
if(req.url.startsWith('${basePath}')) {
req.url = req.url.replace('${basePath}', '')
}
`
: ''
}
const parsedUrl = parse(req.url, true)
const params = ${
pageIsDynamicRoute
? `dynamicRouteMatcher(parsedUrl.pathname)`
: `{}`
}
const resolver = require('${absolutePagePath}')
apiResolver(
req,
res,
Object.assign({}, parsedUrl.query, params ),
resolver,
onError
)
} catch (err) {
console.error(err)
await onError(err)
res.statusCode = 500
res.end('Internal Server Error')
}
}
`
} else {
return `
import {parse} from 'url'
import {parse as parseQs} from 'querystring'
import {renderToHTML} from 'next/dist/next-server/server/render';
import {sendHTML} from 'next/dist/next-server/server/send-html';
import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!'
import buildManifest from '${buildManifest}';
import reactLoadableManifest from '${reactLoadableManifest}';
import Document from '${absoluteDocumentPath}';
import Error from '${absoluteErrorPath}';
import App from '${absoluteAppPath}';
import * as ComponentInfo from '${absolutePagePath}';
${dynamicRouteImports}
${rewriteImports}
const Component = ComponentInfo.default
export default Component
export const unstable_getStaticProps = ComponentInfo['unstable_getStaticProp' + 's']
export const unstable_getStaticParams = ComponentInfo['unstable_getStaticParam' + 's']
export const unstable_getStaticPaths = ComponentInfo['unstable_getStaticPath' + 's']
export const unstable_getServerProps = ComponentInfo['unstable_getServerProp' + 's']
${dynamicRouteMatcher}
${handleRewrites}
export const config = ComponentInfo['confi' + 'g'] || {}
export const _app = App
export async function renderReqToHTML(req, res, fromExport, _renderOpts, _params) {
${
basePath
? `
if(req.url.startsWith('${basePath}')) {
req.url = req.url.replace('${basePath}', '')
}
`
: ''
}
const options = {
App,
Document,
buildManifest,
unstable_getStaticProps,
unstable_getServerProps,
unstable_getStaticPaths,
reactLoadableManifest,
canonicalBase: "${canonicalBase}",
buildId: "${buildId}",
assetPrefix: "${assetPrefix}",
..._renderOpts
}
let _nextData = false
const parsedUrl = handleRewrites(parse(req.url, true))
if (parsedUrl.pathname.match(/_next\\/data/)) {
_nextData = true
parsedUrl.pathname = parsedUrl.pathname
.replace(new RegExp('/_next/data/${escapedBuildId}/'), '/')
.replace(/\\.json$/, '')
}
const renderOpts = Object.assign(
{
Component,
pageConfig: config,
nextExport: fromExport
},
options,
)
try {
${page === '/_error' ? `res.statusCode = 404` : ''}
${
pageIsDynamicRoute
? `const params = fromExport && !unstable_getStaticProps && !unstable_getServerProps ? {} : dynamicRouteMatcher(parsedUrl.pathname) || {};`
: `const params = {};`
}
${
// Temporary work around: `x-now-route-matches` is a platform header
// _only_ set for `Prerender` requests. We should move this logic
// into our builder to ensure we're decoupled. However, this entails
// removing reliance on `req.url` and using `req.query` instead
// (which is needed for "custom routes" anyway).
pageIsDynamicRoute
? `const nowParams = req.headers && req.headers["x-now-route-matches"]
? getRouteMatcher(
(function() {
const { re, groups } = getRouteRegex("${page}");
return {
re: {
// Simulate a RegExp match from the \`req.url\` input
exec: str => {
const obj = parseQs(str);
return Object.keys(obj).reduce(
(prev, key) =>
Object.assign(prev, {
[key]: encodeURIComponent(obj[key])
}),
{}
);
}
},
groups
};
})()
)(req.headers["x-now-route-matches"])
: null;
`
: `const nowParams = null;`
}
// make sure to set renderOpts to the correct params e.g. _params
// if provided from worker or params if we're parsing them here
renderOpts.params = _params || params
let result = await renderToHTML(req, res, "${page}", Object.assign({}, unstable_getStaticProps ? {} : parsedUrl.query, nowParams ? nowParams : params, _params), renderOpts)
if (_nextData && !fromExport) {
const payload = JSON.stringify(renderOpts.pageData)
res.setHeader('Content-Type', 'application/json')
res.setHeader('Content-Length', Buffer.byteLength(payload))
res.setHeader(
'Cache-Control',
unstable_getServerProps
? \`no-cache, no-store, must-revalidate\`
: \`s-maxage=\${renderOpts.revalidate}, stale-while-revalidate\`
)
res.end(payload)
return null
}
if (fromExport) return { html: result, renderOpts }
return result
} catch (err) {
if (err.code === 'ENOENT') {
res.statusCode = 404
const result = await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
unstable_getStaticProps: undefined,
unstable_getStaticPaths: undefined,
unstable_getServerProps: undefined,
Component: Error
}))
return result
} else {
console.error(err)
res.statusCode = 500
const result = await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
unstable_getStaticProps: undefined,
unstable_getStaticPaths: undefined,
unstable_getServerProps: undefined,
Component: Error,
err
}))
return result
}
}
}
export async function render (req, res) {
try {
await initServer()
const html = await renderReqToHTML(req, res)
if (html) {
sendHTML(req, res, html, {generateEtags: ${generateEtags}})
}
} catch(err) {
await onError(err)
console.error(err)
res.statusCode = 500
res.end('Internal Server Error')
}
}
`
}
}
export default nextServerlessLoader