-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathedge.ts
193 lines (170 loc) · 5.82 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
/* eslint-disable max-lines */
import { promises as fs, existsSync } from 'fs'
import { resolve, join } from 'path'
import type { NetlifyConfig } from '@netlify/build'
import { copyFile, emptyDir, ensureDir, readJSON, readJson, writeJSON, writeJson } from 'fs-extra'
import type { MiddlewareManifest } from 'next/dist/build/webpack/plugins/middleware-plugin'
type EdgeFunctionDefinition = MiddlewareManifest['middleware']['name']
export interface FunctionManifest {
version: 1
functions: Array<
| {
function: string
path: string
}
| {
function: string
pattern: string
}
>
}
export const loadMiddlewareManifest = (netlifyConfig: NetlifyConfig): Promise<MiddlewareManifest | null> => {
const middlewarePath = resolve(netlifyConfig.build.publish, 'server', 'middleware-manifest.json')
if (!existsSync(middlewarePath)) {
return null
}
return readJson(middlewarePath)
}
/**
* 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 bootstrap = /* js */ `
globalThis.process = { env: {...Deno.env.toObject(), NEXT_RUNTIME: 'edge', 'NEXT_PRIVATE_MINIMAL_MODE': '1' } }
globalThis._ENTRIES ||= {}
// Deno defines "window", but naughty libraries think this means it's a browser
delete globalThis.window
`
/**
* 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> = [bootstrap]
for (const file of edgeFunctionDefinition.files) {
const filePath = join(publish, file)
const data = await fs.readFile(filePath, 'utf8')
chunks.push('{', data, '}')
}
const middleware = await fs.readFile(join(publish, `server`, `${edgeFunctionDefinition.name}.js`), 'utf8')
chunks.push(middleware)
const exports = /* js */ `export default _ENTRIES["middleware_${edgeFunctionDefinition.name}"].default;`
chunks.push(exports)
return chunks.join('\n')
}
const copyEdgeSourceFile = ({
file,
target,
edgeFunctionDir,
}: {
file: string
edgeFunctionDir: string
target?: string
}) => fs.copyFile(join(__dirname, '..', '..', 'src', 'templates', 'edge', file), join(edgeFunctionDir, target ?? file))
// Edge functions don't support lookahead expressions
const stripLookahead = (regex: string) => regex.replace('^/(?!_next)', '^/')
const writeEdgeFunction = async ({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
}: {
edgeFunctionDefinition: EdgeFunctionDefinition
edgeFunctionRoot: string
netlifyConfig: NetlifyConfig
}): Promise<{
function: string
pattern: string
}> => {
const name = sanitizeName(edgeFunctionDefinition.name)
const edgeFunctionDir = join(edgeFunctionRoot, name)
const bundle = await getMiddlewareBundle({
edgeFunctionDefinition,
netlifyConfig,
})
await ensureDir(edgeFunctionDir)
await fs.writeFile(join(edgeFunctionDir, 'bundle.js'), bundle)
await copyEdgeSourceFile({
edgeFunctionDir,
file: 'runtime.ts',
target: 'index.ts',
})
await copyEdgeSourceFile({ edgeFunctionDir, file: 'utils.ts' })
return {
function: name,
pattern: stripLookahead(edgeFunctionDefinition.regexp),
}
}
/**
* Writes Edge Functions for the Next middleware
*/
export const writeEdgeFunctions = async (netlifyConfig: NetlifyConfig) => {
const manifest: FunctionManifest = {
functions: [],
version: 1,
}
const edgeFunctionRoot = resolve('.netlify', 'edge-functions')
await emptyDir(edgeFunctionRoot)
if (!process.env.NEXT_DISABLE_EDGE_IMAGES) {
if (!process.env.NEXT_USE_NETLIFY_EDGE) {
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',
path: '/_next/image*',
})
}
if (process.env.NEXT_USE_NETLIFY_EDGE) {
const middlewareManifest = await loadMiddlewareManifest(netlifyConfig)
if (!middlewareManifest) {
console.error("Couldn't find the middleware manifest")
return
}
for (const middleware of middlewareManifest.sortedMiddleware) {
const edgeFunctionDefinition = middlewareManifest.middleware[middleware]
const functionDefinition = await writeEdgeFunction({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
})
manifest.functions.push(functionDefinition)
}
// Older versions of the manifest format don't have the functions field
// No, the version field was not incremented
if (typeof middlewareManifest.functions === 'object') {
for (const edgeFunctionDefinition of Object.values(middlewareManifest.functions)) {
const functionDefinition = await writeEdgeFunction({
edgeFunctionDefinition,
edgeFunctionRoot,
netlifyConfig,
})
manifest.functions.push(functionDefinition)
}
}
}
await writeJson(join(edgeFunctionRoot, 'manifest.json'), manifest)
}
export const updateConfig = async (publish: string) => {
const configFile = join(publish, 'required-server-files.json')
const config = await readJSON(configFile)
config.config.env.NEXT_USE_NETLIFY_EDGE = 'true'
await writeJSON(configFile, config)
}
/* eslint-enable max-lines */