{"version":3,"sources":["../../../../src/server/web/sandbox/context.ts"],"sourcesContent":["import type { AssetBinding } from '../../../build/webpack/loaders/get-module-build-info'\nimport type {\n EdgeFunctionDefinition,\n SUPPORTED_NATIVE_MODULES,\n} from '../../../build/webpack/plugins/middleware-plugin'\nimport type { UnwrapPromise } from '../../../lib/coalesced-function'\nimport { AsyncLocalStorage } from 'async_hooks'\nimport {\n COMPILER_NAMES,\n EDGE_UNSUPPORTED_NODE_APIS,\n} from '../../../shared/lib/constants'\nimport { EdgeRuntime } from 'next/dist/compiled/edge-runtime'\nimport { readFileSync, promises as fs } from 'fs'\nimport { validateURL } from '../utils'\nimport { pick } from '../../../lib/pick'\nimport { fetchInlineAsset } from './fetch-inline-assets'\nimport { runInContext } from 'vm'\nimport BufferImplementation from 'node:buffer'\nimport EventsImplementation from 'node:events'\nimport AssertImplementation from 'node:assert'\nimport UtilImplementation from 'node:util'\nimport AsyncHooksImplementation from 'node:async_hooks'\nimport { intervalsManager, timeoutsManager } from './resource-managers'\nimport { createLocalRequestContext } from '../../after/builtin-request-context'\nimport {\n patchErrorInspectEdgeLite,\n patchErrorInspectNodeJS,\n} from '../../patch-error-inspect'\n\ninterface ModuleContext {\n runtime: EdgeRuntime\n paths: Map\n warnedEvals: Set\n}\n\nlet getServerError: typeof import('../../dev/node-stack-frames').getServerError\nlet decorateServerError: typeof import('../../../shared/lib/error-source').decorateServerError\n\nif (process.env.NODE_ENV === 'development') {\n getServerError = (\n require('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames') as typeof import('../../dev/node-stack-frames')\n ).getServerError\n decorateServerError = (\n require('../../../shared/lib/error-source') as typeof import('../../../shared/lib/error-source')\n ).decorateServerError\n} else {\n getServerError = (error) => error\n decorateServerError = () => {}\n}\n\n/**\n * A Map of cached module contexts indexed by the module name. It allows\n * to have a different cache scoped per module name or depending on the\n * provided module key on creation.\n */\nconst moduleContexts = new Map()\n\nconst pendingModuleCaches = new Map>()\n\n/**\n * Same as clearModuleContext but for all module contexts.\n */\nexport async function clearAllModuleContexts() {\n intervalsManager.removeAll()\n timeoutsManager.removeAll()\n moduleContexts.clear()\n pendingModuleCaches.clear()\n}\n\n/**\n * For a given path a context, this function checks if there is any module\n * context that contains the path with an older content and, if that's the\n * case, removes the context from the cache.\n *\n * This function also clears all intervals and timeouts created by the\n * module context.\n */\nexport async function clearModuleContext(path: string) {\n intervalsManager.removeAll()\n timeoutsManager.removeAll()\n\n const handleContext = (\n key: string,\n cache: ReturnType<(typeof moduleContexts)['get']>,\n context: typeof moduleContexts | typeof pendingModuleCaches\n ) => {\n if (cache?.paths.has(path)) {\n context.delete(key)\n }\n }\n\n for (const [key, cache] of moduleContexts) {\n handleContext(key, cache, moduleContexts)\n }\n for (const [key, cache] of pendingModuleCaches) {\n handleContext(key, await cache, pendingModuleCaches)\n }\n}\n\nasync function loadWasm(\n wasm: AssetBinding[]\n): Promise> {\n const modules: Record = {}\n\n await Promise.all(\n wasm.map(async (binding) => {\n const module = await WebAssembly.compile(\n // @ts-expect-error - Argument of type 'Buffer' is not assignable to parameter of type 'BufferSource'.\n await fs.readFile(binding.filePath)\n )\n modules[binding.name] = module\n })\n )\n\n return modules\n}\n\nfunction buildEnvironmentVariablesFrom(\n injectedEnvironments: Record\n): Record {\n const pairs = Object.keys(process.env).map((key) => [key, process.env[key]])\n const env = Object.fromEntries(pairs)\n for (const key of Object.keys(injectedEnvironments)) {\n env[key] = injectedEnvironments[key]\n }\n env.NEXT_RUNTIME = 'edge'\n return env\n}\n\nfunction throwUnsupportedAPIError(name: string) {\n const error =\n new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.\nLearn more: https://nextjs.org/docs/api-reference/edge-runtime`)\n decorateServerError(error, COMPILER_NAMES.edgeServer)\n throw error\n}\n\nfunction createProcessPolyfill(env: Record) {\n const processPolyfill = { env: buildEnvironmentVariablesFrom(env) }\n const overriddenValue: Record = {}\n\n for (const key of Object.keys(process)) {\n if (key === 'env') continue\n Object.defineProperty(processPolyfill, key, {\n get() {\n if (overriddenValue[key] !== undefined) {\n return overriddenValue[key]\n }\n if (typeof (process as any)[key] === 'function') {\n return () => throwUnsupportedAPIError(`process.${key}`)\n }\n return undefined\n },\n set(value) {\n overriddenValue[key] = value\n },\n enumerable: false,\n })\n }\n return processPolyfill\n}\n\nfunction addStub(context: EdgeRuntime['context'], name: string) {\n Object.defineProperty(context, name, {\n get() {\n return function () {\n throwUnsupportedAPIError(name)\n }\n },\n enumerable: false,\n })\n}\n\nfunction getDecorateUnhandledError(runtime: EdgeRuntime) {\n const EdgeRuntimeError = runtime.evaluate(`Error`)\n return (error: any) => {\n if (error instanceof EdgeRuntimeError) {\n decorateServerError(error, COMPILER_NAMES.edgeServer)\n }\n }\n}\n\nfunction getDecorateUnhandledRejection(runtime: EdgeRuntime) {\n const EdgeRuntimeError = runtime.evaluate(`Error`)\n return (rejected: { reason: typeof EdgeRuntimeError }) => {\n if (rejected.reason instanceof EdgeRuntimeError) {\n decorateServerError(rejected.reason, COMPILER_NAMES.edgeServer)\n }\n }\n}\n\nconst NativeModuleMap = (() => {\n const mods: Record<\n `node:${(typeof SUPPORTED_NATIVE_MODULES)[number]}`,\n unknown\n > = {\n 'node:buffer': pick(BufferImplementation, [\n 'constants',\n 'kMaxLength',\n 'kStringMaxLength',\n 'Buffer',\n 'SlowBuffer',\n ]),\n 'node:events': pick(EventsImplementation, [\n 'EventEmitter',\n 'captureRejectionSymbol',\n 'defaultMaxListeners',\n 'errorMonitor',\n 'listenerCount',\n 'on',\n 'once',\n ]),\n 'node:async_hooks': pick(AsyncHooksImplementation, [\n 'AsyncLocalStorage',\n 'AsyncResource',\n ]),\n 'node:assert': pick(AssertImplementation, [\n 'AssertionError',\n 'deepEqual',\n 'deepStrictEqual',\n 'doesNotMatch',\n 'doesNotReject',\n 'doesNotThrow',\n 'equal',\n 'fail',\n 'ifError',\n 'match',\n 'notDeepEqual',\n 'notDeepStrictEqual',\n 'notEqual',\n 'notStrictEqual',\n 'ok',\n 'rejects',\n 'strict',\n 'strictEqual',\n 'throws',\n ]),\n 'node:util': pick(UtilImplementation, [\n '_extend' as any,\n 'callbackify',\n 'format',\n 'inherits',\n 'promisify',\n 'types',\n ]),\n }\n return new Map(Object.entries(mods))\n})()\n\nexport const requestStore = new AsyncLocalStorage<{\n headers: Headers\n}>()\n\nexport const edgeSandboxNextRequestContext = createLocalRequestContext()\n\n/**\n * Create a module cache specific for the provided parameters. It includes\n * a runtime context, require cache and paths cache.\n */\nasync function createModuleContext(options: ModuleContextOptions) {\n const warnedEvals = new Set()\n const warnedWasmCodegens = new Set()\n const { edgeFunctionEntry } = options\n const wasm = await loadWasm(edgeFunctionEntry.wasm ?? [])\n const runtime = new EdgeRuntime({\n codeGeneration:\n process.env.NODE_ENV !== 'production'\n ? { strings: true, wasm: true }\n : undefined,\n extend: (context) => {\n context.process = createProcessPolyfill(edgeFunctionEntry.env)\n\n Object.defineProperty(context, 'require', {\n enumerable: false,\n value: (id: string) => {\n const value = NativeModuleMap.get(id)\n if (!value) {\n throw TypeError('Native module not found: ' + id)\n }\n return value\n },\n })\n\n if (process.env.NODE_ENV !== 'production') {\n context.__next_log_error__ = function (err: unknown) {\n options.onError(err)\n }\n }\n\n context.__next_eval__ = function __next_eval__(fn: Function) {\n const key = fn.toString()\n if (!warnedEvals.has(key)) {\n const warning = getServerError(\n new Error(\n `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`\n ),\n COMPILER_NAMES.edgeServer\n )\n warning.name = 'DynamicCodeEvaluationWarning'\n Error.captureStackTrace(warning, __next_eval__)\n warnedEvals.add(key)\n options.onWarning(warning)\n }\n return fn()\n }\n\n context.__next_webassembly_compile__ =\n function __next_webassembly_compile__(fn: Function) {\n const key = fn.toString()\n if (!warnedWasmCodegens.has(key)) {\n const warning = getServerError(\n new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),\n COMPILER_NAMES.edgeServer\n )\n warning.name = 'DynamicWasmCodeGenerationWarning'\n Error.captureStackTrace(warning, __next_webassembly_compile__)\n warnedWasmCodegens.add(key)\n options.onWarning(warning)\n }\n return fn()\n }\n\n context.__next_webassembly_instantiate__ =\n async function __next_webassembly_instantiate__(fn: Function) {\n const result = await fn()\n\n // If a buffer is given, WebAssembly.instantiate returns an object\n // containing both a module and an instance while it returns only an\n // instance if a WASM module is given. Utilize the fact to determine\n // if the WASM code generation happens.\n //\n // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code\n const instantiatedFromBuffer = result.hasOwnProperty('module')\n\n const key = fn.toString()\n if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {\n const warning = getServerError(\n new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),\n COMPILER_NAMES.edgeServer\n )\n warning.name = 'DynamicWasmCodeGenerationWarning'\n Error.captureStackTrace(warning, __next_webassembly_instantiate__)\n warnedWasmCodegens.add(key)\n options.onWarning(warning)\n }\n return result\n }\n\n const __fetch = context.fetch\n context.fetch = async (input, init = {}) => {\n const callingError = new Error('[internal]')\n const assetResponse = await fetchInlineAsset({\n input,\n assets: options.edgeFunctionEntry.assets,\n distDir: options.distDir,\n context,\n })\n if (assetResponse) {\n return assetResponse\n }\n\n init.headers = new Headers(init.headers ?? {})\n\n if (!init.headers.has('user-agent')) {\n init.headers.set(`user-agent`, `Next.js Middleware`)\n }\n\n const response =\n typeof input === 'object' && 'url' in input\n ? __fetch(input.url, {\n ...pick(input, [\n 'method',\n 'body',\n 'cache',\n 'credentials',\n 'integrity',\n 'keepalive',\n 'mode',\n 'redirect',\n 'referrer',\n 'referrerPolicy',\n 'signal',\n ]),\n ...init,\n headers: {\n ...Object.fromEntries(input.headers),\n ...Object.fromEntries(init.headers),\n },\n })\n : __fetch(String(input), init)\n\n return await response.catch((err) => {\n callingError.message = err.message\n err.stack = callingError.stack\n throw err\n })\n }\n\n const __Request = context.Request\n context.Request = class extends __Request {\n next?: NextFetchRequestConfig | undefined\n constructor(input: URL | RequestInfo, init?: RequestInit | undefined) {\n const url =\n typeof input !== 'string' && 'url' in input\n ? input.url\n : String(input)\n\n if (typeof input === 'string') {\n validateURL(url)\n super(input, init)\n } else {\n super(input, init)\n validateURL(url)\n }\n this.next = init?.next\n }\n }\n\n const __redirect = context.Response.redirect.bind(context.Response)\n context.Response.redirect = (...args) => {\n validateURL(args[0])\n return __redirect(...args)\n }\n\n for (const name of EDGE_UNSUPPORTED_NODE_APIS) {\n addStub(context, name)\n }\n\n Object.assign(context, wasm)\n\n context.performance = performance\n\n context.AsyncLocalStorage = AsyncLocalStorage\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.setInterval = (...args: Parameters) =>\n intervalsManager.add(args)\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.clearInterval = (interval: number) =>\n intervalsManager.remove(interval)\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.setTimeout = (...args: Parameters) =>\n timeoutsManager.add(args)\n\n // @ts-ignore the timeouts have weird types in the edge runtime\n context.clearTimeout = (timeout: number) =>\n timeoutsManager.remove(timeout)\n\n // Duplicated from packages/next/src/server/after/builtin-request-context.ts\n // because we need to use the sandboxed `Symbol.for`, not the one from the outside\n const NEXT_REQUEST_CONTEXT_SYMBOL = context.Symbol.for(\n '@next/request-context'\n )\n Object.defineProperty(context, NEXT_REQUEST_CONTEXT_SYMBOL, {\n enumerable: false,\n value: edgeSandboxNextRequestContext,\n })\n\n return context\n },\n })\n\n const decorateUnhandledError = getDecorateUnhandledError(runtime)\n runtime.context.addEventListener('error', decorateUnhandledError)\n const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime)\n runtime.context.addEventListener(\n 'unhandledrejection',\n decorateUnhandledRejection\n )\n\n patchErrorInspectEdgeLite(runtime.context.Error)\n // An Error from within the Edge Runtime could also bubble up into the Node.js process.\n // For example, uncaught errors are handled in the Node.js runtime.\n patchErrorInspectNodeJS(runtime.context.Error)\n\n return {\n runtime,\n paths: new Map(),\n warnedEvals: new Set(),\n }\n}\n\ninterface ModuleContextOptions {\n moduleName: string\n onError: (err: unknown) => void\n onWarning: (warn: Error) => void\n useCache: boolean\n distDir: string\n edgeFunctionEntry: Pick\n}\n\nfunction getModuleContextShared(options: ModuleContextOptions) {\n let deferredModuleContext = pendingModuleCaches.get(options.moduleName)\n if (!deferredModuleContext) {\n deferredModuleContext = createModuleContext(options)\n pendingModuleCaches.set(options.moduleName, deferredModuleContext)\n }\n return deferredModuleContext\n}\n\n/**\n * For a given module name this function will get a cached module\n * context or create it. It will return the module context along\n * with a function that allows to run some code from a given\n * filepath within the context.\n */\nexport async function getModuleContext(options: ModuleContextOptions): Promise<{\n evaluateInContext: (filepath: string) => void\n runtime: EdgeRuntime\n paths: Map\n warnedEvals: Set\n}> {\n let lazyModuleContext:\n | UnwrapPromise>\n | undefined\n\n if (options.useCache) {\n lazyModuleContext =\n moduleContexts.get(options.moduleName) ||\n (await getModuleContextShared(options))\n }\n\n if (!lazyModuleContext) {\n lazyModuleContext = await createModuleContext(options)\n moduleContexts.set(options.moduleName, lazyModuleContext)\n }\n\n const moduleContext = lazyModuleContext\n\n const evaluateInContext = (filepath: string) => {\n if (!moduleContext.paths.has(filepath)) {\n const content = readFileSync(filepath, 'utf-8')\n try {\n runInContext(content, moduleContext.runtime.context, {\n filename: filepath,\n })\n moduleContext.paths.set(filepath, content)\n } catch (error) {\n if (options.useCache) {\n moduleContext?.paths.delete(filepath)\n }\n throw error\n }\n }\n }\n\n return { ...moduleContext, evaluateInContext }\n}\n"],"names":["AsyncLocalStorage","COMPILER_NAMES","EDGE_UNSUPPORTED_NODE_APIS","EdgeRuntime","readFileSync","promises","fs","validateURL","pick","fetchInlineAsset","runInContext","BufferImplementation","EventsImplementation","AssertImplementation","UtilImplementation","AsyncHooksImplementation","intervalsManager","timeoutsManager","createLocalRequestContext","patchErrorInspectEdgeLite","patchErrorInspectNodeJS","getServerError","decorateServerError","process","env","NODE_ENV","require","error","moduleContexts","Map","pendingModuleCaches","clearAllModuleContexts","removeAll","clear","clearModuleContext","path","handleContext","key","cache","context","paths","has","delete","loadWasm","wasm","modules","Promise","all","map","binding","module","WebAssembly","compile","readFile","filePath","name","buildEnvironmentVariablesFrom","injectedEnvironments","pairs","Object","keys","fromEntries","NEXT_RUNTIME","throwUnsupportedAPIError","Error","edgeServer","createProcessPolyfill","processPolyfill","overriddenValue","defineProperty","get","undefined","set","value","enumerable","addStub","getDecorateUnhandledError","runtime","EdgeRuntimeError","evaluate","getDecorateUnhandledRejection","rejected","reason","NativeModuleMap","mods","entries","requestStore","edgeSandboxNextRequestContext","createModuleContext","options","warnedEvals","Set","warnedWasmCodegens","edgeFunctionEntry","codeGeneration","strings","extend","id","TypeError","__next_log_error__","err","onError","__next_eval__","fn","toString","warning","captureStackTrace","add","onWarning","__next_webassembly_compile__","__next_webassembly_instantiate__","result","instantiatedFromBuffer","hasOwnProperty","__fetch","fetch","input","init","callingError","assetResponse","assets","distDir","headers","Headers","response","url","String","catch","message","stack","__Request","Request","constructor","next","__redirect","Response","redirect","bind","args","assign","performance","setInterval","clearInterval","interval","remove","setTimeout","clearTimeout","timeout","NEXT_REQUEST_CONTEXT_SYMBOL","Symbol","for","decorateUnhandledError","addEventListener","decorateUnhandledRejection","getModuleContextShared","deferredModuleContext","moduleName","getModuleContext","lazyModuleContext","useCache","moduleContext","evaluateInContext","filepath","content","filename"],"mappings":"AAMA,SAASA,iBAAiB,QAAQ,cAAa;AAC/C,SACEC,cAAc,EACdC,0BAA0B,QACrB,gCAA+B;AACtC,SAASC,WAAW,QAAQ,kCAAiC;AAC7D,SAASC,YAAY,EAAEC,YAAYC,EAAE,QAAQ,KAAI;AACjD,SAASC,WAAW,QA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