next 15.0.4-canary.23 → 15.0.4-canary.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of next might be problematic. Click here for more details.
- package/dist/bin/next +1 -1
- package/dist/build/index.js +2 -2
- package/dist/build/swc/index.js +1 -1
- package/dist/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js +3 -3
- package/dist/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js.map +1 -1
- package/dist/build/webpack-config.js +2 -2
- package/dist/client/app-bootstrap.js +1 -1
- package/dist/client/components/react-dev-overlay/server/{middleware.js → middleware-webpack.js} +1 -1
- package/dist/client/components/react-dev-overlay/server/middleware-webpack.js.map +1 -0
- package/dist/client/index.js +1 -1
- package/dist/compiled/next-server/server.runtime.prod.js.map +1 -1
- package/dist/esm/build/index.js +2 -2
- package/dist/esm/build/swc/index.js +1 -1
- package/dist/esm/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js +1 -1
- package/dist/esm/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js.map +1 -1
- package/dist/esm/build/webpack-config.js +2 -2
- package/dist/esm/client/app-bootstrap.js +1 -1
- package/dist/esm/client/components/react-dev-overlay/server/{middleware.js → middleware-webpack.js} +1 -1
- package/dist/esm/client/components/react-dev-overlay/server/middleware-webpack.js.map +1 -0
- package/dist/esm/client/index.js +1 -1
- package/dist/esm/server/config.js +1 -1
- package/dist/esm/server/dev/hot-reloader-turbopack.js +1 -1
- package/dist/esm/server/dev/hot-reloader-webpack.js +2 -2
- package/dist/esm/server/dev/hot-reloader-webpack.js.map +1 -1
- package/dist/esm/server/image-optimizer.js +2 -2
- package/dist/esm/server/image-optimizer.js.map +1 -1
- package/dist/esm/server/lib/app-info-log.js +1 -1
- package/dist/esm/server/lib/router-utils/setup-dev-bundler.js +1 -1
- package/dist/esm/server/lib/router-utils/setup-dev-bundler.js.map +1 -1
- package/dist/esm/server/lib/start-server.js +1 -1
- package/dist/esm/server/patch-error-inspect.js +1 -1
- package/dist/esm/server/patch-error-inspect.js.map +1 -1
- package/dist/esm/server/web/sandbox/context.js +1 -1
- package/dist/esm/server/web/sandbox/context.js.map +1 -1
- package/dist/esm/server/web/sandbox/sandbox.js +1 -1
- package/dist/esm/server/web/sandbox/sandbox.js.map +1 -1
- package/dist/server/config.js +1 -1
- package/dist/server/dev/hot-reloader-turbopack.js +1 -1
- package/dist/server/dev/hot-reloader-webpack.js +4 -4
- package/dist/server/dev/hot-reloader-webpack.js.map +1 -1
- package/dist/server/image-optimizer.js +2 -2
- package/dist/server/image-optimizer.js.map +1 -1
- package/dist/server/lib/app-info-log.js +1 -1
- package/dist/server/lib/router-utils/setup-dev-bundler.js +5 -5
- package/dist/server/lib/router-utils/setup-dev-bundler.js.map +1 -1
- package/dist/server/lib/start-server.js +1 -1
- package/dist/server/patch-error-inspect.js +2 -2
- package/dist/server/patch-error-inspect.js.map +1 -1
- package/dist/server/web/sandbox/context.js +1 -1
- package/dist/server/web/sandbox/context.js.map +1 -1
- package/dist/server/web/sandbox/sandbox.js +1 -1
- package/dist/server/web/sandbox/sandbox.js.map +1 -1
- package/dist/telemetry/anonymous-meta.js +1 -1
- package/dist/telemetry/events/session-stopped.js +2 -2
- package/dist/telemetry/events/version.js +2 -2
- package/package.json +15 -15
- package/dist/client/components/react-dev-overlay/server/middleware.js.map +0 -1
- package/dist/esm/client/components/react-dev-overlay/server/middleware.js.map +0 -1
- /package/dist/client/components/react-dev-overlay/server/{middleware.d.ts → middleware-webpack.d.ts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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'\n\ninterface ModuleContext {\n runtime: EdgeRuntime\n paths: Map<string, string>\n warnedEvals: Set<string>\n}\n\nlet getServerError: typeof import('../../../client/components/react-dev-overlay/server/middleware').getServerError\nlet decorateServerError: typeof import('../../../shared/lib/error-source').decorateServerError\n\nif (process.env.NODE_ENV === 'development') {\n const middleware = require('../../../client/components/react-dev-overlay/server/middleware')\n getServerError = middleware.getServerError\n decorateServerError =\n require('../../../shared/lib/error-source').decorateServerError\n} else {\n getServerError = (error: Error, _: string) => error\n decorateServerError = (_: Error, __: string) => {}\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<string, ModuleContext>()\n\nconst pendingModuleCaches = new Map<string, Promise<ModuleContext>>()\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<Record<string, WebAssembly.Module>> {\n const modules: Record<string, WebAssembly.Module> = {}\n\n await Promise.all(\n wasm.map(async (binding) => {\n const module = await WebAssembly.compile(\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<string, string>\n): Record<string, string | undefined> {\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<string, string>) {\n const processPolyfill = { env: buildEnvironmentVariablesFrom(env) }\n const overriddenValue: Record<string, any> = {}\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<string>()\n const warnedWasmCodegens = new Set<string>()\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 // Forward subrequest header from incoming request to outgoing request\n const store = requestStore.getStore()\n if (\n store?.headers.has('x-middleware-subrequest') &&\n !init.headers.has('x-middleware-subrequest')\n ) {\n init.headers.set(\n 'x-middleware-subrequest',\n store.headers.get('x-middleware-subrequest') ?? ''\n )\n }\n\n const prevs =\n init.headers.get(`x-middleware-subrequest`)?.split(':') || []\n const value = prevs.concat(options.moduleName).join(':')\n init.headers.set('x-middleware-subrequest', value)\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 validateURL(url)\n super(url, init)\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<typeof setInterval>) =>\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<typeof setTimeout>) =>\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 return {\n runtime,\n paths: new Map<string, string>(),\n warnedEvals: new Set<string>(),\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<EdgeFunctionDefinition, 'assets' | 'wasm' | 'env'>\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<string, string>\n warnedEvals: Set<string>\n}> {\n let lazyModuleContext:\n | UnwrapPromise<ReturnType<typeof getModuleContextShared>>\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","getServerError","decorateServerError","process","env","NODE_ENV","middleware","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","store","getStore","prevs","split","concat","moduleName","join","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","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,QAAQ,WAAU;AACtC,SAASC,IAAI,QAAQ,oBAAmB;AACxC,SAASC,gBA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,KAAK,CAACE,MAAM,CAAC8H;gBAC9B;gBACA,MAAM/I;YACR;QACF;IACF;IAEA,OAAO;QAAE,GAAG6I,aAAa;QAAEC;IAAkB;AAC/C"}
|
|
1
|
+
{"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'\n\ninterface ModuleContext {\n runtime: EdgeRuntime\n paths: Map<string, string>\n warnedEvals: Set<string>\n}\n\nlet getServerError: typeof import('../../../client/components/react-dev-overlay/server/middleware-webpack').getServerError\nlet decorateServerError: typeof import('../../../shared/lib/error-source').decorateServerError\n\nif (process.env.NODE_ENV === 'development') {\n const middleware =\n require('../../../client/components/react-dev-overlay/server/middleware-webpack') as typeof import('../../../client/components/react-dev-overlay/server/middleware-webpack')\n getServerError = middleware.getServerError\n decorateServerError =\n require('../../../shared/lib/error-source').decorateServerError\n} else {\n getServerError = (error: Error, _: string) => error\n decorateServerError = (_: Error, __: string) => {}\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<string, ModuleContext>()\n\nconst pendingModuleCaches = new Map<string, Promise<ModuleContext>>()\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<Record<string, WebAssembly.Module>> {\n const modules: Record<string, WebAssembly.Module> = {}\n\n await Promise.all(\n wasm.map(async (binding) => {\n const module = await WebAssembly.compile(\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<string, string>\n): Record<string, string | undefined> {\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<string, string>) {\n const processPolyfill = { env: buildEnvironmentVariablesFrom(env) }\n const overriddenValue: Record<string, any> = {}\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<string>()\n const warnedWasmCodegens = new Set<string>()\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 // Forward subrequest header from incoming request to outgoing request\n const store = requestStore.getStore()\n if (\n store?.headers.has('x-middleware-subrequest') &&\n !init.headers.has('x-middleware-subrequest')\n ) {\n init.headers.set(\n 'x-middleware-subrequest',\n store.headers.get('x-middleware-subrequest') ?? ''\n )\n }\n\n const prevs =\n init.headers.get(`x-middleware-subrequest`)?.split(':') || []\n const value = prevs.concat(options.moduleName).join(':')\n init.headers.set('x-middleware-subrequest', value)\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 validateURL(url)\n super(url, init)\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<typeof setInterval>) =>\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<typeof setTimeout>) =>\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 return {\n runtime,\n paths: new Map<string, string>(),\n warnedEvals: new Set<string>(),\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<EdgeFunctionDefinition, 'assets' | 'wasm' | 'env'>\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<string, string>\n warnedEvals: Set<string>\n}> {\n let lazyModuleContext:\n | UnwrapPromise<ReturnType<typeof getModuleContextShared>>\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","getServerError","decorateServerError","process","env","NODE_ENV","middleware","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","store","getStore","prevs","split","concat","moduleName","join","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","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,QAAQ,WAAU;AACtC,SAASC,IAAI,QAAQ,oBAAmB;AACxC,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,YAAY,QAAQ,KAAI;AACjC,OAAOC,0BAA0B,cAAa;AAC9C,OAAOC,0BAA0B,cAAa;AAC9C,OAAOC,0BAA0B,cAAa;AAC9C,OAAOC,wBAAwB,YAAW;AAC1C,OAAOC,8BAA8B,mBAAkB;AACvD,SAASC,gBAAgB,EAAEC,eAAe,QAAQ,sBAAqB;AACvE,SAASC,yBAAyB,QAAQ,sCAAqC;AAQ/E,IAAIC;AACJ,IAAIC;AAEJ,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;IAC1C,MAAMC,aACJC,QAAQ;IACVN,iBAAiBK,WAAWL,cAAc;IAC1CC,sBACEK,QAAQ,oCAAoCL,mBAAmB;AACnE,OAAO;IACLD,iBAAiB,CAACO,OAAcC,IAAcD;IAC9CN,sBAAsB,CAACO,GAAUC,MAAgB;AACnD;AAEA;;;;CAIC,GACD,MAAMC,iBAAiB,IAAIC;AAE3B,MAAMC,sBAAsB,IAAID;AAEhC;;CAEC,GACD,OAAO,eAAeE;IACpBhB,iBAAiBiB,SAAS;IAC1BhB,gBAAgBgB,SAAS;IACzBJ,eAAeK,KAAK;IACpBH,oBAAoBG,KAAK;AAC3B;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeC,mBAAmBC,IAAY;IACnDpB,iBAAiB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QwC,UAAU,EAAEmC;IACzC;IAEA,MAAME,gBAAgBF;IAEtB,MAAMG,oBAAoB,CAACC;QACzB,IAAI,CAACF,cAAc9H,KAAK,CAACC,GAAG,CAAC+H,WAAW;YACtC,MAAMC,UAAUtK,aAAaqK,UAAU;YACvC,IAAI;gBACF/J,aAAagK,SAASH,cAAczF,OAAO,CAACtC,OAAO,EAAE;oBACnDmI,UAAUF;gBACZ;gBACAF,cAAc9H,KAAK,CAACgC,GAAG,CAACgG,UAAUC;YACpC,EAAE,OAAOhJ,OAAO;gBACd,IAAIgE,QAAQ4E,QAAQ,EAAE;oBACpBC,iCAAAA,cAAe9H,KAAK,CAACE,MAAM,CAAC8H;gBAC9B;gBACA,MAAM/I;YACR;QACF;IACF;IAEA,OAAO;QAAE,GAAG6I,aAAa;QAAEC;IAAkB;AAC/C"}
|
|
@@ -13,7 +13,7 @@ const FORBIDDEN_HEADERS = [
|
|
|
13
13
|
* tagged with `edge-server` so they can properly be rendered in dev.
|
|
14
14
|
*/ function withTaggedErrors(fn) {
|
|
15
15
|
if (process.env.NODE_ENV === 'development') {
|
|
16
|
-
const { getServerError } = require('../../../client/components/react-dev-overlay/server/middleware');
|
|
16
|
+
const { getServerError } = require('../../../client/components/react-dev-overlay/server/middleware-webpack');
|
|
17
17
|
return (params)=>fn(params).then((result)=>{
|
|
18
18
|
var _result_waitUntil;
|
|
19
19
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/server/web/sandbox/sandbox.ts"],"sourcesContent":["import type { NodejsRequestData, FetchEventResult, RequestData } from '../types'\nimport type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'\nimport type { EdgeRuntime } from 'next/dist/compiled/edge-runtime'\nimport {\n getModuleContext,\n requestStore,\n edgeSandboxNextRequestContext,\n} from './context'\nimport { requestToBodyStream } from '../../body-streams'\nimport { NEXT_RSC_UNION_QUERY } from '../../../client/components/app-router-headers'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport {\n getBuiltinRequestContext,\n type BuiltinRequestContextValue,\n} from '../../after/builtin-request-context'\n\nexport const ErrorSource = Symbol('SandboxError')\n\nconst FORBIDDEN_HEADERS = [\n 'content-length',\n 'content-encoding',\n 'transfer-encoding',\n]\n\ninterface RunnerFnParams {\n name: string\n onError?: (err: unknown) => void\n onWarning?: (warn: Error) => void\n paths: string[]\n request: NodejsRequestData\n useCache: boolean\n edgeFunctionEntry: Pick<EdgeFunctionDefinition, 'assets' | 'wasm' | 'env'>\n distDir: string\n incrementalCache?: any\n serverComponentsHmrCache?: ServerComponentsHmrCache\n}\n\ntype RunnerFn = (params: RunnerFnParams) => Promise<FetchEventResult>\n\n/**\n * Decorates the runner function making sure all errors it can produce are\n * tagged with `edge-server` so they can properly be rendered in dev.\n */\nfunction withTaggedErrors(fn: RunnerFn): RunnerFn {\n if (process.env.NODE_ENV === 'development') {\n const { getServerError } =\n require('../../../client/components/react-dev-overlay/server/middleware') as typeof import('../../../client/components/react-dev-overlay/server/middleware')\n\n return (params) =>\n fn(params)\n .then((result) => ({\n ...result,\n waitUntil: result?.waitUntil?.catch((error) => {\n // TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.\n throw getServerError(error, 'edge-server')\n }),\n }))\n .catch((error) => {\n // TODO: used COMPILER_NAMES.edgeServer instead\n throw getServerError(error, 'edge-server')\n })\n }\n\n return fn\n}\n\nexport async function getRuntimeContext(\n params: Omit<RunnerFnParams, 'request'>\n): Promise<EdgeRuntime<any>> {\n const { runtime, evaluateInContext } = await getModuleContext({\n moduleName: params.name,\n onWarning: params.onWarning ?? (() => {}),\n onError: params.onError ?? (() => {}),\n useCache: params.useCache !== false,\n edgeFunctionEntry: params.edgeFunctionEntry,\n distDir: params.distDir,\n })\n\n if (params.incrementalCache) {\n runtime.context.globalThis.__incrementalCache = params.incrementalCache\n }\n\n if (params.serverComponentsHmrCache) {\n runtime.context.globalThis.__serverComponentsHmrCache =\n params.serverComponentsHmrCache\n }\n\n for (const paramPath of params.paths) {\n evaluateInContext(paramPath)\n }\n return runtime\n}\n\nexport const run = withTaggedErrors(async function runWithTaggedErrors(params) {\n const runtime = await getRuntimeContext(params)\n const subreq = params.request.headers[`x-middleware-subrequest`]\n const subrequests = typeof subreq === 'string' ? subreq.split(':') : []\n\n const MAX_RECURSION_DEPTH = 5\n const depth = subrequests.reduce(\n (acc, curr) => (curr === params.name ? acc + 1 : acc),\n 0\n )\n\n if (depth >= MAX_RECURSION_DEPTH) {\n return {\n waitUntil: Promise.resolve(),\n response: new runtime.context.Response(null, {\n headers: {\n 'x-middleware-next': '1',\n },\n }),\n }\n }\n\n const edgeFunction: (args: {\n request: RequestData\n }) => Promise<FetchEventResult> = (\n await runtime.context._ENTRIES[`middleware_${params.name}`]\n ).default\n\n const cloned = !['HEAD', 'GET'].includes(params.request.method)\n ? params.request.body?.cloneBodyStream()\n : undefined\n\n const KUint8Array = runtime.evaluate('Uint8Array')\n const urlInstance = new URL(params.request.url)\n urlInstance.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n params.request.url = urlInstance.toString()\n\n const headers = new Headers()\n for (const [key, value] of Object.entries(params.request.headers)) {\n headers.set(key, value?.toString() ?? '')\n }\n\n try {\n let result: FetchEventResult | undefined = undefined\n const builtinRequestCtx: BuiltinRequestContextValue = {\n ...getBuiltinRequestContext(),\n // FIXME(after):\n // arguably, this is an abuse of \"@next/request-context\" --\n // it'd make more sense to simply forward its existing value into the sandbox (in `createModuleContext`)\n // but here we're using it to just pass in `waitUntil` regardless if we were running in this context or not.\n waitUntil: params.request.waitUntil,\n }\n await edgeSandboxNextRequestContext.run(builtinRequestCtx, () =>\n requestStore.run({ headers }, async () => {\n result = await edgeFunction({\n request: {\n ...params.request,\n body:\n cloned &&\n requestToBodyStream(runtime.context, KUint8Array, cloned),\n },\n })\n for (const headerName of FORBIDDEN_HEADERS) {\n result.response.headers.delete(headerName)\n }\n })\n )\n\n if (!result) throw new Error('Edge function did not return a response')\n return result\n } finally {\n await params.request.body?.finalize()\n }\n})\n"],"names":["getModuleContext","requestStore","edgeSandboxNextRequestContext","requestToBodyStream","NEXT_RSC_UNION_QUERY","getBuiltinRequestContext","ErrorSource","Symbol","FORBIDDEN_HEADERS","withTaggedErrors","fn","process","env","NODE_ENV","getServerError","require","params","then","result","waitUntil","catch","error","getRuntimeContext","runtime","evaluateInContext","moduleName","name","onWarning","onError","useCache","edgeFunctionEntry","distDir","incrementalCache","context","globalThis","__incrementalCache","serverComponentsHmrCache","__serverComponentsHmrCache","paramPath","paths","run","runWithTaggedErrors","subreq","request","headers","subrequests","split","MAX_RECURSION_DEPTH","depth","reduce","acc","curr","Promise","resolve","response","Response","edgeFunction","_ENTRIES","default","cloned","includes","method","body","cloneBodyStream","undefined","KUint8Array","evaluate","urlInstance","URL","url","searchParams","delete","toString","Headers","key","value","Object","entries","set","builtinRequestCtx","headerName","Error","finalize"],"mappings":"AAGA,SACEA,gBAAgB,EAChBC,YAAY,EACZC,6BAA6B,QACxB,YAAW;AAClB,SAASC,mBAAmB,QAAQ,qBAAoB;AACxD,SAASC,oBAAoB,QAAQ,gDAA+C;AAEpF,SACEC,wBAAwB,QAEnB,sCAAqC;AAE5C,OAAO,MAAMC,cAAcC,OAAO,gBAAe;AAEjD,MAAMC,oBAAoB;IACxB;IACA;IACA;CACD;AAiBD;;;CAGC,GACD,SAASC,iBAAiBC,EAAY;IACpC,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1C,MAAM,EAAEC,cAAc,EAAE,GACtBC,QAAQ;QAEV,OAAO,CAACC,SACNN,GAAGM,QACAC,IAAI,CAAC,CAACC;oBAEMA;uBAFM;oBACjB,GAAGA,MAAM;oBACTC,SAAS,EAAED,2BAAAA,oBAAAA,OAAQC,SAAS,qBAAjBD,kBAAmBE,KAAK,CAAC,CAACC;wBACnC,mGAAmG;wBACnG,MAAMP,eAAeO,OAAO;oBAC9B;gBACF;eACCD,KAAK,CAAC,CAACC;gBACN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ACtD;gBACF;gBACA,KAAK,MAAMqB,cAAcxE,kBAAmB;oBAC1CU,OAAOoC,QAAQ,CAACV,OAAO,CAAC2B,MAAM,CAACS;gBACjC;YACF;QAGF,IAAI,CAAC9D,QAAQ,MAAM,IAAI+D,MAAM;QAC7B,OAAO/D;IACT,SAAU;YACFF;QAAN,QAAMA,wBAAAA,OAAO2B,OAAO,CAACmB,IAAI,qBAAnB9C,sBAAqBkE,QAAQ;IACrC;AACF,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/server/web/sandbox/sandbox.ts"],"sourcesContent":["import type { NodejsRequestData, FetchEventResult, RequestData } from '../types'\nimport type { EdgeFunctionDefinition } from '../../../build/webpack/plugins/middleware-plugin'\nimport type { EdgeRuntime } from 'next/dist/compiled/edge-runtime'\nimport {\n getModuleContext,\n requestStore,\n edgeSandboxNextRequestContext,\n} from './context'\nimport { requestToBodyStream } from '../../body-streams'\nimport { NEXT_RSC_UNION_QUERY } from '../../../client/components/app-router-headers'\nimport type { ServerComponentsHmrCache } from '../../response-cache'\nimport {\n getBuiltinRequestContext,\n type BuiltinRequestContextValue,\n} from '../../after/builtin-request-context'\n\nexport const ErrorSource = Symbol('SandboxError')\n\nconst FORBIDDEN_HEADERS = [\n 'content-length',\n 'content-encoding',\n 'transfer-encoding',\n]\n\ninterface RunnerFnParams {\n name: string\n onError?: (err: unknown) => void\n onWarning?: (warn: Error) => void\n paths: string[]\n request: NodejsRequestData\n useCache: boolean\n edgeFunctionEntry: Pick<EdgeFunctionDefinition, 'assets' | 'wasm' | 'env'>\n distDir: string\n incrementalCache?: any\n serverComponentsHmrCache?: ServerComponentsHmrCache\n}\n\ntype RunnerFn = (params: RunnerFnParams) => Promise<FetchEventResult>\n\n/**\n * Decorates the runner function making sure all errors it can produce are\n * tagged with `edge-server` so they can properly be rendered in dev.\n */\nfunction withTaggedErrors(fn: RunnerFn): RunnerFn {\n if (process.env.NODE_ENV === 'development') {\n const { getServerError } =\n require('../../../client/components/react-dev-overlay/server/middleware-webpack') as typeof import('../../../client/components/react-dev-overlay/server/middleware-webpack')\n\n return (params) =>\n fn(params)\n .then((result) => ({\n ...result,\n waitUntil: result?.waitUntil?.catch((error) => {\n // TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.\n throw getServerError(error, 'edge-server')\n }),\n }))\n .catch((error) => {\n // TODO: used COMPILER_NAMES.edgeServer instead\n throw getServerError(error, 'edge-server')\n })\n }\n\n return fn\n}\n\nexport async function getRuntimeContext(\n params: Omit<RunnerFnParams, 'request'>\n): Promise<EdgeRuntime<any>> {\n const { runtime, evaluateInContext } = await getModuleContext({\n moduleName: params.name,\n onWarning: params.onWarning ?? (() => {}),\n onError: params.onError ?? (() => {}),\n useCache: params.useCache !== false,\n edgeFunctionEntry: params.edgeFunctionEntry,\n distDir: params.distDir,\n })\n\n if (params.incrementalCache) {\n runtime.context.globalThis.__incrementalCache = params.incrementalCache\n }\n\n if (params.serverComponentsHmrCache) {\n runtime.context.globalThis.__serverComponentsHmrCache =\n params.serverComponentsHmrCache\n }\n\n for (const paramPath of params.paths) {\n evaluateInContext(paramPath)\n }\n return runtime\n}\n\nexport const run = withTaggedErrors(async function runWithTaggedErrors(params) {\n const runtime = await getRuntimeContext(params)\n const subreq = params.request.headers[`x-middleware-subrequest`]\n const subrequests = typeof subreq === 'string' ? subreq.split(':') : []\n\n const MAX_RECURSION_DEPTH = 5\n const depth = subrequests.reduce(\n (acc, curr) => (curr === params.name ? acc + 1 : acc),\n 0\n )\n\n if (depth >= MAX_RECURSION_DEPTH) {\n return {\n waitUntil: Promise.resolve(),\n response: new runtime.context.Response(null, {\n headers: {\n 'x-middleware-next': '1',\n },\n }),\n }\n }\n\n const edgeFunction: (args: {\n request: RequestData\n }) => Promise<FetchEventResult> = (\n await runtime.context._ENTRIES[`middleware_${params.name}`]\n ).default\n\n const cloned = !['HEAD', 'GET'].includes(params.request.method)\n ? params.request.body?.cloneBodyStream()\n : undefined\n\n const KUint8Array = runtime.evaluate('Uint8Array')\n const urlInstance = new URL(params.request.url)\n urlInstance.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n params.request.url = urlInstance.toString()\n\n const headers = new Headers()\n for (const [key, value] of Object.entries(params.request.headers)) {\n headers.set(key, value?.toString() ?? '')\n }\n\n try {\n let result: FetchEventResult | undefined = undefined\n const builtinRequestCtx: BuiltinRequestContextValue = {\n ...getBuiltinRequestContext(),\n // FIXME(after):\n // arguably, this is an abuse of \"@next/request-context\" --\n // it'd make more sense to simply forward its existing value into the sandbox (in `createModuleContext`)\n // but here we're using it to just pass in `waitUntil` regardless if we were running in this context or not.\n waitUntil: params.request.waitUntil,\n }\n await edgeSandboxNextRequestContext.run(builtinRequestCtx, () =>\n requestStore.run({ headers }, async () => {\n result = await edgeFunction({\n request: {\n ...params.request,\n body:\n cloned &&\n requestToBodyStream(runtime.context, KUint8Array, cloned),\n },\n })\n for (const headerName of FORBIDDEN_HEADERS) {\n result.response.headers.delete(headerName)\n }\n })\n )\n\n if (!result) throw new Error('Edge function did not return a response')\n return result\n } finally {\n await params.request.body?.finalize()\n }\n})\n"],"names":["getModuleContext","requestStore","edgeSandboxNextRequestContext","requestToBodyStream","NEXT_RSC_UNION_QUERY","getBuiltinRequestContext","ErrorSource","Symbol","FORBIDDEN_HEADERS","withTaggedErrors","fn","process","env","NODE_ENV","getServerError","require","params","then","result","waitUntil","catch","error","getRuntimeContext","runtime","evaluateInContext","moduleName","name","onWarning","onError","useCache","edgeFunctionEntry","distDir","incrementalCache","context","globalThis","__incrementalCache","serverComponentsHmrCache","__serverComponentsHmrCache","paramPath","paths","run","runWithTaggedErrors","subreq","request","headers","subrequests","split","MAX_RECURSION_DEPTH","depth","reduce","acc","curr","Promise","resolve","response","Response","edgeFunction","_ENTRIES","default","cloned","includes","method","body","cloneBodyStream","undefined","KUint8Array","evaluate","urlInstance","URL","url","searchParams","delete","toString","Headers","key","value","Object","entries","set","builtinRequestCtx","headerName","Error","finalize"],"mappings":"AAGA,SAC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F,YAAYK,QAAQ;IAEzC,MAAM5B,UAAU,IAAI6B;IACpB,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAAC7D,OAAO2B,OAAO,CAACC,OAAO,EAAG;QACjEA,QAAQkC,GAAG,CAACJ,KAAKC,CAAAA,yBAAAA,MAAOH,QAAQ,OAAM;IACxC;IAEA,IAAI;QACF,IAAItD,SAAuC8C;QAC3C,MAAMe,oBAAgD;YACpD,GAAG1E,0BAA0B;YAC7B,gBAAgB;YAChB,2DAA2D;YAC3D,wGAAwG;YACxG,4GAA4G;YAC5Gc,WAAWH,OAAO2B,OAAO,CAACxB,SAAS;QACrC;QACA,MAAMjB,8BAA8BsC,GAAG,CAACuC,mBAAmB,IACzD9E,aAAauC,GAAG,CAAC;gBAAEI;YAAQ,GAAG;gBAC5B1B,SAAS,MAAMsC,aAAa;oBAC1Bb,SAAS;wBACP,GAAG3B,OAAO2B,OAAO;wBACjBmB,MACEH,UACAxD,oBAAoBoB,QAAQU,OAAO,EAAEgC,aAAaN;oBACtD;gBACF;gBACA,KAAK,MAAMqB,cAAcxE,kBAAmB;oBAC1CU,OAAOoC,QAAQ,CAACV,OAAO,CAAC2B,MAAM,CAACS;gBACjC;YACF;QAGF,IAAI,CAAC9D,QAAQ,MAAM,IAAI+D,MAAM;QAC7B,OAAO/D;IACT,SAAU;YACFF;QAAN,QAAMA,wBAAAA,OAAO2B,OAAO,CAACmB,IAAI,qBAAnB9C,sBAAqBkE,QAAQ;IACrC;AACF,GAAE"}
|
package/dist/server/config.js
CHANGED
|
@@ -234,7 +234,7 @@ function assignDefaults(dir, userConfig, silent) {
|
|
|
234
234
|
if (((_result_experimental = result.experimental) == null ? void 0 : _result_experimental.allowDevelopmentBuild) && process.env.NODE_ENV !== 'development') {
|
|
235
235
|
throw new Error(`The experimental.allowDevelopmentBuild option requires NODE_ENV to be explicitly set to 'development'.`);
|
|
236
236
|
}
|
|
237
|
-
if (!((_process_env___NEXT_VERSION = "15.0.4-canary.
|
|
237
|
+
if (!((_process_env___NEXT_VERSION = "15.0.4-canary.24") == null ? void 0 : _process_env___NEXT_VERSION.includes('canary')) && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_SKIP_CANARY_CHECK) {
|
|
238
238
|
var _result_experimental7, _result_experimental8, _result_experimental_turbo3, _result_experimental9, _result_experimental10;
|
|
239
239
|
// Prevents usage of certain experimental features outside of canary
|
|
240
240
|
if ((_result_experimental7 = result.experimental) == null ? void 0 : _result_experimental7.ppr) {
|
|
@@ -104,7 +104,7 @@ async function createHotReloaderTurbopack(opts, serverFields, distDir, resetFetc
|
|
|
104
104
|
}
|
|
105
105
|
const hasRewrites = opts.fsChecker.rewrites.afterFiles.length > 0 || opts.fsChecker.rewrites.beforeFiles.length > 0 || opts.fsChecker.rewrites.fallback.length > 0;
|
|
106
106
|
const hotReloaderSpan = (0, _trace.trace)('hot-reloader', undefined, {
|
|
107
|
-
version: "15.0.4-canary.
|
|
107
|
+
version: "15.0.4-canary.24"
|
|
108
108
|
});
|
|
109
109
|
// Ensure the hotReloaderSpan is flushed immediately as it's the parentSpan for all processing
|
|
110
110
|
// of the current `next dev` invocation.
|
|
@@ -29,7 +29,7 @@ _export(exports, {
|
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
31
|
const _webpack = require("next/dist/compiled/webpack/webpack");
|
|
32
|
-
const
|
|
32
|
+
const _middlewarewebpack = require("../../client/components/react-dev-overlay/server/middleware-webpack");
|
|
33
33
|
const _hotmiddleware = require("./hot-middleware");
|
|
34
34
|
const _path = require("path");
|
|
35
35
|
const _entries = require("../../build/entries");
|
|
@@ -260,7 +260,7 @@ class HotReloaderWebpack {
|
|
|
260
260
|
this.previewProps = previewProps;
|
|
261
261
|
this.rewrites = rewrites;
|
|
262
262
|
this.hotReloaderSpan = (0, _trace.trace)('hot-reloader', undefined, {
|
|
263
|
-
version: "15.0.4-canary.
|
|
263
|
+
version: "15.0.4-canary.24"
|
|
264
264
|
});
|
|
265
265
|
// Ensure the hotReloaderSpan is flushed immediately as it's the parentSpan for all processing
|
|
266
266
|
// of the current `next dev` invocation.
|
|
@@ -1129,13 +1129,13 @@ class HotReloaderWebpack {
|
|
|
1129
1129
|
...this.config.onDemandEntries
|
|
1130
1130
|
});
|
|
1131
1131
|
this.middlewares = [
|
|
1132
|
-
(0,
|
|
1132
|
+
(0, _middlewarewebpack.getOverlayMiddleware)({
|
|
1133
1133
|
rootDirectory: this.dir,
|
|
1134
1134
|
clientStats: ()=>this.clientStats,
|
|
1135
1135
|
serverStats: ()=>this.serverStats,
|
|
1136
1136
|
edgeServerStats: ()=>this.edgeServerStats
|
|
1137
1137
|
}),
|
|
1138
|
-
(0,
|
|
1138
|
+
(0, _middlewarewebpack.getSourceMapMiddleware)({
|
|
1139
1139
|
clientStats: ()=>this.clientStats,
|
|
1140
1140
|
serverStats: ()=>this.serverStats,
|
|
1141
1141
|
edgeServerStats: ()=>this.edgeServerStats
|