-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
context.ts
353 lines (314 loc) · 11 KB
/
context.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
import type { AssetBinding } from '../../../build/webpack/loaders/get-module-build-info'
import {
decorateServerError,
getServerError,
} from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { EDGE_UNSUPPORTED_NODE_APIS } from '../../../shared/lib/constants'
import { EdgeRuntime } from 'next/dist/compiled/edge-runtime'
import { readFileSync, promises as fs } from 'fs'
import { validateURL } from '../utils'
import { pick } from '../../../lib/pick'
import { fetchInlineAsset } from './fetch-inline-assets'
import type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'
const WEBPACK_HASH_REGEX =
/__webpack_require__\.h = function\(\) \{ return "[0-9a-f]+"; \}/g
interface ModuleContext {
runtime: EdgeRuntime
paths: Map<string, string>
warnedEvals: Set<string>
}
/**
* For a given path a context, this function checks if there is any module
* context that contains the path with an older content and, if that's the
* case, removes the context from the cache.
*/
export function clearModuleContext(path: string, content: Buffer | string) {
for (const [key, cache] of moduleContexts) {
const prev = cache?.paths.get(path)?.replace(WEBPACK_HASH_REGEX, '')
if (
typeof prev !== 'undefined' &&
prev !== content.toString().replace(WEBPACK_HASH_REGEX, '')
) {
moduleContexts.delete(key)
}
}
}
/**
* A Map of cached module contexts indexed by the module name. It allows
* to have a different cache scoped per module name or depending on the
* provided module key on creation.
*/
const moduleContexts = new Map<string, ModuleContext>()
interface ModuleContextOptions {
moduleName: string
onWarning: (warn: Error) => void
useCache: boolean
env: string[]
distDir: string
edgeFunctionEntry: Pick<EdgeFunctionDefinition, 'assets' | 'wasm'>
}
const pendingModuleCaches = new Map<string, Promise<ModuleContext>>()
function getModuleContextShared(options: ModuleContextOptions) {
let deferredModuleContext = pendingModuleCaches.get(options.moduleName)
if (!deferredModuleContext) {
deferredModuleContext = createModuleContext(options)
pendingModuleCaches.set(options.moduleName, deferredModuleContext)
}
return deferredModuleContext
}
/**
* For a given module name this function will get a cached module
* context or create it. It will return the module context along
* with a function that allows to run some code from a given
* filepath within the context.
*/
export async function getModuleContext(options: ModuleContextOptions): Promise<{
evaluateInContext: (filepath: string) => void
runtime: EdgeRuntime
paths: Map<string, string>
warnedEvals: Set<string>
}> {
let moduleContext = options.useCache
? moduleContexts.get(options.moduleName)
: await getModuleContextShared(options)
if (!moduleContext) {
moduleContext = await createModuleContext(options)
moduleContexts.set(options.moduleName, moduleContext)
}
const evaluateInContext = (filepath: string) => {
if (!moduleContext!.paths.has(filepath)) {
const content = readFileSync(filepath, 'utf-8')
try {
moduleContext?.runtime.evaluate(content)
moduleContext!.paths.set(filepath, content)
} catch (error) {
if (options.useCache) {
moduleContext?.paths.delete(options.moduleName)
}
throw error
}
}
}
return { ...moduleContext, evaluateInContext }
}
/**
* Create a module cache specific for the provided parameters. It includes
* a runtime context, require cache and paths cache.
*/
async function createModuleContext(options: ModuleContextOptions) {
const warnedEvals = new Set<string>()
const warnedWasmCodegens = new Set<string>()
const wasm = await loadWasm(options.edgeFunctionEntry.wasm ?? [])
const runtime = new EdgeRuntime({
codeGeneration:
process.env.NODE_ENV !== 'production'
? { strings: true, wasm: true }
: undefined,
extend: (context) => {
context.process = createProcessPolyfill(options)
context.__next_eval__ = function __next_eval__(fn: Function) {
const key = fn.toString()
if (!warnedEvals.has(key)) {
const warning = getServerError(
new Error(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware`
),
'edge-server'
)
warning.name = 'DynamicCodeEvaluationWarning'
Error.captureStackTrace(warning, __next_eval__)
warnedEvals.add(key)
options.onWarning(warning)
}
return fn()
}
context.__next_webassembly_compile__ =
function __next_webassembly_compile__(fn: Function) {
const key = fn.toString()
if (!warnedWasmCodegens.has(key)) {
const warning = getServerError(
new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Middleware.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server'
)
warning.name = 'DynamicWasmCodeGenerationWarning'
Error.captureStackTrace(warning, __next_webassembly_compile__)
warnedWasmCodegens.add(key)
options.onWarning(warning)
}
return fn()
}
context.__next_webassembly_instantiate__ =
async function __next_webassembly_instantiate__(fn: Function) {
const result = await fn()
// If a buffer is given, WebAssembly.instantiate returns an object
// containing both a module and an instance while it returns only an
// instance if a WASM module is given. Utilize the fact to determine
// if the WASM code generation happens.
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code
const instantiatedFromBuffer = result.hasOwnProperty('module')
const key = fn.toString()
if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {
const warning = getServerError(
new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Middleware.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server'
)
warning.name = 'DynamicWasmCodeGenerationWarning'
Error.captureStackTrace(warning, __next_webassembly_instantiate__)
warnedWasmCodegens.add(key)
options.onWarning(warning)
}
return result
}
const __fetch = context.fetch
context.fetch = async (input, init = {}) => {
const assetResponse = await fetchInlineAsset({
input,
assets: options.edgeFunctionEntry.assets,
distDir: options.distDir,
context,
})
if (assetResponse) {
return assetResponse
}
init.headers = new Headers(init.headers ?? {})
const prevs =
init.headers.get(`x-middleware-subrequest`)?.split(':') || []
const value = prevs.concat(options.moduleName).join(':')
init.headers.set('x-middleware-subrequest', value)
if (!init.headers.has('user-agent')) {
init.headers.set(`user-agent`, `Next.js Middleware`)
}
if (typeof input === 'object' && 'url' in input) {
return __fetch(input.url, {
...pick(input, [
'method',
'body',
'cache',
'credentials',
'integrity',
'keepalive',
'mode',
'redirect',
'referrer',
'referrerPolicy',
'signal',
]),
...init,
headers: {
...Object.fromEntries(input.headers),
...Object.fromEntries(init.headers),
},
})
}
return __fetch(String(input), init)
}
const __Request = context.Request
context.Request = class extends __Request {
constructor(input: URL | RequestInfo, init?: RequestInit | undefined) {
const url =
typeof input !== 'string' && 'url' in input
? input.url
: String(input)
validateURL(url)
super(url, init)
}
}
const __redirect = context.Response.redirect.bind(context.Response)
context.Response.redirect = (...args) => {
validateURL(args[0])
return __redirect(...args)
}
for (const name of EDGE_UNSUPPORTED_NODE_APIS) {
addStub(context, name, options)
}
Object.assign(context, wasm)
return context
},
})
runtime.context.addEventListener('unhandledrejection', decorateUnhandledError)
runtime.context.addEventListener('error', decorateUnhandledError)
return {
runtime,
paths: new Map<string, string>(),
warnedEvals: new Set<string>(),
}
}
async function loadWasm(
wasm: AssetBinding[]
): Promise<Record<string, WebAssembly.Module>> {
const modules: Record<string, WebAssembly.Module> = {}
await Promise.all(
wasm.map(async (binding) => {
const module = await WebAssembly.compile(
await fs.readFile(binding.filePath)
)
modules[binding.name] = module
})
)
return modules
}
function buildEnvironmentVariablesFrom(
keys: string[]
): Record<string, string | undefined> {
const pairs = keys.map((key) => [key, process.env[key]])
const env = Object.fromEntries(pairs)
env.NEXT_RUNTIME = 'edge'
return env
}
function createProcessPolyfill(
options: Pick<ModuleContextOptions, 'env' | 'onWarning'>
) {
const env = buildEnvironmentVariablesFrom(options.env)
const processPolyfill = { env }
const overridenValue: Record<string, any> = {}
for (const key of Object.keys(process)) {
if (key === 'env') continue
Object.defineProperty(processPolyfill, key, {
get() {
emitWarning(`process.${key}`, options)
return overridenValue[key]
},
set(value) {
overridenValue[key] = value
},
enumerable: false,
})
}
return processPolyfill
}
const warnedAlready = new Set<string>()
function addStub(
context: EdgeRuntime['context'],
name: string,
contextOptions: Pick<ModuleContextOptions, 'onWarning'>
) {
Object.defineProperty(context, name, {
get() {
emitWarning(name, contextOptions)
return undefined
},
enumerable: false,
})
}
function emitWarning(
name: string,
contextOptions: Pick<ModuleContextOptions, 'onWarning'>
) {
if (!warnedAlready.has(name)) {
const warning =
new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
warning.name = 'NodejsRuntimeApiInMiddlewareWarning'
contextOptions.onWarning(warning)
console.warn(warning.message)
warnedAlready.add(name)
}
}
function decorateUnhandledError(error: any) {
if (error instanceof Error) {
decorateServerError(error, 'edge-server')
}
}