-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathedge.ts
504 lines (449 loc) · 16 KB
/
edge.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
import { promises as fs, existsSync } from 'fs'
import { resolve, join } from 'path'
import type { NetlifyConfig, NetlifyPluginConstants } from '@netlify/build'
import { greenBright } from 'chalk'
import destr from 'destr'
import { copy, copyFile, emptyDir, ensureDir, readJSON, readJson, writeJSON, writeJson } from 'fs-extra'
import type { PrerenderManifest } from 'next/dist/build'
import type { MiddlewareManifest } from 'next/dist/build/webpack/plugins/middleware-plugin'
import type { RouteHas } from 'next/dist/lib/load-custom-routes'
import { outdent } from 'outdent'
import { getRequiredServerFiles, NextConfig } from './config'
import { makeLocaleOptional, stripLookahead, transformCaptureGroups } from './matchers'
import { RoutesManifest } from './types'
// This is the format as of [email protected]
interface EdgeFunctionDefinitionV1 {
env: string[]
files: string[]
name: string
page: string
regexp: string
}
interface AssetRef {
name: string
filePath: string
}
export interface MiddlewareMatcher {
regexp: string
locale?: false
has?: RouteHas[]
}
// This is the format after [email protected]
interface EdgeFunctionDefinitionV2 {
env: string[]
files: string[]
name: string
page: string
matchers: MiddlewareMatcher[]
wasm?: AssetRef[]
assets?: AssetRef[]
}
type EdgeFunctionDefinition = EdgeFunctionDefinitionV1 | EdgeFunctionDefinitionV2
export interface FunctionManifest {
version: 1
functions: Array<
| {
function: string
name?: string
path: string
cache?: 'manual'
}
| {
function: string
name?: string
pattern: string
cache?: 'manual'
}
>
import_map?: string
}
const maybeLoadJson = <T>(path: string): Promise<T> | null => {
if (existsSync(path)) {
return readJson(path)
}
}
export const isAppDirRoute = (route: string, appPathRoutesManifest: Record<string, string> | null): boolean =>
Boolean(appPathRoutesManifest) && Object.values(appPathRoutesManifest).includes(route)
export const loadMiddlewareManifest = (netlifyConfig: NetlifyConfig): Promise<MiddlewareManifest | null> =>
maybeLoadJson(resolve(netlifyConfig.build.publish, 'server', 'middleware-manifest.json'))
export const loadAppPathRoutesManifest = (netlifyConfig: NetlifyConfig): Promise<Record<string, string> | null> =>
maybeLoadJson(resolve(netlifyConfig.build.publish, 'app-path-routes-manifest.json'))
export const loadPrerenderManifest = (netlifyConfig: NetlifyConfig): Promise<PrerenderManifest> =>
readJSON(resolve(netlifyConfig.build.publish, 'prerender-manifest.json'))
/**
* Convert the Next middleware name into a valid Edge Function name
*/
const sanitizeName = (name: string) => `next_${name.replace(/\W/g, '_')}`
/**
* Initialization added to the top of the edge function bundle
*/
const preamble = /* js */ `
import {
decode as _base64Decode,
} from "https://deno.land/[email protected]/encoding/base64.ts";
// Deno defines "window", but naughty libraries think this means it's a browser
delete globalThis.window
globalThis.process = { env: {...Deno.env.toObject(), NEXT_RUNTIME: 'edge', 'NEXT_PRIVATE_MINIMAL_MODE': '1' } }
globalThis.EdgeRuntime = "netlify-edge"
let _ENTRIES = {}
// Next.js uses this extension to the Headers API implemented by Cloudflare workerd
if(!('getAll' in Headers.prototype)) {
Headers.prototype.getAll = function getAll(name) {
name = name.toLowerCase();
if (name !== "set-cookie") {
throw new Error("Headers.getAll is only supported for Set-Cookie");
}
return [...this.entries()]
.filter(([key]) => key === name)
.map(([, value]) => value);
};
}
// Next uses blob: urls to refer to local assets, so we need to intercept these
const _fetch = globalThis.fetch
const fetch = async (url, init) => {
try {
if (typeof url === 'object' && url.href?.startsWith('blob:')) {
const key = url.href.slice(5)
if (key in _ASSETS) {
return new Response(_base64Decode(_ASSETS[key]))
}
}
return await _fetch(url, init)
} catch (error) {
console.error(error)
throw error
}
}
// Next edge runtime uses "self" as a function-scoped global-like object, but some of the older polyfills expect it to equal globalThis
// See https://nextjs.org/docs/basic-features/supported-browsers-features#polyfills
const self = { ...globalThis, fetch }
`
// Slightly different spacing in different versions!
const IMPORT_UNSUPPORTED = [
`Object.defineProperty(globalThis,"__import_unsupported"`,
` Object.defineProperty(globalThis, "__import_unsupported"`,
]
/**
* Concatenates the Next edge function code with the required chunks and adds an export
*/
const getMiddlewareBundle = async ({
edgeFunctionDefinition,
netlifyConfig,
}: {
edgeFunctionDefinition: EdgeFunctionDefinition
netlifyConfig: NetlifyConfig
}): Promise<string> => {
const { publish } = netlifyConfig.build
const chunks: Array<string> = [preamble]
if ('wasm' in edgeFunctionDefinition) {
for (const { name, filePath } of edgeFunctionDefinition.wasm) {
const wasm = await fs.readFile(join(publish, filePath))
chunks.push(`const ${name} = _base64Decode(${JSON.stringify(wasm.toString('base64'))}).buffer`)
}
}
if ('assets' in edgeFunctionDefinition) {
chunks.push(`const _ASSETS = {}`)
for (const { name, filePath } of edgeFunctionDefinition.assets) {
const wasm = await fs.readFile(join(publish, filePath))
chunks.push(`_ASSETS[${JSON.stringify(name)}] = ${JSON.stringify(wasm.toString('base64'))}`)
}
}
for (const file of edgeFunctionDefinition.files) {
const filePath = join(publish, file)
let data = await fs.readFile(filePath, 'utf8')
// Next defines an immutable global variable, which is fine unless you have more than one in the bundle
// This adds a check to see if the global is already defined
data = IMPORT_UNSUPPORTED.reduce(
(acc, val) => acc.replace(val, `('__import_unsupported' in globalThis)||${val}`),
data,
)
chunks.push('{', data, '}')
}
const exports = /* js */ `export default _ENTRIES["middleware_${edgeFunctionDefinition.name}"].default;`
chunks.push(exports)
return chunks.join('\n')
}
const getEdgeTemplatePath = (file: string) => join(__dirname, '..', '..', 'src', 'templates', 'edge', file)
const copyEdgeSourceFile = ({
file,
target,
edgeFunctionDir,
}: {
file: string
edgeFunctionDir: string
target?: string
}) => fs.copyFile(getEdgeTemplatePath(file), join(edgeFunctionDir, target ?? file))
const writeEdgeFunction = async ({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
functionName,
matchers = [],
middleware = false,
}: {
edgeFunctionDefinition: EdgeFunctionDefinition
edgeFunctionRoot: string
netlifyConfig: NetlifyConfig
functionName: string
matchers?: Array<MiddlewareMatcher>
middleware?: boolean
}) => {
const edgeFunctionDir = join(edgeFunctionRoot, functionName)
const bundle = await getMiddlewareBundle({
edgeFunctionDefinition,
netlifyConfig,
})
await ensureDir(edgeFunctionDir)
await fs.writeFile(join(edgeFunctionDir, 'bundle.js'), bundle)
await copyEdgeSourceFile({
edgeFunctionDir,
file: middleware ? 'middleware-runtime.ts' : 'function-runtime.ts',
target: 'index.ts',
})
if (middleware) {
// Functions don't have complex matchers, so we can rely on the Netlify matcher
await writeJson(join(edgeFunctionDir, 'matchers.json'), matchers)
}
}
const generateEdgeFunctionMiddlewareMatchers = ({
edgeFunctionDefinition,
nextConfig,
}: {
edgeFunctionDefinition: EdgeFunctionDefinition
edgeFunctionRoot: string
nextConfig: NextConfig
cache?: 'manual'
}): Array<MiddlewareMatcher> => {
// The v1 middleware manifest has a single regexp, but the v2 has an array of matchers
if ('regexp' in edgeFunctionDefinition) {
return [{ regexp: edgeFunctionDefinition.regexp }]
}
if (nextConfig.i18n) {
return edgeFunctionDefinition.matchers.map((matcher) => ({
...matcher,
regexp: makeLocaleOptional(matcher.regexp),
}))
}
return edgeFunctionDefinition.matchers
}
const middlewareMatcherToEdgeFunctionDefinition = (
matcher: MiddlewareMatcher,
name: string,
cache?: 'manual',
): {
function: string
name?: string
pattern: string
cache?: 'manual'
} => {
const pattern = transformCaptureGroups(stripLookahead(matcher.regexp))
return { function: name, pattern, name, cache }
}
export const cleanupEdgeFunctions = ({
INTERNAL_EDGE_FUNCTIONS_SRC = '.netlify/edge-functions',
}: NetlifyPluginConstants) => emptyDir(INTERNAL_EDGE_FUNCTIONS_SRC)
export const writeDevEdgeFunction = async ({
INTERNAL_EDGE_FUNCTIONS_SRC = '.netlify/edge-functions',
}: NetlifyPluginConstants) => {
const manifest: FunctionManifest = {
functions: [
{
function: 'next-dev',
name: 'netlify dev handler',
path: '/*',
},
],
version: 1,
}
const edgeFunctionRoot = resolve(INTERNAL_EDGE_FUNCTIONS_SRC)
await emptyDir(edgeFunctionRoot)
await writeJson(join(edgeFunctionRoot, 'manifest.json'), manifest)
await copy(getEdgeTemplatePath('../edge-shared'), join(edgeFunctionRoot, 'edge-shared'))
const edgeFunctionDir = join(edgeFunctionRoot, 'next-dev')
await ensureDir(edgeFunctionDir)
await copyEdgeSourceFile({ edgeFunctionDir, file: 'next-dev.js', target: 'index.js' })
}
/**
* Writes an edge function that routes RSC data requests to the `.rsc` route
*/
export const writeRscDataEdgeFunction = async ({
prerenderManifest,
appPathRoutesManifest,
}: {
prerenderManifest?: PrerenderManifest
appPathRoutesManifest?: Record<string, string>
}): Promise<FunctionManifest['functions']> => {
if (!prerenderManifest || !appPathRoutesManifest) {
return []
}
const staticAppdirRoutes: Array<string> = []
for (const [path, route] of Object.entries(prerenderManifest.routes)) {
if (isAppDirRoute(route.srcRoute, appPathRoutesManifest)) {
staticAppdirRoutes.push(path, route.dataRoute)
}
}
const dynamicAppDirRoutes: Array<string> = []
for (const [path, route] of Object.entries(prerenderManifest.dynamicRoutes)) {
if (isAppDirRoute(path, appPathRoutesManifest)) {
dynamicAppDirRoutes.push(route.routeRegex, route.dataRouteRegex)
}
}
if (staticAppdirRoutes.length === 0 && dynamicAppDirRoutes.length === 0) {
return []
}
const edgeFunctionDir = resolve('.netlify', 'edge-functions', 'rsc-data')
await ensureDir(edgeFunctionDir)
await copyEdgeSourceFile({ edgeFunctionDir, file: 'rsc-data.ts' })
return [
...staticAppdirRoutes.map((path) => ({
function: 'rsc-data',
name: 'RSC data routing',
path,
})),
...dynamicAppDirRoutes.map((pattern) => ({
function: 'rsc-data',
name: 'RSC data routing',
pattern,
})),
]
}
export const getEdgeFunctionPatternForPage = ({
edgeFunctionDefinition,
pageRegexMap,
appPathRoutesManifest,
}: {
edgeFunctionDefinition: EdgeFunctionDefinition
pageRegexMap: Map<string, string>
appPathRoutesManifest?: Record<string, string>
}): string => {
// We don't just use the matcher from the edge function definition, because it doesn't handle trailing slashes
// appDir functions have a name that _isn't_ the route name, but rather the route with `/page` appended
const regexp = pageRegexMap.get(appPathRoutesManifest?.[edgeFunctionDefinition.page] ?? edgeFunctionDefinition.page)
if (regexp) {
return regexp
}
if ('regexp' in edgeFunctionDefinition) {
return edgeFunctionDefinition.regexp.replace(/([^/])\$$/, '$1/?$')
}
// If we need to fall back to the matcher, we need to add an optional trailing slash
return edgeFunctionDefinition.matchers?.[0].regexp.replace(/([^/])\$$/, '$1/?$')
}
/**
* Writes Edge Functions for the Next middleware
*/
// eslint-disable-next-line max-lines-per-function
export const writeEdgeFunctions = async ({
netlifyConfig,
routesManifest,
}: {
netlifyConfig: NetlifyConfig
routesManifest: RoutesManifest
}) => {
const manifest: FunctionManifest = {
functions: [],
version: 1,
}
const edgeFunctionRoot = resolve('.netlify', 'edge-functions')
await emptyDir(edgeFunctionRoot)
const { publish } = netlifyConfig.build
const nextConfigFile = await getRequiredServerFiles(publish)
const nextConfig = nextConfigFile.config
const usesAppDir = nextConfig.experimental?.appDir
await copy(getEdgeTemplatePath('../edge-shared'), join(edgeFunctionRoot, 'edge-shared'))
await writeJSON(join(edgeFunctionRoot, 'edge-shared', 'nextConfig.json'), nextConfig)
await copy(join(publish, 'prerender-manifest.json'), join(edgeFunctionRoot, 'edge-shared', 'prerender-manifest.json'))
if (
!destr(process.env.NEXT_DISABLE_EDGE_IMAGES) &&
!destr(process.env.NEXT_DISABLE_NETLIFY_EDGE) &&
!destr(process.env.DISABLE_IPX)
) {
console.log(
'Using Netlify Edge Functions for image format detection. Set env var "NEXT_DISABLE_EDGE_IMAGES=true" to disable.',
)
const edgeFunctionDir = join(edgeFunctionRoot, 'ipx')
await ensureDir(edgeFunctionDir)
await copyEdgeSourceFile({ edgeFunctionDir, file: 'ipx.ts', target: 'index.ts' })
await copyFile(
join('.netlify', 'functions-internal', '_ipx', 'imageconfig.json'),
join(edgeFunctionDir, 'imageconfig.json'),
)
manifest.functions.push({
function: 'ipx',
name: 'next/image handler',
path: '/_next/image*',
})
}
if (!destr(process.env.NEXT_DISABLE_NETLIFY_EDGE)) {
const rscFunctions = await writeRscDataEdgeFunction({
prerenderManifest: await loadPrerenderManifest(netlifyConfig),
appPathRoutesManifest: await loadAppPathRoutesManifest(netlifyConfig),
})
manifest.functions.push(...rscFunctions)
const middlewareManifest = await loadMiddlewareManifest(netlifyConfig)
if (!middlewareManifest) {
console.error("Couldn't find the middleware manifest")
return
}
let usesEdge = false
for (const middleware of middlewareManifest.sortedMiddleware) {
usesEdge = true
const edgeFunctionDefinition = middlewareManifest.middleware[middleware]
const functionName = sanitizeName(edgeFunctionDefinition.name)
const matchers = generateEdgeFunctionMiddlewareMatchers({
edgeFunctionDefinition,
edgeFunctionRoot,
nextConfig,
})
await writeEdgeFunction({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
functionName,
matchers,
middleware: true,
})
manifest.functions.push(
...matchers.map((matcher) => middlewareMatcherToEdgeFunctionDefinition(matcher, functionName)),
)
}
if (typeof middlewareManifest.functions === 'object') {
// When using the app dir, we also need to check if the EF matches a page
const appPathRoutesManifest = await loadAppPathRoutesManifest(netlifyConfig)
const pageRegexMap = new Map(
[...(routesManifest.dynamicRoutes || []), ...(routesManifest.staticRoutes || [])].map((route) => [
route.page,
route.regex,
]),
)
for (const edgeFunctionDefinition of Object.values(middlewareManifest.functions)) {
usesEdge = true
const functionName = sanitizeName(edgeFunctionDefinition.name)
await writeEdgeFunction({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
functionName,
})
const pattern = getEdgeFunctionPatternForPage({
edgeFunctionDefinition,
pageRegexMap,
appPathRoutesManifest,
})
manifest.functions.push({
function: functionName,
name: edgeFunctionDefinition.name,
pattern,
// cache: "manual" is currently experimental, so we restrict it to sites that use experimental appDir
cache: usesAppDir ? 'manual' : undefined,
})
}
}
if (usesEdge) {
console.log(outdent`
✨ Deploying middleware and functions to ${greenBright`Netlify Edge Functions`} ✨
This feature is in beta. Please share your feedback here: https://ntl.fyi/next-netlify-edge
`)
}
}
await writeJson(join(edgeFunctionRoot, 'manifest.json'), manifest)
}